jaredhanson / passport-oauth2

OAuth 2.0 authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-oauth2/?utm_source=github&utm_medium=referral&utm_campaign=passport-oauth2&utm_content=about
MIT License
602 stars 343 forks source link

Allow the `verify` function to be a promise #142

Open franciscop opened 3 years ago

franciscop commented 3 years ago

Right now with all the modules that use Passport OAuth2, the verify function (2nd parameter of a Strategy) has this schema and workflow, when using callbacks:

const github = new GithubStrategy({...}, function verify(accessToken, refreshToken, profile, cb) {
  findUser(profile, function (err, user) {
    if (err) return cb(err);
    if (user) return cb(null, user);
    else createUser(profile, function (err, user) {
      if (err) return cb(err);
      cb(null, user);
    });
  });
});

I'd like to propose to allow for this verify function to be called asynchronously, and if so use promises instead of callbacks. This can be achieved two ways:

A middle point can be reached now by doing some hacky way, that makes the first solution invalid since it'd not be compatible:

const github = new GithubStrategy({...}, async function verify(accessToken, refreshToken, profile, cb) {
  try {
    let user = await findUser(profile.id);  // Sample code
    if (!user) user = await createUser(profile));
    cb(null, user);
  } catch (error) {
    cb(error);
  }
});

So with the new proposed API, this would also be valid:

const github = new GithubStrategy({...}, async function verify(accessToken, refreshToken, profile) {
  let user = await findUser(profile.id);  // Sample code
  if (!user) user = await createUser(profile));
  return user;
});

Example of how it could be handled: https://jsfiddle.net/franciscop/qdu8fa79/

Edit: I can try to work on this with a bit of guidance, first and foremost is to know if this is the direction where passport-oauth2 wants to move forward, and second whether my 2nd proposed method is the wanted one by the project maintainers.