Module 4 · Authentication and user management
4.1 Users and password hashing
Add a users table and ownership columns, hash passwords with argon2id, seed the six scenario users, and see what a stored password actually looks like.
Starting point
Module 3 is complete. Nothing in the application knows who is using it.
Outcome
migrations/003_create_users.sqlsrc/models/users.js- A
userstable with a case-insensitive unique email and a password hash, never a password. issues.reported_by,inspections.created_byandinspection_status_changes.changed_byrecord which user did what.- The seed creates alice, bob, carol, dave, nora and ravi, each with the password
password123(local learning only).
The problem
To log in, the server must check a password. The tempting design stores the password and compares strings. Then one leaked database backup, one SQL injection, or one curious administrator exposes every user's password, and people reuse passwords on other sites.
So we never store the password. We store the output of a password hashing function: a one-way function that is deliberately slow and uses a random salt per password. To check a login we hash the submitted password with the same salt and parameters and compare the results.
Ordinary hashes such as SHA-256 are the wrong tool. They are designed to be fast: a graphics card can try billions of guesses per second. argon2id, the function recommended by OWASP's password storage guidance, is designed to be slow and to need a lot of memory per guess, which makes large-scale guessing expensive.
Build it
1. The migration
CREATE TABLE users ( id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, email text NOT NULL CHECK (email = lower(email) AND position('@' IN email) > 1), name text NOT NULL CHECK (length(trim(name)) BETWEEN 1 AND 100), password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()); CREATE UNIQUE INDEX users_email_idx ON users (email); -- Who did what. Existing rows have no user yet, so these columns allow NULL.ALTER TABLE issues ADD COLUMN reported_by integer REFERENCES users (id) ON DELETE SET NULL;ALTER TABLE inspections ADD COLUMN created_by integer REFERENCES users (id) ON DELETE SET NULL;ALTER TABLE inspection_status_changes ADD COLUMN changed_by integer REFERENCES users (id) ON DELETE SET NULL;- Emails are stored in lower case, and a
CHECKenforces it.Alice@Example.testandalice@example.testare the same person; storing one form makes the unique index meaningful. - New columns on existing tables are nullable. Rows that existed before this migration have no known reporter. A migration cannot invent one. The application will always fill these columns from now on, and the seed fills them for the scenario.
ON DELETE SET NULLkeeps an issue if its reporter's account is deleted. The record of the issue matters more than the link to the person.
npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
applied 003_create_users.sql
migrations are up to date
2. Install argon2
npm install argon2@0.45.2
added 12 packages, and audited 113 packages in 7s
35 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
argon2 contains native code. npm downloads a prebuilt binary for your platform; if none matches, it compiles one, which needs build tools (Xcode Command Line Tools on macOS).
3. The users model
Create src/models/users.js:
import argon2 from 'argon2';import { query } from '../db.js'; const PUBLIC_COLUMNS = 'id, email, name, created_at'; export function normaliseEmail(email) { return typeof email === 'string' ? email.trim().toLowerCase() : '';} export async function hashPassword(password) { return argon2.hash(password, { type: argon2.argon2id });} export async function createUser({ email, name, password }) { const passwordHash = await hashPassword(password); const { rows } = await query( `INSERT INTO users (email, name, password_hash) VALUES ($1, $2, $3) RETURNING ${PUBLIC_COLUMNS}`, [normaliseEmail(email), name, passwordHash], ); return rows[0];} export async function findUserById(id) { const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE id = $1`, [id]); return rows[0] ?? null;} // A real hash of a random string. Used so that "unknown email" takes as long as "wrong password".const DUMMY_HASH = await hashPassword(`dummy-${Math.random()}`); // Returns the user (without the hash) if the email and password match, otherwise null.export async function verifyCredentials(email, password) { const { rows } = await query('SELECT id, password_hash FROM users WHERE email = $1', [normaliseEmail(email)]); const row = rows[0]; const ok = await argon2.verify(row ? row.password_hash : DUMMY_HASH, typeof password === 'string' ? password : ''); return row && ok ? findUserById(row.id) : null;}Every detail here has a reason:
PUBLIC_COLUMNSnever includespassword_hash. Objects returned by this module can be put onreq.user, logged, or passed to a template without carrying the hash around.argon2.hashgenerates a random salt, runs argon2id with the library's default cost parameters, and returns one string that contains the algorithm, the parameters, the salt and the hash.argon2.verifyreads all of those back from that string.verifyCredentialsnever says why it failed. Wrong email and wrong password both returnnull.- The dummy hash. Without it, an unknown email returns in about a millisecond (no hash to check) while a known email with a wrong password takes tens of milliseconds. An attacker could measure the difference and learn which emails have accounts. Verifying against a dummy hash makes both paths do the same work.
awaitat the top level computesDUMMY_HASHonce, when the module is first imported.
4. Seed the scenario's users
Add the users to src/seed.js, and record who reported each issue and created each inspection:
import { hashPassword } from './models/users.js'; // Every seeded user has this password. Local learning data only.export const SEED_PASSWORD = 'password123'; export const users = [ { id: 1, email: 'alice@example.test', name: 'Alice Byrne' }, { id: 2, email: 'bob@example.test', name: 'Bob Okafor' }, { id: 3, email: 'carol@example.test', name: 'Carol Duffy' }, { id: 4, email: 'dave@example.test', name: 'Dave Murphy' }, { id: 5, email: 'nora@example.test', name: 'Nora Quinn' }, { id: 6, email: 'ravi@example.test', name: 'Ravi Shah' },]; export const organisations = [
await client.query('TRUNCATE inspection_status_changes, inspections, issues, buildings, organisations RESTART IDENTITY CASCADE'); await client.query('TRUNCATE inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE'); for (const u of users) { await client.query( 'INSERT INTO users (id, email, name, password_hash) VALUES ($1, $2, $3, $4)', [u.id, u.email, u.name, await hashPassword(SEED_PASSWORD)], ); }
for (const table of ['organisations', 'buildings', 'issues', 'inspections']) { // Who reported each issue and created each inspection (see the scenario table in lesson 0.1). await client.query(`UPDATE issues SET reported_by = CASE WHEN id IN (101, 102) THEN 1 WHEN id IN (103, 104) THEN 4 WHEN id IN (105, 106) THEN 2 WHEN building_id = 10 THEN 1 WHEN building_id = 20 THEN 4 END`); await client.query('UPDATE inspections SET created_by = CASE id WHEN 201 THEN 4 WHEN 202 THEN 1 WHEN 203 THEN 3 WHEN 204 THEN 2 END'); for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections']) {
Show the whole src/seed.js after this change
import { hashPassword } from './models/users.js'; // Every seeded user has this password. Local learning data only.export const SEED_PASSWORD = 'password123'; export const users = [ { id: 1, email: 'alice@example.test', name: 'Alice Byrne' }, { id: 2, email: 'bob@example.test', name: 'Bob Okafor' }, { id: 3, email: 'carol@example.test', name: 'Carol Duffy' }, { id: 4, email: 'dave@example.test', name: 'Dave Murphy' }, { id: 5, email: 'nora@example.test', name: 'Nora Quinn' }, { id: 6, email: 'ravi@example.test', name: 'Ravi Shah' },]; export const organisations = [ { id: 1, name: 'Liffey Estates' }, { id: 2, name: 'Harbour Lets' },]; export const buildings = [ { id: 10, organisationId: 1, name: 'Dublin Offices' }, { id: 20, organisationId: 1, name: 'Cork Apartments' }, { id: 30, organisationId: 2, name: 'Galway Studios' }, { id: 40, organisationId: 2, name: 'Limerick House' },]; const namedIssues = [ { id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' }, { id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' }, { id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' }, { id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' }, { id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' }, { id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },]; const fillerTitles = [ 'Loose handrail on stairs', 'Bins not collected', 'Corridor light not working', 'Radiator cold in room 2', 'Window does not close fully', 'Loose floor tile at entrance', 'Toilet cistern keeps running', 'Blocked sink in kitchen',]; // 24 extra issues (ids 107-130) alternate between buildings 10 and 20,// so that lists have enough rows to page, sort and filter.function fillerIssues() { const priorities = ['low', 'medium', 'high', 'critical']; const statuses = ['open', 'investigating', 'closed']; const issues = []; for (let i = 0; i < 24; i++) { issues.push({ id: 107 + i, buildingId: i % 2 === 0 ? 10 : 20, title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`, priority: priorities[i % priorities.length], status: statuses[i % statuses.length], occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(), description: '', }); } return issues;} export const issues = [...namedIssues, ...fillerIssues()]; export const inspections = [ { id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' }, { id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' }, { id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' }, { id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },]; export async function seed(client) { await client.query('BEGIN'); try { await client.query('TRUNCATE inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE'); for (const u of users) { await client.query( 'INSERT INTO users (id, email, name, password_hash) VALUES ($1, $2, $3, $4)', [u.id, u.email, u.name, await hashPassword(SEED_PASSWORD)], ); } for (const o of organisations) { await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]); } for (const s of buildings) { await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]); } for (const e of issues) { await client.query( `INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at) VALUES ($1, $2, $3, $4, $5, $6, $7)`, [e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt], ); } for (const a of inspections) { await client.query( `INSERT INTO inspections (id, building_id, title, findings, status, submitted_at) VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`, [a.id, a.buildingId, a.title, a.findings, a.status], ); if (a.status === 'submitted') { await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]); } } // Who reported each issue and created each inspection (see the scenario table in lesson 0.1). await client.query(`UPDATE issues SET reported_by = CASE WHEN id IN (101, 102) THEN 1 WHEN id IN (103, 104) THEN 4 WHEN id IN (105, 106) THEN 2 WHEN building_id = 10 THEN 1 WHEN building_id = 20 THEN 4 END`); await client.query('UPDATE inspections SET created_by = CASE id WHEN 201 THEN 4 WHEN 202 THEN 1 WHEN 203 THEN 3 WHEN 204 THEN 2 END'); for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections']) { await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]); } await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; }}import { hashPassword } from './models/users.js';
// Every seeded user has this password. Local learning data only.
export const SEED_PASSWORD = 'password123';
export const users = [
{ id: 1, email: 'alice@example.test', name: 'Alice Byrne' },
{ id: 2, email: 'bob@example.test', name: 'Bob Okafor' },
{ id: 3, email: 'carol@example.test', name: 'Carol Duffy' },
{ id: 4, email: 'dave@example.test', name: 'Dave Murphy' },
{ id: 5, email: 'nora@example.test', name: 'Nora Quinn' },
{ id: 6, email: 'ravi@example.test', name: 'Ravi Shah' },
];
export const organisations = [
{ id: 1, name: 'Liffey Estates' },
{ id: 2, name: 'Harbour Lets' },
];
export const buildings = [
{ id: 10, organisationId: 1, name: 'Dublin Offices' },
{ id: 20, organisationId: 1, name: 'Cork Apartments' },
{ id: 30, organisationId: 2, name: 'Galway Studios' },
{ id: 40, organisationId: 2, name: 'Limerick House' },
];
const namedIssues = [
{ id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' },
{ id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' },
{ id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' },
{ id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' },
{ id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' },
{ id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },
];
const fillerTitles = [
'Loose handrail on stairs',
'Bins not collected',
'Corridor light not working',
'Radiator cold in room 2',
'Window does not close fully',
'Loose floor tile at entrance',
'Toilet cistern keeps running',
'Blocked sink in kitchen',
];
// 24 extra issues (ids 107-130) alternate between buildings 10 and 20,
// so that lists have enough rows to page, sort and filter.
function fillerIssues() {
const priorities = ['low', 'medium', 'high', 'critical'];
const statuses = ['open', 'investigating', 'closed'];
const issues = [];
for (let i = 0; i < 24; i++) {
issues.push({
id: 107 + i,
buildingId: i % 2 === 0 ? 10 : 20,
title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`,
priority: priorities[i % priorities.length],
status: statuses[i % statuses.length],
occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(),
description: '',
});
}
return issues;
}
export const issues = [...namedIssues, ...fillerIssues()];
export const inspections = [
{ id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' },
{ id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' },
{ id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' },
{ id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },
];
export async function seed(client) {
await client.query('BEGIN');
try {
await client.query('TRUNCATE inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE');
for (const u of users) {
await client.query(
'INSERT INTO users (id, email, name, password_hash) VALUES ($1, $2, $3, $4)',
[u.id, u.email, u.name, await hashPassword(SEED_PASSWORD)],
);
}
for (const o of organisations) {
await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]);
}
for (const s of buildings) {
await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]);
}
for (const e of issues) {
await client.query(
`INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
[e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt],
);
}
for (const a of inspections) {
await client.query(
`INSERT INTO inspections (id, building_id, title, findings, status, submitted_at)
VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`,
[a.id, a.buildingId, a.title, a.findings, a.status],
);
if (a.status === 'submitted') {
await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]);
}
}
// Who reported each issue and created each inspection (see the scenario table in lesson 0.1).
await client.query(`UPDATE issues SET reported_by = CASE
WHEN id IN (101, 102) THEN 1 WHEN id IN (103, 104) THEN 4 WHEN id IN (105, 106) THEN 2
WHEN building_id = 10 THEN 1 WHEN building_id = 20 THEN 4 END`);
await client.query('UPDATE inspections SET created_by = CASE id WHEN 201 THEN 4 WHEN 202 THEN 1 WHEN 203 THEN 3 WHEN 204 THEN 2 END');
for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections']) {
await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
}
}
Each user gets their own hash, with its own salt, even though the password is the same. Hashing six passwords makes a seed noticeably slower (a fraction of a second); that slowness is the point of a password hash.
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
Run and inspect
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT id, email, name, left(password_hash, 44) || '…' AS password_hash_start FROM users ORDER BY id;
id | email | name | password_hash_start
----+--------------------+-------------+-----------------------------------------------
1 | alice@example.test | Alice Byrne | $argon2id$v=19$m=65536,t=3,p=4$aQhs/MIkL7ddJ…
2 | bob@example.test | Bob Okafor | $argon2id$v=19$m=65536,t=3,p=4$0qO2SLpqhekRf…
3 | carol@example.test | Carol Duffy | $argon2id$v=19$m=65536,t=3,p=4$9W4uZbfXLpiTe…
4 | dave@example.test | Dave Murphy | $argon2id$v=19$m=65536,t=3,p=4$PfkndC4IpZR4Y…
5 | nora@example.test | Nora Quinn | $argon2id$v=19$m=65536,t=3,p=4$UeLdWIzk90auj…
6 | ravi@example.test | Ravi Shah | $argon2id$v=19$m=65536,t=3,p=4$pZsA1tdvyaCJh…
(6 rows)Every hash starts with $argon2id$v=19$m=65536,t=3,p=4$: the algorithm, its version, 64 MiB of memory, 3 passes, 4 lanes. Then comes the salt, then the hash. Notice that alice's and bob's hashes differ although the passwords are identical: different salts.
Who reported what:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT e.id, e.title, u.email AS reported_byFROM issues e LEFT JOIN users u ON u.id = e.reported_byWHERE e.id BETWEEN 101 AND 106 ORDER BY e.id;
id | title | reported_by
-----+------------------------------------------+--------------------
101 | Lift stuck between floors 2 and 3 | alice@example.test
102 | Dripping tap in the second-floor kitchen | alice@example.test
103 | Front door lock sticks at entrance 4 | dave@example.test
104 | Water stain on the ceiling of flat 7 | dave@example.test
105 | Boiler lost pressure in plant room | bob@example.test
106 | Car park barrier stuck open | bob@example.test
(6 rows)Check the model from the command line. --input-type=module lets node -e use import:
node --env-file=.env --input-type=module -e "
import { verifyCredentials } from './src/models/users.js';
import { pool } from './src/db.js';
console.log('right:', (await verifyCredentials('Alice@Example.test', 'password123'))?.email);
console.log('wrong password:', await verifyCredentials('alice@example.test', 'password124'));
console.log('unknown email:', await verifyCredentials('mallory@example.test', 'password123'));
await pool.end();
"
right: alice@example.test
wrong password: null
unknown email: null
The email was matched in any case, and both failures look identical to the caller.
Experiment
How slow is "slow"? Time a few verifications, for a known and an unknown email:
node --env-file=.env --input-type=module -e "
import { verifyCredentials } from './src/models/users.js';
import { pool } from './src/db.js';
for (const email of ['alice@example.test', 'mallory@example.test']) {
const started = performance.now();
for (let i = 0; i < 5; i++) await verifyCredentials(email, 'not-the-password');
console.log(email === 'mallory@example.test' ? 'unknown email' : 'known email ', ((performance.now() - started) / 5).toFixed(0), 'ms per attempt');
}
await pool.end();
"
known email 23 ms per attempt
unknown email 21 ms per attempt
Reveal What the numbers mean
Both take roughly the same time, tens of milliseconds, because both run one argon2id verification. An attacker who steals the hashes can only try a small number of guesses per second per CPU core and per 64 MiB of memory, instead of billions. Your server pays the same cost per login, which is why Lesson 4.4 also limits how often one client may try.
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ a building can be created inside an organisation (215.208917ms)
✔ a duplicate building name in the same organisation is a field error (3.387375ms)
✔ the same building name is allowed in another organisation (8.073ms)
✔ a building with issues cannot be deleted (21.8085ms)
✔ an empty building can be deleted (7.38975ms)
✔ an organisation with buildings cannot be deleted, an empty one can (13.654208ms)
✔ the dashboard counts match the database (212.020041ms)
✔ every building appears with its organisation (4.372625ms)
✔ create a draft, edit it, submit it, approve it (223.727209ms)
✔ invalid transitions are refused with 409 and change nothing (7.71975ms)
✔ only drafts can be edited (3.099291ms)
✔ returning a submitted inspection makes it editable again (5.704208ms)
✔ concurrent approvals: exactly one wins (20.497458ms)
✔ unknown actions are 404 (2.183333ms)
✔ the list pages 10 at a time and reports the total (228.394209ms)
✔ pages do not overlap (13.757583ms)
✔ filters combine with AND (4.691125ms)
✔ sorting by priority puts critical first when descending (3.300125ms)
✔ unknown sort keys and SQL in the query string are ignored (21.910833ms)
✔ GET /issues lists issues from the database (215.359958ms)
✔ GET /issues/101 shows one issue with its building (5.099958ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (8.672875ms)
✔ POST /issues re-renders the form with errors (7.114625ms)
✔ POST /issues stores the issue and redirects to it (7.258125ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (10.535125ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.617084ms)
✔ an issue time in the future is rejected (2.247292ms)
✔ GET /issues/101/edit shows the current values (3.240292ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.166917ms)
✔ POST /issues/:id/delete removes the issue (5.390167ms)
✔ GET /organisations lists organisations with building counts (194.391292ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.239709ms)
✔ POST /organisations validates and creates (11.222375ms)
✔ POST /organisations/:id/edit renames the organisation (4.287708ms)
✔ unknown organisations are 404 (3.803708ms)
ℹ tests 35
Show 7 more lines
ℹ suites 0
ℹ pass 35
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2284.822459
The existing tests still pass: nothing uses users yet, and the seed (which tests also run) now creates them.
git add -A
git commit -m "Users and password hashing"
[main ea243f7] Users and password hashing
5 files changed, 213 insertions(+), 2 deletions(-)
create mode 100644 migrations/003_create_users.sql
create mode 100644 src/models/users.js
Symptom npm install argon2 fails with gyp ERR!
No prebuilt binary matched and compiling failed. On macOS run xcode-select --install; on Linux install build-essential and python3. Then install again.
Symptom new row for relation "users" violates check constraint "users_email_check"
An email was inserted with capital letters. Always pass emails through normaliseEmail.
Recap and next step
Passwords are stored as argon2id hashes with per-password salts. The users model never returns the hash, never says which half of a login was wrong, and takes the same time either way. Issues and inspections now record their reporter and creator.
Users exist, but nobody can log in. Next: registration, login, logout, and the session cookie that ties a browser to a user.
Open the checkpoint files for lesson 4.1 (separate page; only files from this lesson and earlier)