I have a node server, this is the login route. I am trying to send a response after checking if the user exists in the DB and if the password match the hash value. I am using a custom flag but the code where I check for the value is executed before the value can be changed.
router.route('/login').post( (req,res) => {
User.findOne({email: req.body.email} ,(err,user) => {
let check = false
if(!user){
return res.json({
loginSuccess:false,
message : "Invalid Email or Password"
})
}
user.comparePassword(req.body.password,(err, isMatch)=> {
if(err){
return res.json({
loginSuccess : false,
message : "Can't Login. Try Again!"
})
};
if(isMatch){
check = true
}
})
if(!check){
return res.json({
loginSuccess : false,
message : "Invalid Eail or Password"
})
}
user.generateToken((err, user) => {
if(err) {
return res.status(400).send(err)
}
else{
res.cookie('x_auth' , user.token)
.status(200)
.json({
user : user,
loginSuccess:true
})
}
})
})
})
In the code above, how can I make
if(!check){
return res.json({
loginSuccess : false,
message : "Invalid Eail or Password"
})
}
Wait for this:
user.comparePassword(req.body.password,(err, isMatch)=> {
if(err){
return res.json({
loginSuccess : false,
message : "Can't Login. Try Again!"
})
};
if(isMatch){
check = true
}
})
Actually the code below executes first before the flag is changed, but I want it to wait, so it can decide on the new value of check