jaredhanson / passport-local

Username and password authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-local/?utm_source=github&utm_medium=referral&utm_campaign=passport-local&utm_content=about
MIT License
2.74k stars 498 forks source link

Documentation out of date - findOne no longer accepts a callback #196

Open domluther opened 3 months ago

domluther commented 3 months ago

Since mongoose 7, findOne no longer accepts a callback. However, the documentation on both the readme of this github and your passport-local strategy page have this example block of code that tries to use a callback. This then fails.

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

It needs to be re-written to use promises or async await. I changed it to promises here and this works.

  passport.use(
    new LocalStrategy(function (username, password, done) {
      User.findOne({ username: username })
        .then((user) => {
          if (!user) {
            return done(null, false); // No user found with that username
          }

          return user.verifyPassword(password).then((isMatch) => {
            if (!isMatch) {
              return done(null, false); // Password did not match
            }

          });
          return done(null, user); // Successful authentication
        })
        .catch((err) => {
          return done(err); // Error during the process
        });
    })

Environment