Reputation: 313
I am trying to get a login function going but when I try to compare password with hashed password it always returns false
This is my registerUser function that holds the hashing
const registerUser = async (request, response) => {
const hashedPassword = await bcrypt.hash(request.body.password, 12)
const user = new UserModel({
username: request.body.username,
password: hashedPassword
});
try {
const databaseResponse = await user.save();
response.status(201).send(databaseResponse);
} catch (error) {
response.status(500).send({message: error.message});
}
};
This is the login function that holds the compare
const login = async (request, response) => {
try{
const user = await UserModel.findOne({username: request.body.username})
if(!user) return response.status(403).send('no user with name ' + request.body.username + ' found');
const isPassValidated = await bcrypt.compare(request.body.password, user.password)
if(!isPassValidated) return response.status(403).send('wrong password');
response.status(200).send('yay');
} catch(error){
response.status(500).send({message: error.message});
}
}
When I console.log request.body.password and user.password the hashed string is equal to the unhashed string so it should return true
The hashed string is the same string that is saved in the database
Upvotes: 1
Views: 2057
Reputation: 313
I just found the issue, thank you for your help. in userSchema, password was lowercase:true which caused the issue...
Upvotes: 2
Reputation: 103
The code looks alright. Do you have multiple users with the same username in your database? The generated hash should be: $2b$12$jgrLYOqnHnJGszlpgo26QuaT29tdxBFguyIttSNOIy/8go1viRrYC
Upvotes: 0