loading...

User Login: Trial and Error

mtee profile image Margaret W.N ・1 min read

I added a route to handle login. This route makes a post request and compares the provided password with the saved password. Then returns a success message.

The first step is to find the user. Since the email is unique I'll retrieve the user by searching for the email using findOne.

router.route('/users/login')
    .post(async (req, res) => {
      User.findOne({ email: req.body.email }, (err, user) => {
        if (err) {
          return res.send(err);
        }
        return user
      })
})

Next i tried comparing both passwords using bcrypt compare but i keep getting an error. My guess is that it's a syntax error that I'm yet to identify. Here is the code though.

await bcyrpt.compare(req.body.password, user.password, (err, res) => {
        if(err) {
          res.send(err)
        }
        if (req.body.password != user.password) {
          res.json({ success: false, message: 'passwords do not match' });
        } else {
          res.send('Log in Sucessfull')
        }
      });    

I try debug this when I'm well rested.
Day 25

Posted on by:

mtee profile

Margaret W.N

@mtee

Developer | GADs 20 scholar | Diving into backend

Discussion

markdown guide
 

In your findOne you are returning the found user in the callback. my guess is that you need to do something like "res.send(user)" , never used mongoose so you might need to convert user to a json object before sending.

in your bcrypt callback function you might be thinking that the second parameter "res" is express js response like it is in the function above but that value is going to just be a plain true or false boolean that tells you if the password and the hash match. so it's likely erroring bc you are trying to call non-existing methods on a boolean.

another error you might be getting from that second function is that you are calling await in front of bcrypt.compare which only returns a promise if you do not insert the callback function. from reading the docs it looks like you just do one or the other. either put in a callback function or await the result.

this is all good stuff you are working on. keep on persisting!

 

Thank you for the feedback. I'll makes the changes and try that again.