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

妖精的绣舞 提交于 2020-01-24 21:50:49

问题


my authentication is working well but Redirecting to previous page after authentication using node.js and passport is not working

   *//this is auth.route.js file*

   app.post('/login', passport.authenticate('login',{
        successRedirect : '/',
        failureRedirect : '/login',
        failureFlash : true  
    }));

 *// this is ensureAuthenticated function*

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

回答1:


I found the how to do it.

 *//this is auth.route.js file*
app.post('/login', function(req, res, next){
      passport.authenticate('login', function(err, user, info){
        // This is the default destination upon successful login.
        var redirectUrl = '/profile';

        if (!user) { return res.redirect('/'); }
        if (req.session.redirectUrl) {
          redirectUrl = req.session.redirectUrl;
          req.session.redirectUrl = null;
        }
        req.logIn(user, function(err){
          if (err) { return next(err); }
        });
        res.redirect(redirectUrl);
      })(req, res, next);
    });

 *// this is ensureAuthenticated function*
 function isLoggedIn(req, res, next) {
   if (req.isAuthenticated())
      return next();
   req.session.redirectUrl = req.url;

   req.flash("warn", "You must be logged in to do that")
   res.redirect('/login');
 }


来源:https://stackoverflow.com/questions/45093725/redirecting-to-previous-page-after-authentication-using-node-js-and-passport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!