Authority check with Express.js

Viewed 50

I have a system to do with express.js, but I had difficulty. I want to do something like this.

Middleware;

module.exports = {

AuthorityCheck: function(req, res, next) {
//console.log(/*Where I get the roles*/)
//
}

}

Routes;

routes.get('/admin', AuthorityCheck['role','role2'], (req, res, next) => {
res.render('admin/index.html')
})

How do I get the roles given in AuthorityCheck? Please help me.

1 Answers

You can make AuthorityCheck return another function that closes over the two role arguments, then when you use the middleware, pass your roles to your function. Here I am using arrow functions to make the syntax a little more concise, but you can use regular function expressions if you wish:

module.exports = {
  AuthorityCheck: (role1, role2) => (req, res, next) => {
    console.log(role1, role2);
  }
}

And to use it, call your AuthorityCheck function by passing it the roles, which will return your middleware function that has access to those roles:

routes.get('/admin', AuthorityCheck('role','role2'), (req, res, next) => {

If you want to be able to pass in N roles into your AuthorityCheck function and not just two like in the above example, you can use the rest parameter syntax, where roles will now be an array of all the arguments passed into the AuthorityCheck function:

AuthorityCheck: (...roles) => (req, res, next) => {
Related