如何比较存储的散列密码与纯文本



我正在创建一个登录,注销和注册系统,并将密码存储为散列。登录时,我将存储的密码与输入的密码进行比较,但即使输入的密码是错误的,它也会给出true。

app.post('/login', (req,res)=>{
const user = users.find((u)=>{
if(u.email === req.body.email){
return u
}
})
if(user){
const hash = user.password
const passwordEntered = req.body.password
console.log([hash, passwordEntered])
if(bcrypt.compare(passwordEntered, hash)){
res.redirect('/loggedin')
}else{
res.redirect('/login')
}
}else{
res.redirect('/register')
}
})

正如在对您的问题的评论中提到的,bcrypt.compare函数返回一个Promise。因为看起来你不想在这里使用承诺,最简单的解决方案就是用同步的compareSync方法替换异步的compare方法。

我在下面包含了一个例子(为了便于阅读,我还稍微改变了格式):

app.post('/login', (req,res) => {
// I used filter here as it's easier to understand
const currentUser = users.filter(user => user.email === req.body.email);
// I fliped the if-else here so we can avoid that ugly nested if
if(!currentUser) {
res.redirect('/register');
return;
};

const hash = user.password;
const passwordEntered = req.body.password;
console.log([hash, passwordEntered]);

if(bcrypt.compareSync(passwordEntered, hash)) { // <-- here's the change
res.redirect('/loggedin')
return;
}

// I removed the else here as it wasn't necessary
res.redirect('/login')
});

最新更新