Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport authentication not working in sails.js application

I have a Sails JS application. I am trying to setup authentication using Passport.js authentication layer sails-generate-auth. I have configured my app by following the steps given in their documentation.

But when I lift my sails app, authentication is not working. I am able to access the controllers, even when I am not logged in (It's not redirecting to my login page).

I added a console.log statement in api/policies/passport.js as follows:

module.exports = function (req, res, next) {
  passport.initialize()(req, res, function () {
    passport.session()(req, res, function () {
      res.locals.user = req.user;
      console.log(req.user); // added by me
      next(); 
    });
  });
};

Now, when I access controllers before login or after logout, its printing undefined. But when I am logged in, its printing my user data. Any idea why it is not checking for authentication?

I am using local authentication strategy and I have commented out all others (twitter, facebook...)

like image 360
Yedhu Krishnan Avatar asked Nov 27 '14 10:11

Yedhu Krishnan


2 Answers

The above answer provides useful information. I want to elaborare on that.

sails-generate-auth, by default doesn't deny access to controllers if the user is not logged in. For that, you can create another policy in api/policies/. For example: create sessionAuth policy as follows:

module.exports = function(req, res, next) {
  if (req.user) {
    return next();
  }

  return res.forbidden('You are not permitted to perform this action.');
};

Instead of showing forbidden page, you can also render login page. For that you need access to AuthController.login. So, add the policies in config/policies as follows:

'*': ['passport', 'sessionAuth'],

'auth': {
  '*': ['passport']
}

This helps to restrict access all the controllers except auth controllers such as login, logout and register, if the user is not logged in.

like image 121
Yedhu Krishnan Avatar answered Nov 15 '22 21:11

Yedhu Krishnan


Passport doesn't have a policy to deny access to a controller. For this, you have to create another policy.

See this link for more details.

like image 25
Arun614 Avatar answered Nov 15 '22 22:11

Arun614