40

I'm an node.js and express.js noob. This question may seems silly but I'm really in confusion.

I'm trying to configure Local Strategry authentication by using passport. As shown in the official documentation, we can figure this Local Strategy by the following code,

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); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

My confusion is about the done callback function. When the official docs show this local strategy using as a middleware in the route handler, there is no need to pass the function parameter for this done callback.

app.post('/login', 
  passport.authenticate('local'),
  function(req, res) {
    res.redirect('/');
  });

So, isn't this done callback function will be null if we don't provide the function parameter? If not, what is that done callback function and what processes will be happening in this done callback function?

Steve.NayLinAung
  • 5,086
  • 2
  • 25
  • 49

2 Answers2

56

done is a method called internally by the strategy implementation.

Then it navigates you, as you can see, to one of the success / error / fail methods (again, by the implementation. there are more options). Each of these options may calls to the next, where in your snippet code is the following:

function(req, res) {
  res.redirect('/');
});

When success is called, it can attach the user to the request or do other things, depending on your needs (it looks for the options you pass to passport.authenticate). If you want to determine when next will be called, you should use custom callback which gives you more flexibility.

I strongly recommend that you read the source.

d-_-b
  • 21,536
  • 40
  • 150
  • 256
Roy Miloh
  • 3,381
  • 1
  • 18
  • 17
7

It's now 2022 and I had the same question. The passport documentation has improved and it describes the done method (also called cb) here: https://www.passportjs.org/concepts/authentication/strategies/#verify-function. You will need to call this yourself in your strategy's verify function.

A verify function yields under one of three conditions: success, failure, or an error.

If the verify function finds a user to which the credential belongs, and that credential is valid, it calls the callback with the authenticating user:

return cb(null, user);

If the credential does not belong to a known user, or is not valid, the verify function calls the callback with false to indicate an authentication failure:

return cb(null, false);

If an error occurs, such as the database not being available, the callback is called with an error, in idiomatic Node.js style:

return cb(err);
Matt Pennington
  • 560
  • 1
  • 8
  • 21