why does the second `if` statement in post method not run?

Viewed 35

I'm working on a node.js login page example. But whatever password i put in, it always returns status ok. And the second if statement about checking if password is equal to the hash value doesn't seem to run. why is that?

  app.post('/api/login',async (req,res)=>{
        console.log("you received a message");
        const username = req.body.username;
        const password = req.body.password;
        console.log({username,password})
        const userexist = await logininfo.findOne({username});
        console.log(userexist);
        const passtrue = await bcrypt.compare(password,userexist.password);
        console.log(passtrue);
        if (!userexist) {
             return res.json({status:'error',error:"invalid user/password"})
         }
    
        if (passtrue){
            console.log(passtrue);
            return res.json({status:'ok',statustext:'you are good to go'})
        }
        res.json({status: 'ok'});
    })

here is the log

connect db success
app listening on port 3000
you received a message
{ username: 'xt851231', password: '123123123' }
{
  _id: new ObjectId("62e14b57ad7fc1e3775df133"),
  username: 'xt851231',
  password: '$2a$10$ZZTHC6uY5EPWryGOWGr6m.2rvj5vHUerJxJoCGDv.M4DnISCHehya',
  __v: 0
}
1 Answers

If the password are not equal you should probably return a different message.
Also, make sure that you check userexist before comparing the passwords and nest everything into a try ... catch:

app.post('/api/login', async (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  try {
    const userexist = await logininfo.findOne({ username });
    if (!userexist) {
        return res.status(400).json({ status: 'error', error: 'invalid user/password' });
    }
    const passtrue = await bcrypt.compare(password, userexist.password);
    if (passtrue) {
        return res.status(200).json({ status: 'ok', statustext: 'you are good to go' });
    }
    res.status(401).json({ status: 'error', error: 'invalid user/password' });
  } catch (err) {
    res.status(500).json({ status: 'error', error: 'server error' });
  }
});
Related