使用node.js和passport进行身份验证后重定向到上一页

时间:2017-07-14 02:37:06

标签: node.js authentication passport.js

我的身份验证运行正常但在使用node.js和护照进行身份验证后无法重定向到上一页

   *//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 个答案:

答案 0 :(得分:0)

我找到了怎么做。

 *//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');
 }