Node.js and Passport Object has no method validPassword

Looks like you copied example from passportjs website, where Jared failed to mention how to implement it..

On the passport js github page he has another (simpler) example; he removed validPassword method altogether (line 18):

Example

if (user.password != password) { return cb(null, false); }

That's what I based my app on (using encryption) on top of it.


Also being a noob at this, it took me a whole day to figure this one out. I used the history from another one of Jared's example apps and some crypto advice from folks on here.

First off I made a method that generates a salt (a big random number which is stringified), uses the salt and the user's password to create a hash (with the help of the nodejs 'crypto' module), and finally stores both the salt and the hash every time before mongoose saves a new account.

//make hash
userSchema.pre('save', function(next) {
    var user = this;
    if(!user.isModified('password')) return next();
    var rand = (Math.floor(Math.random() * 1000000000)).toString(36);
    var hash = crypto.createHash('md5').update(user.password + rand).digest("hex");
    user.password = hash;
    user.salt = rand;
    next();
});

For the verification I simply take the inputted password (at login) and attempt the make the same hash again using the salt. I then compare the stored hash to the new one and return true or false accordingly.

 // Password verification
    userSchema.methods.validPassword = function(password) {
      var testhash = crypto.createHash('md5').update(password + this.salt).digest("hex");
      if(testhash === this.password) {
        return true;
      } else {
        return false;
      }
    }

You are using

if (!user.validPassword(password)) {
    return done(null, false, { message: 'Incorrect password.' });
}

but you haven't defined validPassword method. Attach it to your schema:

var authSchema = mongoose.Schema({ 
    username: 'string',
    password: 'string'
});
authSchema.methods.validPassword = function( pwd ) {
    // EXAMPLE CODE!
    return ( this.password === pwd );
};

EDIT You've also incorrectly defined the schema. It should be:

var authSchema = mongoose.Schema({ 
    username: String,
    password: String
});

Note that both username and password should be String type objects, not strings "string", if you know what I mean. :)