对 passport.use(strategy) done 函数及其与 passport.authenticate 的关系感到困惑

Confused about passport.use(strategy) done function and it's relation with passport.authenticate

我有几个关于 passport.js 工作原理的问题。在它的文档中有一个例子:

    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);
    });
  }
));

我从 this 文章中读到:

Calling done will make the flow jump back into passport.authenticate. It's passed the error, user and additional info object (if defined).

所以问题是(希望它们有意义):

  1. done函数在哪里定义的?
  2. 它是如何在何时何地作为参数传递给函数(用户名, 密码,完成)?
  3. passport.use(new LocalStrategy()) 是如何连接到 passport.authenticate?引语说一个叫另一个,但我 看不到发生的地方

谢谢!

您在调用 passport.authenticate() 时将 done() 函数作为参数传递。当您调用它时,您的策略也会被调用并传递您定义为 3d 参数的函数。

视觉流

function done(err, user, info) => {
  if (err || !user) {
    return new Error(info.msg);
  }

  // log-in user
}

// pass done
passport.authenticate("local", done); 
              │                 └┬──→ will be called within LocalStrategy
              │                  │    e.g. if (!user) done(err, user, info);
              ↓                  │
  calls your strategy func       │
                 └───┐           └───────────────┐
                     ↓                           ↓           
new LocalStrategy(function (username, password, done) {
  User.findOne({ username}, (err, user) => {     │
    if (!user) {                                 │
      return done(err, user, { mgs: "err" });  ←─┤
    }                                            │
  });                                            ↓
});                                   here done func is called

如果不是您想知道的,请澄清您的问题。

更新:

如前所述,callbackpassport.authenticate()中的可选参数。如果你传递它——这个函数被 verified(default) one which becomes the 3d argument within your strategy. The time you call this wrapping function there, it verifies parameters you sent and decides the response type: success, fail, or error — all these methods are created here and call your custom done() 函数包装(如果存在)。如果未提供 passport 则自动处理授权。