Auth Repository
Finally, we arrived to the core logic of our project. Create now src/repositories/auth.repo.ts
. In this file we gonna create a static methods class for our repo.
Before that, Let's add some other functions and services we gonna need here. We will need:
- JWT Handlers
- Mail Service
- Function helpers
JWT Handlers
Create this file src/utils/jwtHandler.ts
In the JWT Middleware, the user object in the call back is the payload we created. So, in our config, the user will return the user id and a timestamp.
Mail Service
This services calls nodemailer
to send the email. Create src/services/mail.service.ts
install first nodemailer
As you can see, we have another config file for emails. Create src/config/mail.config.ts
Note: We already added the .env
variables for the mailer.
Helper functions
A helper functions we can use in our app. Create src/utils/helpers.ts
The Auth Repo
First, we will go with each function alone, then have the summary file.
Login
You can throw "Credentials Error" for password not match error as well if you want.
Refresh token
When the access token has expired, the client side calls to refresh that access token. And we use this "Refresh token" as validation process, also to know which user is it. Note that refresh token has an expiration date too (double of JWT token).
Register / Create User
Send Email Verification
This is a private method, called by CreateUser
method.
Notice that the a
tag have an ID of token-link
. We will use that later for testing, it's important for email testing.
Confirm email
The token passed to this method is received from the sent email
Forget Password
Reset password
Update password
Send update password email
Confirm update password
After the user receives the email and is redirected to the client side. The latter sends us the token. The process is the almost the same as the previous token validation processes.
Summary
We walked through all the methods. Here is the whole file