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
Create New Users
#Set Up Authentication Routes
Let see in this next video how to set up authentication routes!
Start by building the infrastructure you need for your authentication routes, such as a controller and a router, and then register that router with your Express app.
First, create a user.js in your controllers folder:
exports.signup = (req, res, next) => {
};
exports.login = (req, res, next) => {
};
Create another user.js file, this time in your routes folder:
const express = require('express');
const router = express.Router();
const userCtrl = require('../controllers/user');
router.post('/signup', userCtrl.signup);
router.post('/login', userCtrl.login);
module.exports = router;
The routes provided are the ones expected by the front-end app.
Now register your router with your app. First, import the router:
const userRoutes = require('./routes/user');
And then register it:
app.use('/api/stuff', stuffRoutes);
app.use('/api/auth', userRoutes);
Your routes are now ready, so it's time to start implementing the business logic.
#Create New Users
Let's create new users in the next video!
You will need the bcrypt encryption package for your signup function, so install it to your project:
npm install bcrypt
You can now import it to your controller, and implement your signup function (don't forget to import your user model!):
exports.signup = (req, res, next) => {
bcrypt.hash(req.body.password, 10).then(
(hash) => {
const user = new User({
email: req.body.email,
password: hash
});
user.save().then(
() => {
res.status(201).json({
message: 'User added successfully!'
});
}
).catch(
(error) => {
res.status(500).json({
error: error
});
}
);
}
);
};
In this function:
Call bcrypt's hash function on your password and ask it to salt the password 10 times (the higher the value, the longer the function will take, but the more secure the hash. For more information, check out bcrypt's documentation).
This is an asynchronous function that returns a promise, where you receive the produced hash.
Create a new user in your
thenblock and save it to the database, returning a success response if successful and any errors with an error code if not.
#Let's Recap!
bcrypt's
hash()method creates an encrypted hash of your users' passwords to save them securely in the database
In the next chapter, you'll learn to implement the login function to check user credentials, allowing them to log in.
- Formations jusqu’à 100 % financées
- Date de début flexible
- Projets professionnalisants
- Mentorat individuel