DEV Community

LePhuongTrung
LePhuongTrung

Posted on

User Security - P1 How to encrypt password in Nodejs?

With any software provider, there is also a responsibility that is to protect user information. Data breaches can cause millions of dollars in damages, and according to Imperva, the US has the highest data breach costs.
And one of the ways to secure user information is to encrypt confidential information. This article will guide you to encrypt passwords with

Step 1 Install the necessary dependencies

in your Project open terminal and enter command

npm install bcrypt
npm install dotenv

in the package.json file the dependencies section has "bcrypt": "^5.1.0" and "dotenv": "^16.0.3",, which is ok
Note the version may change depending on the time of installation (currently the latest version)

Step 2 Define environment variable

in the outermost create file .env
SALT: number of data hashes

SALT=10

Step 3 HashPassword

create a new founder named utils, in utils create a new file named handlePassword

const bcrypt = require("bcrypt");

const hashPassword = async (plainPassword) => {
  try {
    const hashPassword = await bcrypt.hash(plainPassword, parseInt(process.env.SALT));
    return hashPassword ;
  } catch (error) {
    console.log("🚀 ~ file: bcrypt.js ~ line 12 ~ hashPassword ~ error", error);
    return error;
  }
};

module.exports = {
  hashPassword,
};
Enter fullscreen mode Exit fullscreen mode

Step 4 Handle Controller

in the outermost create the Controller folder, in the controller create the file Auth.js

const UserModel = require("../Database/Models/User");
const { hashPassword } = require("../utils/bcrypt");

const signUp = async (req, res, next) => {
  try {
    let data = req.body;
    //look in database User has email entered yet
    const findAccount = await UserModel.findOne({email : data.email});
    if (!data.email || !data.fullName || !data.password) return res.status(412).send("You have not filled in the required information");
    if (findAccount ) {
      return res.status(403).send("The email has already been registered");
    };

    const hashedPassword = await hashPassword(data.password);
    const createNewAccount = await UserModel.create({
      ...data,
      password: hashedPassword,
    });
    if (!createNewAccount ) {
      return res.status(500).send("Internal server error");
    }
    return res.status(200).send(create);
  } catch (err) {
    console.log("🚀 ~ file: Controllers.js ~ line 34 ~ signUp ~ err", err);
    next(err);
  }
};
Enter fullscreen mode Exit fullscreen mode

Step 5 Handle router

in the outermost create the Router folder, in the Router folder create the file AuthRouter.js

var express = require("express");
var router = express.Router();
const AuthController = require("../Controllers/Auth");

router.post("/register", AuthController.signUp);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

In the additional App.js file:

var authRouter = require("./Router/AuthRouter");

app.use("/user", userRouter);

//IIFE
(async () => {
  await database.connectDatabase();
})();
Enter fullscreen mode Exit fullscreen mode

Conclusion

With today's post we have done the password hashing, tomorrow we will continue with 2 articles: login and send verified mail.
If you do not understand something, you can message me or join this group Zalo: Link, to exchange knowledge about BackEnd Nodejs

Top comments (0)