Question

Users visiting http://localhost/login are instantly redirected to Facebook for confirmation of application usage. Once authorized, Facebook contacts http://localhost/login?code= with a special code that allows the server to obtain the user's information such as their name and gender.

Express().get('/login', Passport().authenticate('facebook', {
    failureRedirect: 'http://localhost/',
}), function(req, res) {
    database.saveData(req.user, **randomlyGeneratedHash**);
    res.cookie('session', **randomlyGeneratedHash**);
    res.end();
});

This works as expected, but when authenticated users visit the /login in succession, the whole process is repeated and they get a new cookie.

Is there a way that I can run some code inbetween Express and Passport, to stop Passport from redirecting to Facebook if the user has a valid cookie already?

Était-ce utile?

La solution

You can use something similar to ensureAuthenticated on your /login route:

var CheckIfAlreadyLoggedIn = function(req, res, next) {
  if (req.isAuthenticated()) {
    return res.redirect('/'); // or where you want them to go
  }
  next();
};

Express().get('/login', CheckIfAlreadyLoggedIn, Passport().authenticate('facebook', ...));

This would redirect users that are already logged in back to / when they try to access /login.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top