Install Middleware – Step 4

Install Middleware – Step 4

Step 4: -Install Middleware

Middleware=>auth.js

const jwt = require('jsonwebtoken');
const asyncHandler = require('./async');
const ErrorResponse = require('../util/errorResponse');
const user = require('../models/login');

//Protect routes

exports.protect = asyncHandler(async(req,res,next)=>{
    let token;
    if(
        req.headers.authorization &&
        req.headers.authorization.startsWith('Bearer'))
    {
        token = req.headers.authorization.split(' ')[1];

    }
    // else if(req.cookies.token)
    // {
    //     token =req.cookies.token
    // }
    //MAke sure token exists
    if(!token){
        return next(new ErrorResponse('Not authorize to access ',401))
    }
    try{
       //verify Token
       const decoded = jwt.verify(token,process.env.JWT_SECRET)
        console.log(decoded);
        req.user = await user.findById(decoded.id);
        next();
    }
    catch(err)
    {
return next(new ErrorResponse('Not authorize to access ',401))
    }
});

//Grant access to specific role

exports.authorize = (...roles)=>{
 return(req,res,next)=>{
     if(!roles.includes(req.user.role))
     {
         return next(new ErrorResponse(`user role${req.user.role} is not authorize tp access the route`,403))
     }
     next();
 }
}

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*