Checkpoint · Lesson 4.1
Users and password hashing: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m04-l01 -- src.
Files changed in this lesson
migrations/003_create_users.sql added
migrations/003_create_users.sqlCREATE 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;
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;package-lock.json changed
Generated by npm from package.json. Do not edit it by hand; run the npm commands from the lesson.
package.json changed
package.json{
"name": "caretaker",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec \"test/**/*.test.js\"",
"start": "node --env-file=.env src/server.js",
"dev": "node --env-file=.env --watch src/server.js",
"db:migrate": "node --env-file=.env scripts/migrate.js",
"db:seed": "node --env-file=.env scripts/seed.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"dependencies": {
"argon2": "0.45.2",
"ejs": "7.0.2",
"express": "5.3.0",
"pg": "8.23.1"
},
"devDependencies": {
"supertest": "7.3.2"
}
}
{ "name": "caretaker", "version": "1.0.0", "description": "", "scripts": { "test": "node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec \"test/**/*.test.js\"", "start": "node --env-file=.env src/server.js", "dev": "node --env-file=.env --watch src/server.js", "db:migrate": "node --env-file=.env scripts/migrate.js", "db:seed": "node --env-file=.env scripts/seed.js" }, "keywords": [], "author": "", "license": "ISC", "type": "module", "dependencies": { "argon2": "0.45.2", "ejs": "7.0.2", "express": "5.3.0", "pg": "8.23.1" }, "devDependencies": { "supertest": "7.3.2" }}src/models/users.js added
src/models/users.jsimport 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;
}
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;}src/seed.js changed
src/seed.jsimport { 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; }}Project tree at this checkpoint
.env.example
.env.test
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
migrations/002_create_inspections.sql
migrations/003_create_users.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/migrate.js
scripts/seed.js
src/app.js
src/config.js
src/db.js
src/lib/ids.js
src/lib/validation.js
src/migrate.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/organisations.js
src/models/users.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/buildings.test.js
test/dashboard.test.js
test/helpers.js
test/inspections.test.js
test/issue-list.test.js
test/issues.test.js
test/organisations.test.js
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.ejs
views/issues/form.ejs
views/issues/index.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs