Basic solution

Let's first solve the problem, and after that improve the solution.

To be able to hash passwords, let's first install the package bcrypt.

yarn add bcrypt
yarn add -D @types/bcrypt

Now, going back to the UsersService, let's create a private method to hash a password.

private async hashPassword(password: string) {
  const salt = await genSalt();
  return hash(password, salt);
}

The salt is a collection of random characters that are mixed with the password before hashing it, making it harder for the original password to be discovered. This article further dicusses about this topic.

Now, in the create() method, we can extract the password from the DTO in order to hash it before saving the user.

const { password } = createUserDto;
const hashedPassword = await this.hashPassword(password);

const user = this.usersRepository.create({
  ...createUserDto,
  password: hashedPassword,
});

In the update() method, it's the same thing. We just need to also check if the password was indeed altered before attempting to hash it.

const hashedPassword = password && (await this.hashPassword(password));

And we're done, we have password hashing working. Let's now improve the solution.

Commit - Implementing password hashing

Last updated