node.js-创建一个接受参数的expressjs中间件

我正在尝试创建一个可以接受参数的中间件。 如何才能做到这一点?

app.get('/hasToBeAdmin', HasRole('Admin'), function(req,res){

})

HasRole = function(role, req, res, next){
   if(role != user.role){
      res.redirect('/NotInRole);
   }

   next();
}
Vartan Arabyan asked 2019-10-09T08:59:43Z
4个解决方案
114 votes
function HasRole(role) {
  return function(req, res, next) {
    if (role !== req.user.role) res.redirect(...);
    else next();
  }
}

我还想确保我不制作同一功能的多个副本:

function HasRole(role) {
  return HasRole[role] || (HasRole[role] = function(req, res, next) {
    if (role !== req.user.role) res.redirect(...);
    else next();
  })
}
Jonathan Ong answered 2019-10-09T08:59:54Z
2 votes

或者,如果您没有太多的情况或角色不是字符串:

function HasRole(role) {
  return function(req, res, next) {
    if (role !== req.user.role) res.redirect(...);
    else next();
  })
}

var middlware_hasRoleAdmin = HasRole('admin'); //define router only once

app.get('/hasToBeAdmin', middlware_hasRoleAdmin, function(req,res){

})
zevero answered 2019-10-09T09:00:17Z
2 votes
app.get('/hasToBeAdmin', function(req, res, next){
  hasRole(req, res, next, 'admin');
}, function(req,res){ // regular route });

var hasRole = function(req, res, next, role){
   if(role != user.role){
      res.redirect('/NotInRole');
   }
   next();
};
chovy answered 2019-10-09T09:00:34Z
1 votes

如果您具有各种权限级别,则可以像下面这样构造它们:

const LEVELS = Object.freeze({
  basic: 1,
  pro: 2,
  admin: 3
});

/**
 *  Check if user has the required permission level
 */
module.exports = (role) => {
  return (req, res, next) => {
    if (LEVELS[req.user.role] < LEVELS[role]) return res.status(401).end();
    return next();
  }
}
walteronassis answered 2019-10-09T09:00:58Z
translate from https://stackoverflow.com:/questions/12737148/creating-a-expressjs-middleware-that-accepts-parameters