Redirecting to previous page after authentication in node.js using passport.js
Take a look at connect-ensure-login, which works along side Passport to do exactly what you want!
In your ensureAuthenticated
method save the return url in the session like this:
...
req.session.returnTo = req.originalUrl;
res.redirect('/login');
...
Then you can update your passport.authenticate route to something like:
app.get('/auth/google/return', passport.authenticate('google'), function(req, res) {
res.redirect(req.session.returnTo || '/');
delete req.session.returnTo;
});
I don't know about passport, but here's how I do it:
I have a middleware I use with app.get('/account', auth.restrict, routes.account)
that sets redirectTo
in the session...then I redirect to /login
auth.restrict = function(req, res, next){
if (!req.session.userid) {
req.session.redirectTo = '/account';
res.redirect('/login');
} else {
next();
}
};
Then in routes.login.post
I do the following:
var redirectTo = req.session.redirectTo || '/';
delete req.session.redirectTo;
// is authenticated ?
res.redirect(redirectTo);