首页 > 解决方案 > Express 中间件:只允许管理员或版主访问

问题描述

我希望一条路线只能由版主或管理员访问。我试图在路由上应用数组中间件。但是,如果一个中间件无法应用,它只会拒绝访问。

所以,假设我是管理员或版主,我可以访问/store-detail.

但是在这里,如果我是管理员,我将无法访问它,因为它也会检查版主。

这里的中间件adminmoderator正在应用。

我希望它适用adminmoderator
我怎样才能只应用其中一个?
这样只有管理员或版主才能访问它。
verify中间件是验证 jwt 令牌。
路由器

router.post('/store-detail', [verify, admin, moderator], async (req, res) => {
    //validate data
}}

中间件

const User = require('../models').User

module.exports = async function (req, res, next) { 
    // 401 Unauthorized
    const user = await User.findOne({ where: { id : req.user.id}})
    if(user.role !== 'moderator') return res.status(403).send({error: { status:403, message:'Access denied.'}});
    next();
  }
const User = require('../models').User

module.exports = async function (req, res, next) { 
    // 401 Unauthorized
    const user = await User.findOne({ where: { id : req.user.id}})
    if(user.role !== 'admin') return res.status(403).send({error: { status:403, message:'Access denied.'}});
    next();
  }

标签: node.jsexpress

解决方案


中间件是连续执行的,所以第一个拒绝访问的中间件会发送一个错误。我建议创建一个接受参数的中间件:

module.exports = function hasRole(roles) {
  return async function(req, res, next) {
    const user = await User.findOne({ where: { id: req.user.id } });
    if (!user || !roles.includes(user.role)) {
      return res.status(403).send({error: { status:403, message:'Access denied.'}});
    }
    next();
  }
}

并像这样使用中间件:

router.post('/store-detail', verify, hasRole(['admin', 'moderator']), async (req, res) => {})

推荐阅读