我正在尝试创建一个可以接受参数的中间件。怎么办呢?
例如
app.get('/hasToBeAdmin', HasRole('Admin'), function(req,res){
})
HasRole = function(role, req, res, next){
if(role != user.role){
res.redirect('/NotInRole);
}
next();
}
答案 0 :(得分:118)
function HasRole(role) {
return function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
}
}
我还想确保我不会制作相同功能的多个副本:
function HasRole(role) {
return HasRole[role] || (HasRole[role] = function(req, res, next) {
if (role !== req.user.role) res.redirect(...);
else next();
})
}
答案 1 :(得分:4)
app.get('/hasToBeAdmin', function(req, res, next){
hasRole(req, res, next, 'admin');
}, function(req,res){ // regular route });
var hasRole = function(req, res, next, role){
if(role != user.role){
res.redirect('/NotInRole');
}
next();
};
答案 2 :(得分:2)
或者,如果您没有太多案例或者角色不是字符串:
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){
})
答案 3 :(得分:1)
如果你有各种权限级别,你可以像这样构建它们:
const LEVELS = Object.freeze({
basic: 1,
pro: 2,
admin: 3
});
/**
* Check if user has the required permission level
*/
module.exports = (role) => {
return (req, res, next) => {
if (LEVELS[req.user.role] < LEVELS[role]) return res.status(401).end();
return next();
}
}
答案 4 :(得分:0)
我使用此解决方案。我在body req中收到一个jwt令牌,并从那里获取角色信息
var iframe = $('#player1')[0],
player = $f(iframe),
status = $('.status');
// When the player is ready, add listeners for pause, finish, and playProgress
player.addEvent('ready', function() {
status.text('ready');
player.addEvent('pause', onPause);
player.addEvent('finish', onFinish);
player.addEvent('playProgress', onPlayProgress);
});
// Call the API when a button is pressed
$('button').bind('click', function() {
player.api($(this).text().toLowerCase());
});
function onPause(id) {
status.text('paused');
}
function onFinish(id) {
// status.text('finished');
window.location = 'http://www.google.com';
}
function onPlayProgress(data, id) {
status.text(data.seconds + 's played');
}
因此,我首先使用auth中间件来确定是否是有效用户,然后使用角色中间件来确定用户是否有权访问api路由
//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 }
我希望会有用
答案 5 :(得分:0)
既然我们在 2021 年,为什么不使用 ES6 语法?...使用 NodeJS v14.16.1,下面的示例非常有用:-)
使用快速路由器
const someFunc = ({ option1, option2 }) =>
router.get("/", (req, res, next) => {
// code
next();
});
module.exports = someFunc;
或
const someFunc = ({ option1, option2 }) =>
(req, res, next) => {
// code
next();
};
module.exports = someFunc;
...然后这样称呼它:
const someFunc = require('./middlewares/someFunc.js');
app.use(someFunc({option1: 'test', option2: false ));