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
constUserModel=require('../models/user.model')/** * * @param{*} user { * - name * - email * - password * } * * @returns user */constfindUserByEmailAndPassword=async (userData) => {constfoundUser=awaitUserModel.findOne(userData)return foundUser}
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
/** * @returns user */constloginUser=async (user) => {constloginUser=awaituserRepository.findUserByEmailAndPassword(user)if (!loginUser) {thrownewApiException({ status:'error', code:400, message:`Invalid credentials, please try a different email and password combination.`, data:null, errors: [`Invalid credentials, please try a different email and password combination.` ] }) }return loginUser}
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.
/** * Logs the user in and set a session for it. */constlogUserIn=catchExceptions(async (req, res) => {constloginUserRequest=loginUserRequestDto(req.body)loginUserValidator(loginUserRequest)// if the user's email and password match in our database// then set the current session to that userconstloggedInUser=awaitauthService.loginUser(loginUserRequest)// If there we find a user with authService.loginUser, then// we'll set the current session to that userreq.session.user = loggedInUserconstuserDto=userResponseDto(loggedInUser)res.status(200).json(globalResponseDto({ status:'success', code:200, message:`The user has successfully logged in.`, data: userDto, errors:null }) )})module.exports= logUserIn