K
K
KonstantoS2015-06-30 23:18:50
Node.js
KonstantoS, 2015-06-30 23:18:50

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);
...

At the same time, before calling roleModule.hasPermission, data about the user (id, role ..) has already been written to req.currUser.
I want to somehow determine which module they are trying to access in order to look at the permissions.
I don't want to cut the bike through req.path. I also don't want to do something like this in every controller:
var roleModule = require(./libs/roles);
router.use(function(req,res,next){
        roleModule.hasPermission(req.currUser.role,'%moduleName%',function(permitted){
              if(permitted)
                  next();
        });
});

Maybe there is a better method? My version above will give extra lines of code, I want to be more concise.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Shatokhin, 2015-07-01
@KonstantoS

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);

A
Alexander Litvinenko, 2015-06-30
@edli007

app.all( '/cabinet/*', checkRole, function( req, res, next){
    ....
    next();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question