Automatically redirect logged in users nodejs passport.js

时间:2015-05-04 19:24:32

标签: node.js express passport.js

Currently using node.js, express & passport.js to create a custom website/application.

Having followed several guides, I have a functioning login/logout system with authentication. However, should a user revisit and their session is still active, it doesn't redirect them to the 'dashboard'.

Current root route:

   /* GET login page. */
    router.get('/',function(req, res) {
        // Display the Login page with any flash message, if any
        res.render('index', { message: req.flash('message') });
    });

I am making use of the isAuthenticated function, as below:

var isAuthenticated = function (req, res, next) {
    if (req.isAuthenticated())
        return next();
    res.redirect('/');
}

How do I get it to automatically redirect users with an existing session? Any pointers most welcome!

2 个答案:

答案 0 :(得分:1)

Ok, I figured it out. In the / route, I queried whether req.user was set.

/* GET login page. */
router.get('/',function(req, res) {
    if(req.user){
        res.redirect("/dashboard");
    }else{
    // Display the Login page with any flash message, if any
    res.render('index', { message: req.flash('message') });
    }
});

答案 1 :(得分:1)

您可以使用" /"附加中间件端点是这样的。

router.get('/', sessionValidate, function(req, res, next) {
     res.render('login');
});

其中sessionValidate看起来像这样:

function sessionValidate(req,res,next){
  console.log(req.user,"i am here");
  users.findById(req.user,function(err, user) {
    if(user!=null){
      req.session.user = user;
      res.locals.user=user;
      res.redirect("/home")
    }
    else {
          next();
    }
  });
}