Search code examples
node.jsredispassport.jsaclmeanjs

SEAN.js autologin after sign up and req.user.roles


I currently using sean.js on a project. Everything looks good but I have a issue with the sign up process. I recently Implemented a backend policy on my routes to give permissions to my users depending on their roles, something like this:

exports.invokeRolesPolicies = function () {
  acl.allow([{
    roles: ['myRole'],
    allows: [{
      resources: '/some-route',
      permissions: '*'
    }]
  }]);
};

exports.isAllowed = function (req, res, next) {
  var roles = (req.user) ? req.user.roles : ['guest'];

  // If an person is being processed and the current user created it then allow any manipulation
  if (req.people && req.user && req.people.user && req.people.user.id === req.user.id) {
    return next();
  }

  // Check for user roles
  acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
    if (err) {
      // An authorization error occurred
      return res.status(500).send('Unexpected authorization error');
    } else {
      if (isAllowed) {
        // Access granted! Invoke next middleware
        return next();
      } else {
        return res.status(403).json({
          message: 'User is not authorized'
        });
      }
    }
  });
};

I used the template that comes with SEAN an it uses ACL to set the permissions. This method works fine when you log in with your user.

The problem is, when I create a new user from the sign up form, it automatically log in on the system but it doesn't get the roles with it and the req.user.roles is null. I have a process when after signing up the user need to finish another form to set everything, but due the role issue, the policy doesn't recognize the role and gives a "guest" role causing that I can't access to my routes. If I log out after the automatic sign in of the sign up, everything works fine because now the roles are set fine.

Do I have to set something else on the redis server and how? Or what do I need to do?


Solution

  • Well after a long research I figure out how to solve this. It follows that I was missing a line of code on my sign up controller. I need to login the req.user right after saving the user like this:

    user.save().then(function() {
        req.login(user, function(err) {
          if (err)
            res.status(400).send({
              message: errorHandler.getErrorMessage(err)
            });
          res.json(user);
        });
      }).catch(function(err) {
    

    The second line was that I was missing.

    Hope this help someone else in the future.