Implement the Login Function
Now that you can create new users in the database, you need a way to check whether a user trying to sign in has valid credentials by implementing a 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:
Use your Mongoose model to check if the email entered by the user corresponds to an existing user in the database.
If it does not, return a
401 Unauthorized
error.If it does, move on.
Use bcrypt's compare function to compare the user-entered password with the hash saved in the database.
If it does not match, return a
401 Unauthorized
error.If it matches, your user has valid credentials.
If your user has valid credentials, return a
200
response containing the user ID and a token, which for now is a generic string.
Let's Recap!
bcrypt's
compare
method compares a string with a hash to check whether an entered password corresponds to a secure hash stored in the database. This shows that not even bcrypt can decrypt its own hashes
In the next chapter, you will discover token-based authentication — what it's for, how it works, and how you will be apply it in your app to secure your API properly.