ENCRYPTING USER PASSWORD IN NODEJS


Introduction

In the current digital age, safeguarding our information has become increasingly crucial due to the rise in hacking incidents aimed at stealing sensitive data such as passwords, ATM pins, and bank account information. The potential loss of such information emphasizes the need for robust security measures. One effective approach is to store data in an encrypted format, ensuring that it remains inaccessible to external sources and significantly reducing the risk of unauthorized access.

            Encryption serves as a vital tool for protecting user information in various real-world applications, offering a reliable defense against hackers and enhancing overall data security. Organizations and individuals can fortify their defenses by implementing encrypting techniques and mitigating the potential risks associated with data breaches.

This blog post explores the process of securely adding a user with an encrypted password in Nodejs. We will delve into the steps involved in dynamically receiving user information through Postman and storing the user details, including the encrypted password in the user collection. Following this tutorial will give you insights into implementing robust security measures to protect user data.

Prerequisites:-

To begin with, we need to add some fields to the existing user model (click here), which we have defined earlier. In the user model, we will add two fields

  • userName (data type as String)
  • password (data type as String)

userName: {
    type: String,
  },
  password: {
    type: String,
  },


Bcrypt

Bcrypt is a method for transforming data into an encrypted format. By utilizing the bcrypt function, we can effectively hash passwords, rendering them incomprehensible to authorized users.

The syntax for encrypting data using bcrypt is as follows: bcrypt.hash(data, salt)

When employing the bcrypt method to hash specific data, two parameters are required. 
Firstly, the data that needs to be encrypted, and
Secondly, the salt, a value that determines the number of hashing iterations applied to the data, bolstering its protection against potential leaks.

Implementation of Encrypting and Storing User data in the collection

We will try to modify the code in the userController (Defined in Previous Blog) for adding a user with by encrypting a password. Follow the below steps to ensure the required output

  • Install the dependency of bcrypt using --- npm i bcrypt (execute in terminal)
  • Import the dependency in the userController as below:
// importing the bcrypt dependency
const bcrypt = require("bcrypt");

  • Write a function to encrypt the password as follows:-

// function to encrypt the password
function encryptPassword(password) {
  // define any dynamic value for salt
  const salt = 7;
  return bcrypt.hash(password, salt);
}

The whole code required for implementing Encryption technique is as follows:- 

// import the userModel from the models folder
// to perform the Db operations
const userRepo = require("../models/userModel");

// importing the bcrypt dependency
const bcrypt = require("bcrypt");

// function to encrypt the password
function encryptPassword(password) {
  // define any dynamic value for salt
  const salt = 7;
  return bcrypt.hash(password, salt);
}

// writing a method to add a user
exports.addNewUser = async (req, res) => {
  try {

    // creating a user object for user details obtained from req body.
    const userInfo = {
      name: req.body.name,
      userName: req.body.userName,
      password: await encryptPassword(req.body.password),
      emailId: req.body.emailId,
      mobile: req.body.mobile,
      dateOfBirth: req.body.dateOfBirth
    }

    // adding a user in Runtime to users collection via postman
    const addUser = await userRepo.create(userInfo);

    if (addUser !== "" || addUser !== null) {
      res.status(200).json({
        status: "success",
        data: addUser,
      });
    } else {
      res.status(400).json({
        status: "failed",
        message: "Unable to add new user",
      });
    }

  } catch (err) {
    res.status(400).json({
      status: "failed",
      message: err.message,
    });
  }
};

In the above code, we have created a method for adding a new user (addNewUser). we are making an asynchronous call to encrypt a password because Nodejs follows asynchronous function calling mechanism to perform the required operations to get the Data. To run the above code of adding a user, you need two files with the required code – Routing.js and App.js (Refer this link for the code of two files).

Now we will run the add API defined in the UserRouting in the postman.


This is the data stored in the users collection of the code_builders_hut database in mongodb.


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