我正在尝试创建一个可以接受参数的中间件.如何才能做到这一点?
例
app.get('/hasToBeAdmin', HasRole('Admin'), function(req,res){
})
HasRole = function(role, req, res, next){
if(role != user.role){
res.redirect('/NotInRole);
}
next();
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*Ong 128
function HasRole(role) {
return function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
}
}
Run Code Online (Sandbox Code Playgroud)
我还想确保我不会制作相同功能的多个副本:
function HasRole(role) {
return HasRole[role] || (HasRole[role] = function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
})
}
Run Code Online (Sandbox Code Playgroud)
小智 11
我使用这个解决方案。我在 body req 中收到一个 jwt 令牌,并从那里获取角色信息
//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 }
Run Code Online (Sandbox Code Playgroud)
所以首先我使用 auth 中间件来了解是否是有效用户,然后使用角色中间件来了解用户是否有权访问 api 路由
// router.js
router.post('/v1/something-protected', requireAuth, checkRole('commercial'), (req, res) => {
// do what you want...
})
Run Code Online (Sandbox Code Playgroud)
我希望有用
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();
};
Run Code Online (Sandbox Code Playgroud)
或者,如果您没有太多案例或角色不是字符串:
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) {
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28374 次 |
| 最近记录: |