What is the "done" function in Passport for?

Asked

Viewed 62 times

1

I have begun to learn the local authentication form with passport-local, provided by Passport, and I was left with doubts regarding the usefulness of the function done within the authentication process. What it does?

1 answer

1


Well, in the documentation of Passport there is an example with done, which is probably what you’re quoting:

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

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

The done is the Verify Callback (see documentation), i.e., it is an internal method called verified responsible for continuing the authentication process, returning an error, failure or authenticated user. A more detailed explanation can be found at documentation, but in short we have:

  • return done(err); corresponding to self.error(err) of the method verify. This is the case when an Exception occurs, for example.
  • return done(null, false, { message: 'Incorrect username.' }); corresponding to self.fail(info) of the method verify. This is the case when an authentication failure occurs (incorrect password, incorrect user or other reason).
  • return done(null, user); corresponding to self.success(user, info) of the method verify. This is the case when credentials are valid and the callback passes the authenticated user to Passport :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.