2016-04-06 83 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通知「您現在可以使用您的帳戶」正確。