我在代码的bcrypt.compare部分遇到麻烦。我的路线能够对密码进行哈希处理并将密码存储在数据库中。该数据库能够存储255个字符,并且我已经验证密码长度为60个字符。每次将密码与db上的哈希密码进行比较时,都会从bycrypt.compare返回一个错误。
有人遇到过这种情况,知道我可能做错了吗?
用于在数据库中创建用户的身份验证路径:
app.post('/register/local', async (req, res) => {
const hashedPassword = await bcrypt.hash(req.body.password, 10) || undefined
const existingLocalUser = await db.User.findOne({ where: { email: req.body.email } }) || undefined
if (!existingLocalUser) {
try {
const newUser = await db.User.create({
given_name: req.body.given_name,
family_name: req.body.family_name,
email: req.body.email,
password: hashedPassword,
}
)
res.redirect('/login')
} catch {
res.redirect('/register')
}
} else if (existingLocalUser.dataValues.google_id) {
const updateUser = await db.User.update(
{ password: hashedPassword },
{ where: { email: req.body.email } }
)
} else {
console.log("You already have an account. Please login.")
res.redirect('/login');
}
})
护照的本地策略:
passport.use(new LocalStrategy( async (username, password, done) => {
const existingLocalUser = await User.findOne({ where: { email: username }})
if (!existingLocalUser) {
console.log("No user exisits")
return done(null, false)
}
console.log("password", password)
console.log("existingLocalUser.password", existingLocalUser.password)
await bcrypt.compare(password, existingLocalUser.dataValues.password, function(error, result) {
if (error) {
return done(error)
} else if (result) {
return done(null, existingLocalUser)
} else {
return done(null, false)
}
})
}
));
bcrypt.compare(password, existingLocalUser.password, function(error, result) {
if (error) {
return done(error)
} else if (result) {
return done(null, existingLocalUser)
} else {
return done(null, false)
}
})
您正在尝试同时使用回调和等待,请删除等待并坚持使用回调,或者您重构并单独使用async-await
正如@cristos正确指出的那样,问题可能是您混淆了异步/等待和回调。坚持一种模式。这是使用异步/等待代码的代码,
try {
const result = await bcrypt.compare(password, existingLocalUser.password);
if (result) {
return done(null, existingLocalUser);
} else {
return done(null, false);
}
} catch (error) {
return done(error);
}
也请注意,您确定要比较正确的值吗?按照您提供的代码示例,我可以看到您正在记录日志,
console.log("password", password)
console.log("existingLocalUser.password", existingLocalUser.password)
但是,bcrypt.compare()
中比较的值不同,
bcrypt.compare(password, existingLocalUser.dataValues.password)
我弄清楚了为什么它不起作用... React或Redux用星号掩盖了密码,因此将其更改为一个散列的星号。