I am creating a login, logout and register system and storing password as hashed. When logging in I am comparing stored password with entered password but it is giving true even when password entered is wrong.
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')
}
})
As mentioned in the comments to you question, the bcrypt.compare
function returns a Promise. Since it looks like you're not wanting to use promises here, the simplest solution is to just replace the asynchronous compare
method with the synchronous compareSync
method.
I have included an example below (I also altered the formatting slightly for legibility):
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') });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.