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
Looks like you misspelled the method on the array.
Try using
roles.includes('admin')
instead ofroles.include('admin')
and It should work as expected.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.if admin is part of your schema,you can just check if isAdmin is in the request body
then in your route