Passportjs 自定义回调 - 'Incorrect password' 消息

Passportjs custom callback - 'Incorrect password' message

对于常规身份验证,'Incorrect password' 消息可通过 failureFlash

app.post('/login',
  passport.authenticate('local', { successRedirect: '/',
                                   failureRedirect: '/login',
                                   failureFlash: true })
);

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

但是如果我使用自定义回调,我如何访问该 'Incorrect password' 消息并将其显示给用户?因为自定义回调似乎只检查 (!user)。我需要自定义回调,因为我正在通过 ajax 进行登录,但我无法进行重定向。

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.status(401).send({"ok": false}); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return return res.send({"ok": true});
    });
  })(req, res, next);
});

该消息位于自定义回调处理程序的 info 参数中,因此很容易访问和发送给用户。

另一方面,我不会具体说明登录失败的原因是用户名还是密码。使用这种响应很容易测试存在哪些用户名,然后只关注密码。