We used bcryptjs
to hash user passwords before storing them in the database for security. We can also use it to verify that the hash of an incoming plain-text password matches the stored hash.
// Synchronous password checking
bcrypt.compareSync('password_string', stored_password_hash);
// Async password checking
bcrypt.compare('password_string', stored_password_hash, (err, res) => {
// returns true if password is correct
});
In Mongoose, instances of Models are known as documents. They have many pre-defined instance methods. Pre-defined instance methods can be overwritten if necessary, or new custom methods can be added. We have now done both.
First, we overwrote the existing .toJSON()
method to remove extraneous data from the returned user object.
userSchema.methods.toJSON = function() {
var user = this.toObject();
delete user.password;
delete user.__v;
return user;
};
Later, we wrote a custom .authenticate()
method for checking to make sure the password was correct before logging in a user.
userSchema.methods.authenticate = function(password, callback) {
bcrypt.compare(password, this.passwordDigest, (err, isMatch) => {
callback(isMatch);
});
};
Meganote: Source
Meganote-server: Source
Show flash messages for the success or failure of ‘sign up’ and ‘log in’
In Meganote Server, re-write the route for logging in using promises