Express中间件:仅允许访问管理员或主持人
我希望仅管理员或管理员可以访问路由。我试图在路由上应用数组中间件。但是,如果一个中间件无法应用,它只是拒绝访问。因此,假设我是管理员或主持人,我可以访问/store-detail
。但是在这里,如果我是管理员,我将无法访问它,因为它也会检查主持人。此处同时使用中间件admin
和moderator
。我希望它应用admin
或moderator
。我怎样才能只使用其中之一?这样,只有管理员或主持人才能访问它。[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();
}
回答如下:中间件是连续执行的,因此第一个拒绝访问的中间件会发送错误。我建议创建一个可以接受参数的中间件:
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) => {})