2016-04-06 33 views
0

使用passportjs进行身份验证。当用户注册时,我想要显示一条消息,让他们知道他们现在可以使用他们的帐户登录。截至目前,报名也记录他们会抛出我的通知功能:Passportjs PREVENT注册后自动登录

  • “你现在可以报名参加”
  • “你已经登录”

  • “欢迎新用户”

我如何避免这种情况?我尝试req.logout()到底verifySignup()达到并没有骰子。

我的路由器:

router.route('/login') 
    .get(function(req, res){ 
    // If the user is already logged in, redirect them to the dashboard 
    if(req.isAuthenticated()) { 
     req.flash('alert', 'You are already logged in'); 
     res.redirect('/'); 
    } else { 
     // Otherwise, allow them to login 
     // Redirect them to the login pages 
     res.render('login', 
     { host: req.baseUrl, 
     error: req.flash('error'), 
     success: req.flash('success'), 
     alert: req.flash('alert') 
     }); 
    } 
    }).post(passport.authenticate('local-login', { 
     successRedirect: '/', 
     failureRedirect: '/login', 
     badRequestMessage: "You need to enter your username and password", 
     failureFlash: true // allow flash 
     }) 
); 

    router.route('/signup') 
    .get(function(req, res){ 
     // If the user is already logged in, redirect them to the dashboard 
     if(req.isAuthenticated()) { 
     req.flash('alert', 'You must first log out before signing up for a new account'); 
     res.redirect('/'); 
     } else { 
     // Otherwise, allow them to signup 
     // Redirect them to the signup pages 
     res.render('signup', 
     { host: req.baseUrl, 
      error: req.flash('error'), 
      success: req.flash('success'), 
      alert: req.flash('alert') 
     }); 
     } 
    }).post(passport.authenticate('local-signup', { 
      successRedirect: '/login', 
      failureRedirect: '/signup', 
      badRequestMessage: "You must fill in all of the form fields.", 
      failureFlash: true // allow flash 
     }) 
    ); 

回答

4

两种方法可以防止自动登录:

提供passport.authenticate的optional callback。例如...

 router.post('/signup', function(req, res, next) { 

     /* ... */ 

     passport.authenticate('local-signup', function(err, user, info) { 
      if (err) { return next(err) } 
      if (!user) { return res.redirect('/signup') } 
      res.redirect('/login'); 
     })(req, res, next); 
     }); 

注:,如果回调时,它会成为应用程序的 责任登录用户,建立会话,否则执行所需的操作。

在这个例子中,登录和会话存储发生。因此防止自动登录。

2.更简单的解决方案。使用选项session: false禁用会话。

.post(passport.authenticate('local-signup', { 
       successRedirect: '/login', 
       failureRedirect: '/signup', 
       badRequestMessage: "You must fill in all of the form fields.", 
       failureFlash: true, // allow flash, 
       session: false // prevent auto-login 
      }) 

通过这一解决方案,没有用户信息存储在会话实例等重定向到/login通知“您现在可以使用您的帐户”正确。