node.js - 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) => {})
推荐阅读
- javascript - 本地机器上的 Nodejs webhook 服务器
- mockito - Mockito doNothing with Mockito.mockStatic
- microsoft-graph-api - 使用 Microsoftgraph 的威胁评估请求的 RestAPI 问题
- mysql - 从重复值中选择行,其中字段从未更改
- assembly - EMU8086 将 32 位数除以 16 位数给出意外的 0 余数
- html - 如何在 Power BI 中显示 HTML 页面
- javascript - 在 highcharts 上绘制数据和时区反应
- awk - 当条件为真时从另一个文件添加行
- c# - 如何将 url 重定向到特定端点
- c++ - 如何获取比例因子以获得真实的屏幕分辨率?