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
1// index.js
2
3const express = require('express');
4const jwt = require('jsonwebtoken');
5
6const app = express();
7
8// generate token for another API to use in req.header
9app.post('/login', (req, res) => {
10 const user = {
11 id: 1,
12 username: 'abhishek',
13 email: "abhishek@gmail.com"
14 }
15 let token = jwt.sign({ user: user }, 'shhhhh');
16 res.send(token);
17})
18
19// verifyToken is a function that is used for check in API that token exist or not
20// it can be put in between n number of API to check that authoriZed user loggedin or not.
21app.get('/api', verifyToken, (req, res) => {
22 try {
23 jwt.verify(req.token, 'shhhhh', (error, authData) => {
24 if (error) {
25 res.send("not logged in")
26 }
27 res.json({
28 message: "post Created",
29 authData
30 })
31 })
32 } catch (error) {
33 res.send(error)
34 }
35})
36
37// This funtion is middleware.
38function verifyToken(req, res, next) {
39 try {
40 const bearerHeader = req.headers['authorization'];
41 if (typeof bearerHeader !== 'undefined') {
42 const bearerToken = bearerHeader.split(' ')[1];
43 req.token = bearerToken;
44 next();
45 }
46 else {
47 res.send("Not logged-in")
48 }
49 }
50 catch {
51 res.send("something went wrong")
52 }
53}
54
55app.listen(3000, () => {
56 console.log("server is runing")
57})
58
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}
1// JWT MIDDLEWARE
2const jwt = require('jsonwebtoken')
3const httpError = require('http-errors')
4
5module.exports = (req, res, next) => {
6 try {
7 const tokenHeader = req.headers.authorization.split('Bearer ')[1]
8 const decoded = jwt.verify(tokenHeader, process.env.ACCESS_TOKEN_SECRET)
9 req.user = decoded
10 next()
11 } catch (err) {
12 next(httpError(401))
13 }
14}
15
16// ROUTE LOGIN
17app.get('/protect', authJwt, (req, res) => {
18 console.log(req.user)
19 res.send('aim in proteced route')
20})
21
22app.post('/login', (req, res) => {
23 const bodyPayload = {
24 id: Date.now(),
25 username: req.body.username
26 }
27 const token = signAccessToken(res, bodyPayload)
28 return res.status(200).json(token)
29})
30
31app.post('/refresh-token', (req, res) => {
32 const refreshToken = signRefreshToken(req)
33 res.status(200).json(refreshToken)
34 res.end()
35})
36
37// JWT HELPER
38const jwt = require('jsonwebtoken')
39const httpError = require('http-errors')
40
41exports.signAccessToken = (res, payload) => {
42 try {
43 if (payload) {
44 const accessToken = jwt.sign({ ...payload }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
45 const refreshToken = jwt.sign({ ...payload }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
46 res.cookie('refreshToken', `${refreshToken}`, { expired: 86400 * 90 })
47 return { accessToken, refreshToken }
48 }
49 } catch (err) {
50 return httpError(500, err)
51 }
52}
53
54exports.signRefreshToken = (req) => {
55 try {
56 const getToken = req.cookies.refreshToken
57 if (getToken) {
58 const { id, username } = jwt.verify(getToken, process.env.REFRESH_TOKEN_SECRET)
59 const accesssToken = jwt.sign({ id, username }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
60 return { accesssToken }
61 }
62 } catch (err) {
63 return httpError(401, err)
64 }
65}
66
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