I am developing a NodeJS Api and having some issues with middlewares. routes are accessible to user based on their roles and a role could be Admin or superAdmin. My permission middleware looks like this:
permission.js
// middleware for doing role-based permissions
const { getRoleName } = require('../../constants/roles');
module.exports = function permit(...allowed) {
const isAllowed = role => allowed.indexOf(role) > -1;
console.log(isAllowed)
// return a middleware
return (req, res, next) => {
//findRole Name
if (req.user && isAllowed(getRoleName[req.user.role]))
next(); // role is allowed, so continue on the next middleware
else {
res.error({ code: 403, message: 'Forbidden', errors: ['Permission Denied'] }); // user is forbidden
}
}
}
I also have an authentication middleware which attaches logged in user to req.user
.
I am using this permission-based middleware into my routes Like this.
records.js
const permit = require("../middlewares/permissions/permission");
router.get("/", permit("superAdmin"), getAllRecords);
router.get("/route1", permit("admin"), getRouteOneRecords);
router.get("/route2", permit("admin","superAdmin"), getRouteTwoRecords);
Now the problem is when my app runs all the roles are printing without making any request, console.log(isAllowed), this line in permission.js is printing the roles without any request made to any of the routes.
I wonder why this is happening, even before making a request to the route.