Redirecting to previous page after authentication in node.js using passport.js -
i'm trying establish login mechanism using node.js, express , passport.js. login works quite nice, sessions stored nicely redis have troubles redirecting user started before being prompted authenticate.
e.g. user follows link http://localhost:3000/hidden
redirected http://localhost:3000/login
want him redirected again http://localhost:3000/hidden
.
the purpose of is, if user access randomly page needs logged in first, shall redirected /login site providing credentials , being redirected site tried access.
here 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(); // <-? line right? }); } })(req, res, next); });
and here ensureauthenticated method
function ensureauthenticated (req, res, next) { if (req.isauthenticated()) { return next(); } res.redirect('/login'); }
which hooks /hidden
page
app.get('/hidden', ensureauthenticated, function(req, res){ res.render('hidden', { title: 'hidden page' }); });
the html output login site quite 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>
i don't know passport, here's how it:
i have middleware use app.get('/account', auth.restrict, routes.account)
sets redirectto
in session...then redirect /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
following:
var redirectto = req.session.redirectto ? req.session.redirectto : '/'; delete req.session.redirectto; // authenticated ? res.redirect(redirectto);
Comments
Post a Comment