Reputation: 20780
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?
Upvotes: 1
Views: 315
Reputation: 2103
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: '[email protected]' }
, { id: 2, username: 'joe', password: 'birthday', email: '[email protected]' }
];
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
Upvotes: 2