简体   繁体   中英

Passportjs documentation - meaning of function

On this Passportjs.org page, the documentation gives an example of using a LocalStrategy, and within the LocalStrategy, it calls a function:

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

Now, I'm seeing this " User " object crop up in multiple places, such as in the documentation for the passport-windowsauth strategy, where the following function is used in an example:

User.findOrCreate()

So now I'm wondering if I'm crazy.

Is this 'User' object and its functions some existing framework or set of functions, or are these just examples of your own home-grown function for finding a user?

User is a object which contains information about users and findOne or findById or findByusername are just prototype functions associated with this object.

They have assumed a User schema ( Mongoose user schema) for all the examples they have given. it comes with all the mentioned prototype functions attached with it

From their working example (without Mongoose schema) :
https://github.com/jaredhanson/passport-local/tree/master/examples/express3

Adding code in case of link expiration:

var users = [
    { id: 1, username: 'bob', password: 'secret', email: 'bob@example.com' }
  , { id: 2, username: 'joe', password: 'birthday', email: 'joe@example.com' }
];

    function findById(id, fn) {
      var idx = id - 1;
      if (users[idx]) {
        fn(null, users[idx]);
      } else {
        fn(new Error('User ' + id + ' does not exist'));
      }
    }

    function findByUsername(username, fn) {
      for (var i = 0, len = users.length; i < len; i++) {
        var user = users[i];
        if (user.username === username) {
          return fn(null, user);
        }
      }
      return fn(null, null);
    }
    passport.use(new LocalStrategy(
      function(username, password, done) {
        process.nextTick(function () {
          findByUsername(username, function(err, user) {
            if (err) { return done(err); }
            if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
            if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
            return done(null, user);
          })
        });
      }
    ));

Reference:
https://github.com/jaredhanson/passport-local/tree/master/examples/express3

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