1var jwt = require("jsonwebtoken");
2const config = require("config"); // store jwt token seret in it.....
3const { check, validationResult } = require("express-validator"); //validater fields
4
5module.exports = (req, res, next) => {
6 //Get Token from header
7
8 const token = req.header("x-auth-token");
9
10 //Check if not token
11
12 if (!token) {
13 return res.status(401).json({ msg: "No token ,authorized" });
14 }
15
16 //Verify Token
17 try {
18 const decoded = jwt.verify(token, config.get("jwtToken"));
19 req.user = decoded.user;
20 console.log(req.user);
21 next();
22 } catch (error) {
23 res.status(401).json({ msg: "Token is not valid" });
24 }
25};
26
27
28//Controller------
29
30module.exports.Login = async (req, res) => {
31 const errors = validationResult(req);
32 if (!errors.isEmpty()) {
33 return res.status(400).json({ errors: errors.array() });
34 }
35 const { Email, Phone_No, Password } = req.body;
36 try {
37 //See if user exists
38 let user = await User.findOne({Emai});
39
40 if (!user) {
41 res.status(400).json({ msg: "Invalid Credentials !" });
42 }
43
44 //Match password
45 const isMatch = await bcrypt.compare(Password, user.Password);
46
47 if (!isMatch) {
48 res.status(400).json({ msg: "Invalid Password !" });
49 }
50 //Jwt Token
51 const payload = {
52 user: {
53 id: user.id,
54 },
55 };
56 jwt.sign(
57 payload,
58 config.get("jwtToken"), { expiresIn: 360000 },
59 (err, token) => {
60 if (err) throw err;
61 res.json({ msg: "Login success", token });
62 }
63 );
64 } catch (err) {
65 console.error(err.message);
66 res.status(500).send("server error");
67 }
68};
69
70//reactjs side
71
72import axios from "axios";
73import JwtDecode from "jwt-decode";
74const setAuthToken = () => {
75 const token = window.localStorage.getItem("token");
76 console.log("Token get", token);
77 if (token) {
78 // Apply authorization token to every request if logged in
79 axios.defaults.headers.common["x-auth-token"] = token;
80 } else {
81 // Delete auth header
82 delete axios.defaults.headers.common["x-auth-token"];
83 }
84};
85
86export default setAuthToken;
87
88
89export function getDetails (token){
90 try{
91 return JwtDecode(token);
92 }catch(e){
93 console.error(e);
94 }
95}
96
1const jwt = require("jsonwebtoken")
2
3const jwtKey = "my_secret_key"
4const jwtExpirySeconds = 300
5
6const users = {
7 user1: "password1",
8 user2: "password2",
9}
10
11const signIn = (req, res) => {
12 // Get credentials from JSON body
13 const { username, password } = req.body
14 if (!username || !password || users[username] !== password) {
15 // return 401 error is username or password doesn't exist, or if password does
16 // not match the password in our records
17 return res.status(401).end()
18 }
19
20 // Create a new token with the username in the payload
21 // and which expires 300 seconds after issue
22 const token = jwt.sign({ username }, jwtKey, {
23 algorithm: "HS256",
24 expiresIn: jwtExpirySeconds,
25 })
26 console.log("token:", token)
27
28 // set the cookie as the token string, with a similar max age as the token
29 // here, the max age is in milliseconds, so we multiply by 1000
30 res.cookie("token", token, { maxAge: jwtExpirySeconds * 1000 })
31 res.end()
32}
1var jwt = require("jsonwebtoken");
2const config = require("config"); // store jwt token seret in it.....
3const { check, validationResult } = require("express-validator"); //validater fields
4
5module.exports = (req, res, next) => {
6 //Get Token from header
7
8 const token = req.header("x-auth-token");
9
10 //Check if not token
11
12 if (!token) {
13 return res.status(401).json({ msg: "No token ,authorized" });
14 }
15
16 //Verify Token
17 try {
18 const decoded = jwt.verify(token, config.get("jwtToken"));
19 req.user = decoded.user;
20 console.log(req.user);
21 next();
22 } catch (error) {
23 res.status(401).json({ msg: "Token is not valid" });
24 }
25};
26
27
28//Controller------
29
30module.exports.Login = async (req, res) => {
31 const errors = validationResult(req);
32 if (!errors.isEmpty()) {
33 return res.status(400).json({ errors: errors.array() });
34 }
35 const { Email, Phone_No, Password } = req.body;
36 try {
37 //See if user exists
38 let user = await User.findOne({Emai});
39
40 if (!user) {
41 res.status(400).json({ msg: "Invalid Credentials !" });
42 }
43
44 //Match password
45 const isMatch = await bcrypt.compare(Password, user.Password);
46
47 if (!isMatch) {
48 res.status(400).json({ msg: "Invalid Password !" });
49 }
50 //Jwt Token
51 const payload = {
52 user: {
53 id: user.id,
54 },
55 };
56 jwt.sign(
57 payload,
58 config.get("jwtToken"), { expiresIn: 360000 },
59 (err, token) => {
60 if (err) throw err;
61 res.json({ msg: "Login success", token });
62 }
63 );
64 } catch (err) {
65 console.error(err.message);
66 res.status(500).send("server error");
67 }
68};
69
1jwt.sign({ exp: Math.floor(Date.now() / 1000) + (60 * 60), data: 'foobar'}, 'secret');