'i am working on authorization and it shows error Cannot read property 'role' of null"

i am working on authorization and it shows error Cannot read property 'role' of null"

my authorization code:

   exports.authorizeRoles = (roles) => {
        return (req, res, next) => {
            user = req.user.role;
    
             isAllowed = false;
          
            user.roles.map((role) => {
          if (roles.includes(role)) {
            isAllowed = true;
          }
            });
            
       if (!isAllowed)
          return res.status(401).json({
            status: "failed",
            message: " You are not allowed to access this",
          });
    
        next();
      };
    };

route code:

router.route('/product').get(isAuthenticatedUser, authorizeRoles("admin"), getAllProducts)

error : Cannot read property 'role' of null" please help me..!



Solution 1:[1]

is user object coming in your req try console on it

 exports.authorizeRoles = (roles) => {
        return (req, res, next) => {
            console.log(req.user)
            user = req.user.role;
    
             isAllowed = false;
          
            user.roles.map((role) => {
          if (roles.includes(role)) {
            isAllowed = true;
          }
            });
            
       if (!isAllowed)
          return res.status(401).json({
            status: "failed",
            message: " You are not allowed to access this",
          });
    
        next();
      };
    };

if you are passing it in query it should be coming in req.query field

Solution 2:[2]

In the isAuthenticatedUser Method Check whether you are recieving the user by console.log(req.user); and if you are getting null or Undefined then the token you are decoding must get the right id

example: const decodedData = jwt.verify(token, process.env.JWT_SECRET);

req.user = await User.findById(decodedData.id);

console.log(req.user);

So if in the above code, if you got right id in findById(decodeData.id); then you will be error free!! and if you still got error, try to console the decodeData, and req.user and check where you are missing

the decodeData should get the right Key, check for spelling in the decodeData.id it should not decodeData._id

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Smriti Shikha
Solution 2 Anuj Verma