arunkumar
arunkumar

Reputation: 34133

Unable to get simple passportjs with mongoose working

I am using passport-local-mongoose and trying to setup a simple working example using the login example in the repository. But I'm running into problems and I get an error message saying "Error: failed to serialize user into session".

I have reproduced the problem in a gist. (To run the gist, you will need to replace the mongodb server IP and database name in the user.js file and do a POST to the /register endpoint with username and password values.)

In it you will see the endpoints '/setval' and '/getval' which set values in the session and retrieves it, showing that session support is working. The endpoint '/authtest' gives an Unauthorized response, even after doing a POST to '/login'. The endpoint '/authdebug' gives more information - the error mentioned above.

Anyone have any ideas on what is going on? I'm running out of things to try.

Upvotes: 0

Views: 215

Answers (1)

robertklep
robertklep

Reputation: 203509

I think that passport.authenticate should only be used on routes which are actually used for authenticating the user; in your case, that would be the /login route.

For routes for which you want to make sure a user has previously authenticated, like /authtest, you need a middleware which checks if a user is authenticated:

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/login'); // or your login page
}
// and
app.get('/authtest', ensureAuthenticated, function(req, res) {
 ...
});

An alternative for that middleware would be connect-ensure-login.

Upvotes: 1

Related Questions