skip to Main Content

I am trying to write a middleware that checks if the user that is trying to retrieve the data of all users is an admin or not, for testing purpose I have manually passed an array to isAuthorized function.

userRouter.use(isAuthorized(['admin']));
userRouter
.route('/')
.get(getAllUsers);

The isAuthorized function goes as follows:

module.exports.isAuthorized = function isAuthorized(roles) { 
    return function(req,res,next) {
        try{
            if(roles.include('admin')) {
                next();
            }
            else {
                res.status(401).json({
                    message:"User not authorized"
                });
            }
        }
        catch(error) {
            return res.json({
                message: error.message
            });
        }
    }
}

I am getting an error :
roles.include is not a function

Please Help!!

I tried googling same error and looked up previously posted solutions on stackoverflow and other websies, but none of them worked.

3

Answers


  1. Looks like you misspelled the method on the array.
    Try using roles.includes('admin') instead of roles.include('admin') and It should work as expected.

    Login or Signup to reply.
  2. The correct name of the method you are trying to call is .includes(). You may want to look up the documentation for array methods to make sure you’re using the correct method and to look up any unclear behaviour.

    Login or Signup to reply.
  3. if admin is part of your schema,you can just check if isAdmin is in the request body

    module.exports = function (req, res, next) {
        if (!req.body.isAdmin ) {
            return res.status(401).json({ success: false, message: "Sorry, you need admin access for this route" })
          }
          next()
    
    };
    

    then in your route

    const isAdmin = require("../middelwares");
    
    userRouter.use(isAdmin);
    userRouter
    .route('/')
    .get(getAllUsers);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search