1

I am just getting my head round Passport in Node

 passport.use(new LocalStrategy(
   function(username, password, done) {
     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);
     });
   }
 ));

This is all great, I understand the logic. However I don't understand where variables User from

User.findOne({ username:....

Is coming from? This isn't set anywhere and baffles me a little.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291
  • Without knowing the library, just pointing out Node.JS has a `global` global object that is treated as the [root](http://stackoverflow.com/questions/21578446/what-is-the-root-object-in-node-js) object. Some libraries like to break (what's arguably widely accepted as) the module paradigm and convention, adding things like what you're describing to this `global` or `root` object in order to be accessible by all scripts, regardless of whether or not they've `require`d the containing script. – Qix - MONICA WAS MISTREATED Oct 04 '14 at 21:33

1 Answers1

2

The example is using a mongoose model (User) that was defined elsewhere. Mongoose models have a findOne function. It's meant to mostly be filler to show how you would use the strategy to lookup info in the db to authenticate the user.

mscdex
  • 104,356
  • 15
  • 192
  • 153
Lbatson
  • 1,017
  • 8
  • 18
  • arghhh... Good lord :) Learning to use Node and things like passport reminds me of using facebook's api when it first came out, or phonegap. In fact, just anything that is poorly documented :) – Jamie Hutber Oct 04 '14 at 21:25
  • 2
    yea, the whole assumption of using a specific db or implementation is sort of annoying and you'll find this in many examples. Some do a better job of explaining it though. maybe open up an issue for passport.js to update that to help others avoid the confusion :) – Lbatson Oct 04 '14 at 21:28
  • 1
    Ye, i agree. Either way very helpful. Until that time maybe people will find here – Jamie Hutber Oct 05 '14 at 21:05