I have a node.js login form that should get the user name validate that is exists. Then is should compare it to the hashed Password I have generated. I am able to register new users to the mongodb database correctly. I am also able to findOne() user. But I am unable to compare the passwords.
app.post('/login-users', async (req, res) =>{
const user = User.findOne({name: req.body.name}, function(err, user){
console.log('User Found')
})
try{
if(await bcrypt.compare(req.body.password, user.password)){
res.redirect('/')
} else{
console.log('Not Allowed')
}
} catch {
res.status(500).send()
}
})
CodePudding user response:
you need to move your try catch to the callback because user is an unresolved promise
app.post('/login-users', async (req, res) =>{
const user = User.findOne({name: req.body.name},async function(err, user){
console.log('User Found')
try{
if(await bcrypt.compare(req.body.password, user.password)){
res.redirect('/')
} else{
console.log('Not Allowed')
}
} catch {
res.status(500).send()
}
})
})
or wait for promise to resolve
app.post('/login-users', async (req, res) =>{
const user = await User.findOne({name: req.body.name})
try{
if(await bcrypt.compare(req.body.password, user.password)){
res.redirect('/')
} else{
console.log('Not Allowed')
}
} catch {
res.status(500).send()
}
})
