Storing a User in the Database

Learn to implement logic to add a user to an in-memory database.

Hashing and salting

Even though we’re using an in-memory database, we’ve decided that we won’t store the passwords in plain text. Instead, we’ll use a common method to store passwords called hashing and salting. If this isn’t familiar, auth0 has a great article on it called “Adding Salt to Hashing: A Better Way to Store Passwords.”

The pattern itself is not complicated, and we can learn it just by following the code.

So, what we’ll do is store our password hashedData converted into a concise string using a hash function for security or indexing purposes. . We won’t be storing the exact hashed password the user entered, but the password plus a randomly generated string called a salt. This salt will then be stored alongside the password so that it can be used later. After this, we’ll never need to decode the password again.

With the salt, any time we want to check if a password is correct, we just have to add the salt to whatever password the user entered, hash it, and verify that the output matches what is stored in the database.

If this still seems strange to you, don’t worry. It becomes much simpler when you look at the code. Let’s implement these functions by following these steps:

  1. Create a utils file called src/users/util.ts with a hashWithSalt function inside it that hashes a string with the provided salt:

Get hands-on with 1200+ tech skills courses.