Nodejs, bcrypt async, mongoose login
You encrypt the password when the value is changed, but not when you insert a new mongo document, you can check this with document.isNew
.
I have updated your save method to the follow.
UsersSchema.pre('save', function (next) { let user = this; if (this.isModified('password') || this.isNew) { bcrypt.genSalt(10, (err, salt) => { if (err) { return next(err); } bcrypt.hash(user.password, salt, (err, hash) => { if (err) { return next(err); } user.password = hash; next(); }); }); } else { next(); }});
Also, Schema.statics
is used to serve static
methods. The this
context will not return the user, thus making this.password
undefined. To populate the instances of your schema with methods, you have to append them to the Schema.methods
object.
I have used bcrypt.compare
in the past, I dont know if bcrypt.compareAsync
is a valid method because the first one is already async. And if it was async, it wouldnt directly return a value. Compare requires a callback.
UsersSchema.methods.comparePassword = function (password, callback) { bcrypt.compare(password, this.password, (err, isMatch) => callback(err, isMatch));};
To compare the password, u can do something like the following:
const { email, password } = req.bodyUser.findOne({ email: email,}, (err, user) => { if (err) throw err; if (user) { user.comparePassword(password, (err, match) => { if (match && !err) { // match } }); }});