简体   繁体   中英

How do I redirect back to protected page after user logs in?

I am using express. I have a page myprofile which is only accessible when user is logged in. The problem is I cant redirect back to myprofile automatically when user gets logged in. I am using social media OAuth login / passport strategies.

After click on profile button, this happens :

home --->isAuthenticated() ---> /login ---> /

After click on profile button, I want :

home --->isAuthenticated() ---> /login ---> /myprofile

Finally I got the answer. I didnt hope that it will so easy to tackle this problem.

Some changes that I did :

function isLoggedIn (req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        // variable holding previous path 
        req.session.returnPath = req.path;
        res.redirect('/login');
    }
}

.
.
.

  app.get('/auth/<provider>/callback',
    passport.authenticate(<provider>, {
        failureRedirect : '/login'
    }), 
    function(req, res) {
        res.redirect(req.session.returnTo || "/");
        delete req.session.returnTo;
    });    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM