Creating a expressjs middleware that accepts parameters

前端 未结 5 2102
自闭症患者
自闭症患者 2020-12-07 10:28

I am trying to create a middleware that can accept parameters. How can this be done?

example

app.get(\'/hasToBeAdmin\', HasRole(\'Admin\'), function(         


        
相关标签:
5条回答
  • 2020-12-07 11:18
    app.get('/hasToBeAdmin', (req, res, next) => {
      hasRole(req, res, next, 'admin');
    }, (req,res) => { 
        // regular route 
    });
    
    const hasRole = (req, res, next, role) => {
       if(role != user.role){
          res.redirect('/NotInRole');
       }
       next();
    };
    
    0 讨论(0)
  • 2020-12-07 11:19

    Alternatively if you do not have too many cases or if role is NOT a string:

    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) {
    
    })
    
    0 讨论(0)
  • 2020-12-07 11:23

    If you have various permissions levels you could structure them like this:

    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();
      }
    }
    
    0 讨论(0)
  • 2020-12-07 11:24
    function HasRole(role) {
      return function(req, res, next) {
        if (role !== req.user.role) res.redirect(...);
        else next();
      }
    }
    

    I also want to make sure that I don't make multiple copies of the same function:

    function HasRole(role) {
      return HasRole[role] || (HasRole[role] = function(req, res, next) {
        if (role !== req.user.role) res.redirect(...);
        else next();
      })
    }
    
    0 讨论(0)
  • 2020-12-07 11:33

    I use this solution. I recieve a jwt token in body req, and get role information from there

    //roleMiddleware.js
    
    const checkRole = role => {
        
        return (req, res, next) => {
            if (req.role == role) {
                console.log(`${role} role granted`)
                next()
            } else {
                res.status(401).send({ result: 'error', message: `No ${role} permission granted` })
            }
        }
    }
    
    module.exports = { checkRole }
    

    So first I use auth middleware to know if is a valid user, and then the role middleware to know if user have access to the api route

    // router.js
    
    router.post('/v1/something-protected', requireAuth, checkRole('commercial'), (req, res) => {
        // do what you want...
    })
    

    I hope to be useful

    0 讨论(0)
提交回复
热议问题