Verify access/group in Passport.js

You could create a simple middleware that checks the group:

var needsGroup = function(group) {
  return function(req, res, next) {
    if (req.user && req.user.group === group)
      next();
    else
      res.send(401, 'Unauthorized');
  };
};

app.get('/api/users', 
  passport.authenticate('local'),
  needsGroup('admin'), 
  function(req, res) {
    ...
  });

This assumes that the object stored in req.user has a property group. This object is the one passed along from the strategy implementation and deserializeUser.

An alternative could be connect-roles, but I don’t know how well that integrates with Passport.

EDIT: you could also combine Passport and the group-checking middleware:

var needsGroup = function(group) {
  return [
    passport.authenticate('local'),
    function(req, res, next) {
      if (req.user && req.user.group === group)
        next();
      else
        res.send(401, 'Unauthorized');
    }
  ];
};

app.get('/api/users', needsGroup('admin'), function(req, res) {
});

Leave a Comment