防止用户再次loginpassportjs,如果他们被authentication一次?

我正在使用PassportJS,注册和loginfunction工作相当顺利。

我唯一遇到的问题是PassportJS(我正在使用会话),即使用户已经login,他们可以再次返回到注册/loginurl,并进行注册和/或login!

这是诱惑我。 如果有人有修正/build议,请放下。

更新 – 1

一瞥我的routes.js :(使用PassportJS以及routes.js -ensure-login。

 app.get('*', function(req, res, next) { if (req.url.indexOf('/users/login') < 0 && req.url.indexOf('/users/signup') < 0) { req.session.returnTo = null; } next(); }); // ===================================== // HOME PAGE (with login links) ======== // ===================================== app.get('/', sabSettings, function(req, res) { Setting.findOne(function(err, setting) { if (err) throw err; // console.log(setting); res.render('index', { title: 'eduBird | Reach the glory', setting: req.setting }); // load the index file }); }); // ===================================== // LOGIN =============================== // ===================================== // show the login form app.get('/login', sabSettings, function(req, res) { // render the page and pass in any flash data if it exists res.render('login', { message: req.flash('loginMessage'), errors: req.flash('error'), title: 'Login | eduBird', setting: req.setting }); }); // process the login form app.post('/login', passport.authenticate('local-login', { successReturnToOrRedirect: '/loggedin', failureRedirect: '/login', failureFlash: true })); // ===================================== // SIGNUP ============================== // ===================================== // show the signup form app.get('/signup', sabSettings, function(req, res) { // render the page and pass in any flash data if it exists process.nextTick(function() { res.render('signup', { message: req.flash('signupMessage'), errors: req.flash('error'), title: 'Register | eduBird', setting: req.setting }); }); }); // process the signup form app.post('/signup', passport.authenticate('local-signup', { successReturnToOrRedirect: '/profile/welcome', failureRedirect: '/signup', failureFlash: true })); 

您尚未创build任何types的访问控制,但不必担心,我们将首先介绍Passport如何工作并使用它来解决问题。

  1. 当用户提交一个login表单时,POST请求到我们指定的path,导致执行passport.authenticate。
  2. 该路由的身份validation中间件被configuration为处理本地策略,护照将调用您的本地策略的实施。
  3. 如果在与我们的数据库交互时发生错误,我们调用done(err)。 否则,如果找不到用户或者密码不匹配,我们调用done(null,false)。 如果成功,我们调用done(null,user)。

完成调用将返回到passport.authenticate和相应的redirect将被执行。

此时,如果login成功,则将用户对象(from done(null,user))附加到请求,并且可以通过req.user访问用户对象。

主要思想是如果用户对象没有附加到请求,这意味着用户没有login,所以我们可以通过req.user控制我们的应用程序行为,以login用户。 例如:

 // If the user object does not exist it means the user is not logged in if (!req.user) { res.render('signin'); } else { // If the user object exists, the user is logged in and if they try to log in we redirect them to the home page return res.redirect('/'); } 

我希望这有帮助。