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

前端 未结 7 1205
悲&欢浪女
悲&欢浪女 2020-11-30 17:13

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 hav

7条回答
  •  渐次进展
    2020-11-30 17:59

    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);
    

提交回复
热议问题