1

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?

4

1 に答える 1

2

User は、ユーザーに関する情報を含むオブジェクトであり、findOne、findById、または findByusername は、このオブジェクトに関連付けられた単なるプロトタイプ関数です。

彼らは、与えられたすべての例に対してUser スキーマ ( Mongooseユーザー スキーマ) を想定しています。言及されたすべてのプロトタイプ関数が付属しています

実際の例から (Mongoose スキーマなし):
https://github.com/jaredhanson/passport-local/tree/master/examples/express3

リンクの有効期限が切れた場合のコードの追加:

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

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

于 2013-10-15T07:19:45.947 に答える