• 10 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 4/28/21

Check a user's credentials

Log in or subscribe for free to enjoy all this course has to offer!

Implement the login function

Now that we can create new users in the database, we need a way to check whether a user trying to sign in has valid credentials by implementing our login function:

exports.login = (req, res, next) => {
User.findOne({ email: req.body.email }).then(
(user) => {
if (!user) {
return res.status(401).json({
error: new Error('User not found!')
});
}
bcrypt.compare(req.body.password, user.password).then(
(valid) => {
if (!valid) {
return res.status(401).json({
error: new Error('Incorrect password!')
});
}
res.status(200).json({
userId: user._id,
token: 'token'
});
}
).catch(
(error) => {
res.status(500).json({
error: error
});
}
);
}
).catch(
(error) => {
res.status(500).json({
error: error
});
}
);
}

In this function:

  • we use our Mongoose model to check if the email entered by the user corresponds to an existing user in the database

    • if it does not, we return a  401 Unauthorized  error

    • if it does, we move on

  • we use bcrypt's compare function to compare the user entered password with the hash saved in the database

    • if they do not match, we return a  401 Unauthorized  error

    • if they match, our user has valid credentials

  • if our user has valid credentials, we return a  200  response containing the user ID and a token, which for now is a generic string

In the next chapter, you will discover token-based authentication — what it's for, how it works, and how we will be applying it in our app to secure our API properly.

Example of certificate of achievement
Example of certificate of achievement