OpenClassrooms devient une université américaine accréditée.
Découvrez ce que cela change pour vousTable des matières
- Partie 1
Build a Simple Express Server
- Partie 2
Build a RESTful API
- Partie 3
Make Your API Secure
- Partie 4
Add Image Upload to Your API
Check a User's Credentials
#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 Unauthorizederror.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 Unauthorizederror.If it matches, your user has valid credentials.
If your user has valid credentials, return a
200response containing the user ID and a token, which for now is a generic string.
#Let's Recap!
bcrypt's
comparemethod 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.
- Formations jusqu’à 100 % financées
- Date de début flexible
- Projets professionnalisants
- Mentorat individuel