Friday 27 March 2020

bcrypt.compare() lets every password through

I am making a user authentication system. Registering users and hashing password works, however when I try to log in with the correct username, my isValidPassword always lets me log in with whichever password. Do you see any errors/solutions to this?I need to use .pre() because I have a route to update user details, and without it the changed password is saved as plain text and not hashed.​const mongoose = require('mongoose') const bcrypt = require('bcrypt'), SALT_WORK_FACTOR = 10; const Schema = mongoose.Schema // Schema for making a new user account (for employees) const User = new Schema({ name: { type: String, required: true }, surname: { type: String, required: true }, role: { type: String, enum: ['Admin', 'Manager', 'Advisor'], required: true }, username: { type: String, unique: true, required: true }, password: { type: String, required: true } }) // Generates salts and hash-encrypts the password before writing it to the database User.pre('save', async function(next){ const user = this; const hash = await bcrypt.hash(this.password, 10); this.password = hash; next(); }); User.methods.isValidPassword = async function(password){ const user = this; const compare = await bcrypt.compare(password, user.password); return compare; } module.exports = mongoose.model('User', User )

Submitted March 27, 2020 at 05:04PM by Fizaraz

No comments:

Post a Comment