注册后Passportjs PREVENT自动登录

Dan*_*Dan 0 javascript node.js passport.js

使用passportjs进行身份验证。当用户注册时,我希望显示一条消息,让他们知道现在可以使用其帐户登录。截至目前,注册还记录了它们,这使我的通知无效:

  • “您现在可以注册”
  • “您已经登录”

  • “欢迎新用户”

我该如何预防?我在到达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
        })
    );
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 5

防止自动登录的两种方法:

1.在passport.authenticate中提供一个可选的回调。例...

      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);
      });
Run Code Online (Sandbox Code Playgroud)

注意:如果提供了回调,则登录用户,建立会话以及执行所需的操作将成为应用程序的责任。

对于此示例,将进行登录或会话存储。因此,将阻止自动登录。

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
            })
Run Code Online (Sandbox Code Playgroud)

使用此解决方案,会话实例中不会存储任何用户信息,因此重定向到/login通知“您现在可以使用您的帐户登录”正确。