Reputation: 71
I'm new to node.js and mongodb, and I'm working on an authentication api using passport.js. I have a method in the user model named "isValidPassword", but i can't use it in the passport local strategy to sign in.
I always have "user.isValidPassword is not a function"
here's the user model
const mongoose = require ('mongoose');
const bcrypt = require('bcryptjs');
const Schema = mongoose.Schema;
// Create Schema
const userSchema = new Schema({
email: String,
password: {
type: String,
required: true,
minlength: 4,
id_user: Number,
username: String,
nom: String,
prenom: String,
num_portable: Number,
num_fix: Number,
image: String
}
});
// Hash password before saving the user
userSchema.pre('save', async function (next){
try {
// Generate Salt for the password encryption
const salt = await bcrypt.genSalt(15);
// Generate a hashed password using Salt
const passwordHash = await bcrypt.hash(this.password, salt);
// Re-assign the hashed password to the user's acuatl password
this.password = passwordHash;
next();
console.log ('Salt: '+ salt);
console.log ('Original password: ' + this.password);
console.log ('Hashed Password: ' +passwordHash);
} catch (error) {
next(error);
}
});
// isValidPassword
// Compare hashedpassword vs password stored in db
userSchema.methods.isValidPassword = async function(newPassword) {
try {
return await bcrypt.compare(newPassword, this.password);
} catch (error) {
throw new Error (error);
}
}
// Create Module
const User = mongoose.model('user',userSchema);
// Export Module
module.exports = User;
and here's when I used it in the passport local strategy
passport.use(new LocalStrategy({
usernameField: 'email'
}, async(email, password, done)=> {
try {
// Find user by the given email
const user = User.findOne({email});
// If the user doesn't existe, handle it
if(!user){
return done(null, false);
}
// else, check if the password is correct
const isMatch = await user.isValidPassword(password);
// if the password is wrong, handle it
if(!isMatch){
return done(null, false);
}
done(null, user);
} catch (error) {
done(error, false);
}
}));
and when I tried to do "console.log(user)" I found that isValidPassword is among the methods !
I just need the that boolean from isValidPassword method
Thank you for your attention.
Upvotes: 1
Views: 1269
Reputation: 71
Well I solved it, it was a silly mistake.. The problem was here
const user = User.findOne({email});
I forgot to put await before User.findOne(...)
so basically it doesn't wait for a response from the database, and it returns an empty user object.
Upvotes: 1