我在代码的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)
}
})
}
));
答案 0 :(得分:0)
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
答案 1 :(得分:0)
正如@cristos正确指出的那样,问题可能是您混淆了异步/等待和回调。坚持一种模式。 这就是使用async / await的代码的样子,
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)
答案 2 :(得分:0)
我弄清楚了为什么它不起作用... React或Redux用星号屏蔽了密码,因此将其更改为散列的星号。.