I am trying to set up a login mechanism using node.js, express and passport.js. The login itself works very well, also the sessions are well saved with redis, but I have some problems redirecting the user to where he started from before being asked to authenticate.
eg. The user following the link http://localhost:3000/hidden is then redirected to http://localhost:3000/login , but then I want it to be redirected again to http://localhost:3000/hidden .
The purpose of this is that if a user accidentally gets a page that he must first register, he should be redirected to the / login site providing his credentials, and then redirected back to the site he previously tried to access.
Here is my login
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 is my secureAuthenticated Method
function ensureAuthenticated (req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/login'); }
which intercepts the /hidden page
app.get('/hidden', ensureAuthenticated, function(req, res){ res.render('hidden', { title: 'hidden page' }); });
Html logout output is pretty simple
<form method="post" action="/login"> <div id="username"> <label>Username:</label> <input type="text" value="bob" name="username"> </div> <div id="password"> <label>Password:</label> <input type="password" value="secret" name="password"> </div> <div id="info"></div> <div id="submit"> <input type="submit" value="submit"> </div> </form>