嗨,我正在尝试使用bcriptjs库来比较加密密码和数据库密码。
我使用的是“比较”方法。我添加到该方法的值是:
但总是返回假的
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" });
}
}
);
};我也试过这段代码,但没成功。
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);
});
});我希望你能帮助解决这个问题,谢谢。
发布于 2022-01-02 17:25:12
只要正确检索到数据库中存储的密码,它就会正常工作。我将程序简化为不使用数据库(只是存储散列密码的本地对象),它工作得很好。由于我使用的是您所使用的相同的bcrypt命令,我唯一可以想象的是,哈希密码不能正确地从数据库返回。尝试在create期间打印散列值,在从db检索之后再打印一次,并确认它们匹配。如果pass_db不完全是应该的,那就解释了为什么您不能成功地进行比较。您确定result[0]从db.query返回是一个具有password属性的JSON对象吗?
下面是不使用db的简化代码版本:
const bcrypt = require('bcryptjs')
const passwords = {};
const create = async (email, password) => {
if (password.length < 6) {
console.log("Password must be at least 6 characters");
} else {
const hash = bcrypt.hashSync(password, 6);
passwords[email] = hash; // Store the hash in the passwords instead of db
}
};
const login = (email, password) => {
const pass_db = passwords[email]; // Retrieve hash from passwords instead of db
if (pass_db) {
const validate = bcrypt.compareSync(password, pass_db);
if (validate) {
console.log('Correct login');
} else {
console.log('Incorrect email or password');
}
} else {
console.log('Incorrect email or password');
}
};
const email = 'abc@mail.com';
const pw = 'testpass12345';
create(email, pw);
console.log('Try the right password');
login(email, pw);
console.log('Try the wrong password');
login(email, 'wrongpw');
console.log('Try the wrong email');
login('unknown@abc.com', 'blah');运行此程序将提供以下输出:
Try the right password
Correct login
Try the wrong password
Incorrect email or password
Try the wrong email
Incorrect email or passwordhttps://stackoverflow.com/questions/70555471
复制相似问题