Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Redirecting to previous page after authentication in node.js using passport.js

Redirecting to previous page after authentication in node.js using passport.js

Problem

I'm trying to establish a Login mechanism using node.js, express and passport.js. The Login itself works quite nice, also sessions are stored nicely with redis but I do have some troubles with redirecting the user to where he started from before being prompted to authenticate.

e.g. User follows link http://localhost:3000/hidden is then redirected to http://localhost:3000/login but then I want him to be redirected again back to http://localhost:3000/hidden.

The purpose of this is, if the user access randomly a page he needs to be logged in first, he shall be redirected to the /login site providing his credentials and then being redirected back to the site he previously tried to access.

Here is my login post

app.post('/login', function (req, res, next) {
    passport.authenticate('local', function (err, user, info) {
        if (err) {
            return next(err)
        } else if (!user) { 
            console.log('message: ' + info.message);
            return res.redirect('/login') 
        } else {
            req.logIn(user, function (err) {
                if (err) {
                    return next(err);
                }
                return next(); // 

and here my ensureAuthenticated Method

function ensureAuthenticated (req, res, next) {
  if (req.isAuthenticated()) { 
      return next();
  }
  res.redirect('/login');
}

which hooks into the /hidden page

app.get('/hidden', ensureAuthenticated, function(req, res){
    res.render('hidden', { title: 'hidden page' });
});

The html output for the login site is quite simple

Problem courtesy of: Alx

Solution

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 ? req.session.redirectTo : '/';
delete req.session.redirectTo;
// is authenticated ?
res.redirect(redirectTo);
Solution courtesy of: chovy

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Redirecting to previous page after authentication in node.js using passport.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×