Logging the User In - Implementation
1 - Route Name
Let's add the route and the controller in first.
POST /api/v1/auth/login
File: src/routes/index.js
const express = require('express')
const router = express.Router()
const userRoutes = require('./user.route')
const authRoutes = require('./auth.route')
function getRouter() {
router.use('/users', userRoutes)
router.use('/auth', authRoutes) // our new route
return router
}
module.exports = getRouterFile: src/routes/auth.route.js
File: src/controllers/auth/logUserIn.js
2 - Input Request
Next we'll add in the DTO, let's call it loginUserRequestDto.
3 - Middleware
None.
4 - Validation
Now time for the validator.
5 - Domain
For checking if there is a match in our database, we'll use our userModel that was created in the last section.
We'll add a new method called findUserByEmailAndPassword which will simply use our userModel to do a find in our database.
File: src/domain/services/userRepository.js
Once we have database query done, we'll add a new method called loginUser and use it in our authService. Notice here that we throw and exception if we do not find any users in the database. This would mean that the client's request has failed.
File: src/domain/services/authService.js
6 - Events
None.
7 - Response
Now to put everything all together. We'll reuse our userResponseDto from last section and log the user into our session with a simple req.session.user.
Once again, our code looks nice and clean 😎.
Last updated