gpt4 book ai didi

node.js - Express 中间件 : allow access to only admin or moderator

转载 作者:搜寻专家 更新时间:2023-10-31 23:33:46 25 4
gpt4 key购买 nike

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

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

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

这里 中间件 adminmoderator 都被应用了。

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

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) => {})

关于node.js - Express 中间件 : allow access to only admin or moderator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58301501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com