Start learning free

LESSON 86 OF 173 · BACKEND: USERS AND SECURITY

Never Store Passwords in JavaScript

Practice

Until now, sign-up wrote the password itself into the users table. If that table ever leaks, every account is open, and many people use the same password on other sites too. A shop should never store passwords.

Hashes: store a hash instead, a one-way scramble of the password: easy to compute, no way back. hashPassword, a function already in your file, makes one with Node's crypto.scryptSync. It also mixes in a random salt, so the same password gives a different result every time:

console.log(hashPassword("tulip7"));   // scrypt:32768:8:1$...$...
console.log(hashPassword("tulip7"));   // another salt, another hash

The result holds the method, the salt and the hash, split by $. The tests read the table through GET /check/users, a route the course adds for checking, which shows each different salt and hash as a numbered label. With your changes, the test requests get:

POST /register  {"email": "ana@example.com", "password": "secret123"}  →  201  {"email": "ana@example.com", "id": 1}
POST /register  {"email": "ana@example.com", "password": "hello456"}   →  409  {"error": "Email already registered"}
POST /register  {"email": "ben@example.com", "password": "secret123"}  →  201  {"email": "ben@example.com", "id": 2}
GET /check/users  →  200  [{"email": "ana@example.com", "id": 1, "password_hash": "scrypt:32768:8:1$<salt 1>$<hash 1>"},
                           {"email": "ben@example.com", "id": 2, "password_hash": "scrypt:32768:8:1$<salt 2>$<hash 2>"}]

Ana and Ben chose the same password, yet their rows share nothing but the method.

Your task: name the last column of CREATE TABLE password_hash instead of password, compute the hash in the /register route, and save the hash instead of the password. The hashPassword function is already there.


Assignment
Follow the Coding Tutorial to store a salted hash at sign-up instead of the password.


Hint
Hash only after the 409 check, then pass the variable passwordHash as the second value of the INSERT.


STEP 1 OF 3
    Ctrl + Enter to check

    Auth Hash Passwords in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free