In the previous blog post,
we delved into the process of Register a User,
where we learned how to add a user with an encrypted password, securely stored
in the users collection. If you
haven’t read that post yet, I highly recommend checking it out first, as it
covers the fundamental functions used for password encryption and storage.
Today, we will continue our journey to focus on the user login process, exploring how to implement the encryption technique to ensure a secure login experience for the application users.
What are the details required for a User Login….??
As we proceed with our
discussion on user login in Nodejs, let’s take a closer look at the necessary
information required for a successful login. When users attempt to log in to
our application, we need them to provide two essential details, their username and password.
From the client side,
users will enter both the username and password in string format. However, it’s
important to note that we have taken security measures on the server side to
protect user passwords. In our previous blog post, we learned about storing
passwords in an encrypted format within out database.
Combining the client-side input of username and password with the server-side encryption ensures a robust and secure user login experience for our Nodejs application. In
the upcoming sections, we will explore the steps to handle this process
efficiently and safeguard user credentials.
How is the user password comparison handled during the login process….??
When users enter their
password from the client side, the password is received in string format.
Subsequently, this entered password is passed into the login function on the
server side. Within this function, we utilize the powerful bcrypt function for password comparison.
The bcrypt function enables us to securely compare the entered password with the stored user password in the users collection. This crucial step ensures that the entered password is matched against the correct user’s password, verifying the user’s identity accurately. By incorporating bcrypt for password comparison, we reinforce the security of our login process and protect sensitive information effectively.
Code for Implementing Login Functionality
- Install the bcrypt dependency in the application – npm i bcrypt
- Import the bcrypt dependency in the code file
- Write the below code in the userController
- To run the above function, we need an API where a user requests for the login service, the api is written in the userRoutes as follows
Case
1:-
when we provide the improper username. The request payload and the response are
shown below.
Case 2: When the username is correct and the password is wrong. The request payload and the response are shown below.
Case 3: When both username and password are wrong. The request payload and the response are shown below.
Happy Coding !!