USER LOGIN WITH ENCRYPTED PASSWORD IN NODEJS

 

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
exports.loginUser = async (req, res) => {
  try {
    // First check whether the user is exists in the Collection or not
    const user = await userRepo.find({ userName: req.body.userName });

    // if the user exists, the below code executes to check the password belonging
    // to the particular user.
    if (user.length > 0) {
      const password = await bcrypt.compare(
        req.body.password,
        user[0].password,
        function (err, data) {
          if (data === true) {
            // If all the credentials are correct
            res
              .status(200)
              .json({ status: "success", message: "Login is Successful" });
          } else {
            // If Password is not correct
            res
              .status(400)
              .json({ status: "failed", message: "Incorrect Password" });
          }
        }
      );
    } else {
      // If the user doesn't exist in the application
      res.status(400).json({
        status: "failed",
        message: "User doesn't exist in the application",
      });
    }
  } catch (err) {
    res.status(400).json({
      status: "failed",
      message: err.message,
    });
  }
};
  • 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
// api call to login a existing user
router.post('/login', userController.loginUser);

Now let us try to check the login functionality from postman as below:

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 !!

Harsha Vardhan Garlapati

As a software engineer and technology enthusiast, I thrive on exploring the ever-evolving world of technology and leveraging it to create innovative solutions. With a passion for sharing knowledge and insights, I also delve into the world of blogging to inspire and educate others in the realm of software development. Beyond the realm of code, I find joy in exploring new destinations as a passionate traveler, embracing diverse cultures, and broadening my horizons. In my free time, I cherish moments spent with friends, valuing the connections and experiences that enrich my life. Combining my technical expertise, love for writing, adventurous spirit, and the importance of human connections, I aim to leave a positive impact on the world through my work, experiences, and interactions. Let’s embark on this exciting journey together, exploring the wonders of technology while cherishing the moments that truly matter.

Post a Comment

Previous Post Next Post