1
votes

I have a few questions regarding how passport.js works. On it's documentation theres an axample:

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

And from this article I read:

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

So the questions are (and hope they make sense):

  1. Where is the done function defined?
  2. How when and where is it passed as an argument to function(username, password, done)?
  3. How is passport.use(new LocalStrategy()) connected to passport.authenticate? The quotation says one call the other, but I can't see where that is happening

Thanks!

1

1 Answers

1
votes

You pass your done() function as an argument when you call passport.authenticate(). The time you call it, your strategy is called too and passes the function you defined as 3d argument.

Visual Flow

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

If it is not what you want to know, clarify your question then, please.

UPDATE:

As it has been already mentioned, callback is optional parameter in passport.authenticate(). If you pass it — this function is wrapped by 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() function(if exists). If it isn't supplied passport handles authorization automatically then.