简体   繁体   中英

passport.js and process.nextTick in strategy

I'm facing something new in nodeJS: process.nextTick

In some strategies code examples for passport.js, we can see

passport.use(new LocalStrategy(
  function (username, password, done) {

    // asynchronous verification, for effect...
    process.nextTick(function () {

      findByUsername(username, function (err, user) {
        // ...
        bcrypt.compare(password, user.password, function (err, res) {
          // ...
        });
      })
    });
  }
));

But in the official documentation, it is not used. ( http://passportjs.org/guide/username-password/ )

What I understand is that process.nextTick should be used to defer synchronous stack to not block an event. But in this strategy code, there is no event.

What the benefit of doing that here ?

It's only there in the example to show that async authentication is possible. In most cases, you'd be querying a database, so it'd be async in nature. However, the example just has a hard-coded set of users, so the nextTick call is there for effect, to simulate an async function.

100% ES6 working so you can delete the nextTick
I use babel and webpack at server side to so:

import passport from 'passport';

const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

const manipulateUser = async (User, profile, done, token) => {
  try {
    const user = await User.findOne({ googleId: profile.id });
    if (user) {
      user.accessToken = token;
      await user.save();
      return done(null, user);
    }
    const newUser = new User();
    newUser.googleId = profile.id;
    newUser.name = profile.displayName;
    newUser.avatar = profile.photos[0].value;
    newUser.accessToken = token;
    profile.emails.forEach((email) => { newUser.emails.push(email.value); });
    await newUser.save();
    return done(null, newUser);
  } catch (err) {
    console.log('err at manipulateUser passport', err);
    return done(err);
  }
};

const strategy = (User, config) => new GoogleStrategy({
  clientID: config.googleAuth.clientID,
  clientSecret: config.googleAuth.clientSecret,
  callbackURL: config.googleAuth.callbackURL,
}, async (token, refreshToken, profile, done) => manipulateUser(User, profile, done, token));

export const setup = (User, config) => {
  passport.use(strategy(User, config));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM