Step 9

Let's fix a considerable security risk in our application!

You should never store users' passwords in a database! Instead, you must encode the password and keep the encoded version.

To mitigate the issue, we will hash the user password and save the hashed password!

  • A hashed password has been run through a function that generates a long encrypted string from the original password.
  • The same password run through the same hash function will generate the same response. This process is how we can match passwords when users log in.

Stop the application and install the bcrypt package:

npm install bcrypt

Bcrypt is a common library for password hashing in web apps!

Create a subfolder util inside the server folder. Next, create a file, hashing.js in the util folder, with the following content:

const bcrypt = require("bcrypt");

const hashPassword = (password) => {
  return new Promise((resolve, reject) => {
    bcrypt.genSalt(10, (err, salt) => {
      if (err) {
        reject(err);
      }
      bcrypt.hash(password, salt, (err, hash) => {
        if (err) {
          reject(err);
        }
        resolve(hash);
      });
    });
  });
};

const verifyPassword = (plainPassword, hashedPassword) => {
  return bcrypt.compare(plainPassword, hashedPassword);
};

module.exports = {
  hashPassword,
  verifyPassword,
};

Notice the $10$ is the value for "salt round," which is the cost factor in the BCrypt algorithm. The cost factor controls how much time is needed to calculate a single BCrypt hash. The higher the cost factor, the more hashing rounds are done. Increasing the cost factor by $1$ doubles the necessary time. The more time is needed, the more difficult is password brute-forcing.

The following section will use the functions exposed in hashing.js to secure our registration and authentication processes.

Resources