Hi, I am trying to use the bcriptjs library to compare the encrypted password with the database password.
I am using the "compare" method.
The values that I add to the method are:
- First, the password that the user gives me. (password)
- Second, the encrypted password of the database. (pass_db)
But always return false
const bcrypt = require('bcryptjs')
const create = (req, res) => {
const { email, password } = req.body;
if (password.length < 6) {
res.send({ msgType: "error", msg: "Contraseña almenos 6 caracteres" });
} else {
const hash = bcrypt.hashSync(password, 6);
db.query(
"INSERT INTO users (email, password) VALUES (?,?)",
[email, hash],
(err) => {
res.send({ msgType: "success", msg: "Usuario creado correctamente" });
}
);
}
};
//TODO Login dont work always return false
const login = (req, res) => {
//Password from req.body
const { email, password } = req.body;
db.query(
"SELECT password FROM users WHERE email = ?",
[email],
(err, result) => {
// Password encrypted from database
pass_db = result[0].password;
if(err){
res.send({msgType:'error', msg:'Incorrect Login'})
}
if(result.length > 0){
//Compare password from req.body with password encryted from database
const validate = bcrypt.compareSync(password, pass_db);
//Always false
console.log(validate);
if(validate){
res.send({msgType:'success', msg: "Correct login" })
}else{
res.send({msgType:'error', msg: "Incorrect email or password" });
}
}else{
res.send({msgType:'error', msg: "Incorrect email or password" });
}
}
);
};
I tried this code too but didn't work eighter.
bcrypt.hash(password, 6, function (err, hash) {
if (err) {
throw err;
}
bcrypt.compare(pass_db, hash, function (err, result) {
if (err) {
throw err;
}
console.log(result);
});
});
I hope you can help with this problem, thanks.
As long as the password being stored in the db is retrieved properly it should work. I simplified the program to not use a database (just a local object to store the hashed password) and it works fine. Since I'm using the same
bcrypt
commands you are, the only thing I can imagine is that there's a problem with the hashed password not coming back from the database properly. Try printing out the hashed value duringcreate
and again after retrieving from the db and confirm they match. Ifpass_db
is not exactly what it should be, that would explain why you can't compare successfully. Are you positive thatresult[0]
coming back from thedb.query
is a JSON object that has apassword
attribute?Here's my simplified version of the code that works without using the db:
Running this program gives the following output: