kindacoder
kindacoder

Reputation: 173

Middleware Called before any request in ExpressJS

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.

Upvotes: 0

Views: 612

Answers (1)

Sheldon Oliveira
Sheldon Oliveira

Reputation: 1005

just because in each route you are executing the permit() method, inside of that you are executing this block before return your middleware function:

const isAllowed = role => allowed.indexOf(role) > -1;
    console.log(isAllowed)
    // return a middleware

But for sure that the content for this function return (req, res, next) => { are gonna be executed as the middleware purpose when you execute the route.

Upvotes: 1

Related Questions