Answer the question
In order to leave comments, you need to log in
Express.js How to define "next()" module in middleware (role-based access system) or pass a parameter?
Good day, I'm sawing a system with a role-playing access model. Now I have each router - a separate module. Would like to do something like this:
var roleModule = require(./libs/roles);
var events = require('./controllers/events');
app.use(roleModule.hasPermission);
app.use('/events', events);
...
var roleModule = require(./libs/roles);
router.use(function(req,res,next){
roleModule.hasPermission(req.currUser.role,'%moduleName%',function(permitted){
if(permitted)
next();
});
});
Answer the question
In order to leave comments, you need to log in
var roleModule = require(./libs/roles);
var checkRole = function (name) { // пишем middleware один раз и для всех, передаем имя роутера через замыкание
return function (req, res, next) {
roleModule.hasPermission(req.currUser.role, name, function(permitted){ // возвращать флаг первым параметром ОЧЕНЬ плохая практика, по соглашению в node.js первым аргумент в коллбеке должна быть ошибка
if (permitted)
next();
else
res.sendStatus(403);
})
}
}
var router = express.Router();
router.use(checkRole("%name")); // где name это имя вашего модуля
app.use('/user', router);
app.all( '/cabinet/*', checkRole, function( req, res, next){
....
next();
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question