Module 5 · Authorization before Cedar
5.1 Memberships, building roles and the access matrix
Store who belongs to which organisation and who holds which role at which building, load it for every request, and write down the exact access matrix we will enforce.
Starting point
Users authenticate, and req.user comes from the session. Nothing records what any user may do, so every logged-in user can do everything, as Nora showed in lesson 4.4.
Outcome
migrations/005_create_memberships_and_building_roles.sqlsrc/models/access.jssrc/routes/account.js views/account.ejstest/access.test.jsmemberships: which users belong to which organisations, asmemberororg_admin.building_role_assignments: which users hold which role at which building, with who granted it and when, and who revoked it and when.req.user.accessholds the current user's active memberships and assignments, loaded fresh on every request.- A My access page shows them, and the lesson defines the access matrix the rest of the course enforces.
The problem
Before we write a single if, we need two things that are easy to skip and expensive to get wrong:
- Data that describes permissions. Not a hard-coded list of admin emails, and not a role stored in the session (it would not change until the user logs in again).
- An exact specification. "Alice can manage her building" is not testable. "Alice may edit issue 101 and may not edit issue 103" is.
Build it
1. The roles
Two levels, as introduced in lesson 0.1:
| Level | Role | Grants |
|---|---|---|
| Organisation | member |
See the organisation and the names of its buildings. Nothing inside a building. |
| Organisation | org_admin |
Everything building_admin can do, at every building of that organisation, plus managing the organisation itself, its buildings and its members. |
| Building | viewer |
See the building, its issues and its inspections. |
| Building | reporter |
Viewer, plus report issues at the building and edit their own issues while they are not closed. |
| Building | inspector |
Viewer, plus create inspections at the building and edit and submit their own draft inspections. |
| Building | building_admin |
Everything at that building: edit and delete any issue, edit, submit, approve and return any inspection, update the building, and (Module 7) grant and revoke viewer, reporter and inspector roles at the building. |
Three statements define what is inherited and what is not:
- A role at a building applies to that building only. Alice's admin role at building 10 gives her nothing at building 20; she needed a separate viewer assignment there.
- Roles within a building form a ladder:
building_adminincludes everythingviewercan do at that building. org_adminapplies to every building whose organisation is that organisation, including buildings created later. That is inheritance through a relationship (building → organisation), not through a list of assignments.
2. The migration
CREATE TABLE memberships ( user_id integer NOT NULL REFERENCES users (id) ON DELETE CASCADE, organisation_id integer NOT NULL REFERENCES organisations (id) ON DELETE CASCADE, role text NOT NULL CHECK (role IN ('member', 'org_admin')), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (user_id, organisation_id)); CREATE INDEX memberships_organisation_id_idx ON memberships (organisation_id); CREATE TABLE building_role_assignments ( id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, user_id integer NOT NULL REFERENCES users (id) ON DELETE CASCADE, building_id integer NOT NULL REFERENCES buildings (id) ON DELETE CASCADE, role text NOT NULL CHECK (role IN ('viewer', 'reporter', 'inspector', 'building_admin')), granted_by integer REFERENCES users (id) ON DELETE SET NULL, granted_at timestamptz NOT NULL DEFAULT now(), revoked_by integer REFERENCES users (id) ON DELETE SET NULL, revoked_at timestamptz); -- At most one ACTIVE assignment of each role per user and building. Revoked rows are history.CREATE UNIQUE INDEX building_role_assignments_active_idx ON building_role_assignments (user_id, building_id, role) WHERE revoked_at IS NULL; CREATE INDEX building_role_assignments_building_id_idx ON building_role_assignments (building_id);- A membership is one row per user and organisation, so the primary key is the pair.
- Assignments are never deleted when revoked. Revoking sets
revoked_atandrevoked_by. "Who had access to building 30 on 15 November?" stays answerable. - A partial unique index (
WHERE revoked_at IS NULL) allows any number of revoked rows but only one active row for each user, building and role. - Deleting a user or a building removes their memberships and assignments (
CASCADE). Those rows mean nothing without both ends.
npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
applied 005_create_memberships_and_building_roles.sql
migrations are up to date
3. Seed the scenario
Add the scenario's memberships and assignments to src/seed.js:
// Organisation memberships: [userId, organisationId, role]export const memberships = [ [1, 1, 'member'], // alice, Liffey [2, 2, 'member'], // bob, Harbour Lets [3, 1, 'org_admin'], // carol, Liffey [4, 1, 'member'], // dave, Liffey [6, 2, 'member'], // ravi, Harbour Lets]; // Building role assignments. Ravi's was revoked by Bob on 20 November.export const assignments = [ { id: 1, userId: 1, buildingId: 10, role: 'building_admin', grantedBy: 3 }, { id: 2, userId: 1, buildingId: 20, role: 'viewer', grantedBy: 3 }, { id: 3, userId: 2, buildingId: 30, role: 'building_admin', grantedBy: null }, { id: 4, userId: 4, buildingId: 10, role: 'inspector', grantedBy: 1 }, { id: 5, userId: 4, buildingId: 20, role: 'reporter', grantedBy: 3 }, { id: 6, userId: 6, buildingId: 30, role: 'viewer', grantedBy: 2, revokedBy: 2, revokedAt: '2026-11-20T10:00:00Z' },]; export const inspections = [
await client.query('TRUNCATE inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE'); await client.query('TRUNCATE building_role_assignments, memberships, inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE');
for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections']) { for (const [userId, organisationId, role] of memberships) { await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]); } for (const a of assignments) { await client.query( `INSERT INTO building_role_assignments (id, user_id, building_id, role, granted_by, granted_at, revoked_by, revoked_at) VALUES ($1, $2, $3, $4, $5, '2026-11-01T09:00:00Z', $6, $7)`, [a.id, a.userId, a.buildingId, a.role, a.grantedBy, a.revokedBy ?? null, a.revokedAt ?? null], ); } for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments']) {
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()]; // Organisation memberships: [userId, organisationId, role]export const memberships = [ [1, 1, 'member'], // alice, Liffey [2, 2, 'member'], // bob, Harbour Lets [3, 1, 'org_admin'], // carol, Liffey [4, 1, 'member'], // dave, Liffey [6, 2, 'member'], // ravi, Harbour Lets]; // Building role assignments. Ravi's was revoked by Bob on 20 November.export const assignments = [ { id: 1, userId: 1, buildingId: 10, role: 'building_admin', grantedBy: 3 }, { id: 2, userId: 1, buildingId: 20, role: 'viewer', grantedBy: 3 }, { id: 3, userId: 2, buildingId: 30, role: 'building_admin', grantedBy: null }, { id: 4, userId: 4, buildingId: 10, role: 'inspector', grantedBy: 1 }, { id: 5, userId: 4, buildingId: 20, role: 'reporter', grantedBy: 3 }, { id: 6, userId: 6, buildingId: 30, role: 'viewer', grantedBy: 2, revokedBy: 2, revokedAt: '2026-11-20T10:00:00Z' },]; 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 building_role_assignments, memberships, 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 [userId, organisationId, role] of memberships) { await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]); } for (const a of assignments) { await client.query( `INSERT INTO building_role_assignments (id, user_id, building_id, role, granted_by, granted_at, revoked_by, revoked_at) VALUES ($1, $2, $3, $4, $5, '2026-11-01T09:00:00Z', $6, $7)`, [a.id, a.userId, a.buildingId, a.role, a.grantedBy, a.revokedBy ?? null, a.revokedAt ?? null], ); } for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments']) { 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()];
// Organisation memberships: [userId, organisationId, role]
export const memberships = [
[1, 1, 'member'], // alice, Liffey
[2, 2, 'member'], // bob, Harbour Lets
[3, 1, 'org_admin'], // carol, Liffey
[4, 1, 'member'], // dave, Liffey
[6, 2, 'member'], // ravi, Harbour Lets
];
// Building role assignments. Ravi's was revoked by Bob on 20 November.
export const assignments = [
{ id: 1, userId: 1, buildingId: 10, role: 'building_admin', grantedBy: 3 },
{ id: 2, userId: 1, buildingId: 20, role: 'viewer', grantedBy: 3 },
{ id: 3, userId: 2, buildingId: 30, role: 'building_admin', grantedBy: null },
{ id: 4, userId: 4, buildingId: 10, role: 'inspector', grantedBy: 1 },
{ id: 5, userId: 4, buildingId: 20, role: 'reporter', grantedBy: 3 },
{ id: 6, userId: 6, buildingId: 30, role: 'viewer', grantedBy: 2, revokedBy: 2, revokedAt: '2026-11-20T10:00:00Z' },
];
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 building_role_assignments, memberships, 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 [userId, organisationId, role] of memberships) {
await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]);
}
for (const a of assignments) {
await client.query(
`INSERT INTO building_role_assignments (id, user_id, building_id, role, granted_by, granted_at, revoked_by, revoked_at)
VALUES ($1, $2, $3, $4, $5, '2026-11-01T09:00:00Z', $6, $7)`,
[a.id, a.userId, a.buildingId, a.role, a.grantedBy, a.revokedBy ?? null, a.revokedAt ?? null],
);
}
for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments']) {
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;
}
}
Nora (user 5) appears in neither list: she is registered and nothing more.
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
4. Load the user's access on every request
Create src/models/access.js:
import { query } from '../db.js'; // The current user's ACTIVE memberships and building role assignments.export async function loadAccess(userId) { const [memberships, assignments] = await Promise.all([ query( `SELECT m.organisation_id, o.name AS organisation_name, m.role FROM memberships m JOIN organisations o ON o.id = m.organisation_id WHERE m.user_id = $1 ORDER BY o.name`, [userId], ), query( `SELECT a.building_id, s.name AS building_name, s.organisation_id, a.role FROM building_role_assignments a JOIN buildings s ON s.id = a.building_id WHERE a.user_id = $1 AND a.revoked_at IS NULL ORDER BY s.id, a.role`, [userId], ), ]); return { memberships: memberships.rows, assignments: assignments.rows };}revoked_at IS NULLis where revocation takes effect. Revoked rows never reach the application.- Each assignment carries the building's
organisation_id. A role at a building is meaningless without knowing which tenant that building belongs to.
Attach it in loadUser:
import { findUserById } from '../models/users.js';import { loadAccess } from '../models/access.js';
if (!req.user) { // The account no longer exists. Forget it. delete req.session.userId; } else { req.user.access = await loadAccess(req.user.id); }
Show the whole src/middleware/auth.js after this change
import { findUserById } from '../models/users.js';import { loadAccess } from '../models/access.js'; // Turns the session's userId into req.user (or null) for every request.export async function loadUser(req, res, next) { req.user = null; if (req.session.userId) { req.user = await findUserById(req.session.userId); if (!req.user) { // The account no longer exists. Forget it. delete req.session.userId; } else { req.user.access = await loadAccess(req.user.id); } } res.locals.currentUser = req.user; next();} // Everything mounted after this middleware needs a logged-in user.export function requireLogin(req, res, next) { if (req.user) { return next(); } if (req.method === 'GET') { req.session.returnTo = req.originalUrl; } req.flash('error', 'Please log in to continue.'); res.redirect(303, '/login');}import { findUserById } from '../models/users.js';
import { loadAccess } from '../models/access.js';
// Turns the session's userId into req.user (or null) for every request.
export async function loadUser(req, res, next) {
req.user = null;
if (req.session.userId) {
req.user = await findUserById(req.session.userId);
if (!req.user) {
// The account no longer exists. Forget it.
delete req.session.userId;
} else {
req.user.access = await loadAccess(req.user.id);
}
}
res.locals.currentUser = req.user;
next();
}
// Everything mounted after this middleware needs a logged-in user.
export function requireLogin(req, res, next) {
if (req.user) {
return next();
}
if (req.method === 'GET') {
req.session.returnTo = req.originalUrl;
}
req.flash('error', 'Please log in to continue.');
res.redirect(303, '/login');
}
Fresh on every request is a deliberate choice. If Bob revokes Ravi's role, Ravi's very next request is decided with the new data. The cost is two small indexed queries per request. Caching this data would make revocation slower to take effect; Module 9 returns to that trade-off.
5. A "My access" page
Users (and you, while debugging) should be able to see what the server believes about them. Create src/routes/account.js:
import express from 'express'; export const accountRouter = express.Router(); accountRouter.get('/', (req, res) => { res.render('account', { title: 'My access', access: req.user.access });});<%- include('partials/head') %><h1>My access</h1><p class="muted">Signed in as <%= currentUser.email %>. This is what Caretaker loaded from the database for this request.</p> <h2>Organisations</h2><% if (access.memberships.length === 0) { %> <p class="empty">You are not a member of any organisation.</p><% } else { %> <table class="data"> <thead><tr><th>Organisation</th><th>Role</th></tr></thead> <tbody> <% for (const m of access.memberships) { %> <tr><td><%= m.organisation_name %></td><td><span class="badge role-badge"><%= m.role %></span></td></tr> <% } %> </tbody> </table><% } %> <h2>Building roles</h2><% if (access.assignments.length === 0) { %> <p class="empty">You have no roles at any building.</p><% } else { %> <table class="data"> <thead><tr><th>Building</th><th>Role</th></tr></thead> <tbody> <% for (const a of access.assignments) { %> <tr><td>#<%= a.building_id %> <%= a.building_name %></td><td><span class="badge role-badge"><%= a.role %></span></td></tr> <% } %> </tbody> </table><% } %><%- include('partials/foot') %>Mount it (after requireLogin, like every other router) and link to it:
import { authRouter } from './routes/auth.js';import { accountRouter } from './routes/account.js';
app.use('/account', accountRouter);app.use('/issues', issuesRouter);
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { csrf } from './middleware/csrf.js';import { authRouter } from './routes/auth.js';import { accountRouter } from './routes/account.js';import { issuesRouter } from './routes/issues.js';import { organisationsRouter } from './routes/organisations.js';import { buildingsRouter } from './routes/buildings.js';import { inspectionsRouter } from './routes/inspections.js';import { getDashboard } from './models/dashboard.js'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });app.locals.currentUser = null;app.locals.flash = null;app.locals.csrfToken = ''; const PgSession = connectPgSimple(session); app.use((req, res, next) => { if (process.env.NODE_ENV === 'test') { return next(); } const started = Date.now(); res.on('finish', () => { console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`); }); next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false }));app.use(session({ store: new PgSession({ pool, tableName: 'session', pruneSessionInterval: config.env === 'test' ? false : 900 }), name: 'caretaker.sid', secret: config.sessionSecret, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax', secure: config.cookieSecure, maxAge: 8 * 60 * 60 * 1000, },}));app.use(loadUser);app.use(flash);app.use(csrf); app.use(authRouter);app.use(requireLogin); app.get('/', async (req, res) => { res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });}); app.use('/account', accountRouter);app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); app.use((req, res) => { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });}); app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) { console.error(err); } const message = err.expose ? err.message : 'Something went wrong'; res.status(status).render('error', { title: 'Error', status, message });});import express from 'express';
import path from 'node:path';
import session from 'express-session';
import connectPgSimple from 'connect-pg-simple';
import { config } from './config.js';
import { pool } from './db.js';
import { loadUser, requireLogin } from './middleware/auth.js';
import { flash } from './middleware/flash.js';
import { csrf } from './middleware/csrf.js';
import { authRouter } from './routes/auth.js';
import { accountRouter } from './routes/account.js';
import { issuesRouter } from './routes/issues.js';
import { organisationsRouter } from './routes/organisations.js';
import { buildingsRouter } from './routes/buildings.js';
import { inspectionsRouter } from './routes/inspections.js';
import { getDashboard } from './models/dashboard.js';
export const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(import.meta.dirname, '..', 'views'));
app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });
app.locals.currentUser = null;
app.locals.flash = null;
app.locals.csrfToken = '';
const PgSession = connectPgSimple(session);
app.use((req, res, next) => {
if (process.env.NODE_ENV === 'test') {
return next();
}
const started = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);
});
next();
});
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));
app.use(express.urlencoded({ extended: false }));
app.use(session({
store: new PgSession({ pool, tableName: 'session', pruneSessionInterval: config.env === 'test' ? false : 900 }),
name: 'caretaker.sid',
secret: config.sessionSecret,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
sameSite: 'lax',
secure: config.cookieSecure,
maxAge: 8 * 60 * 60 * 1000,
},
}));
app.use(loadUser);
app.use(flash);
app.use(csrf);
app.use(authRouter);
app.use(requireLogin);
app.get('/', async (req, res) => {
res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });
});
app.use('/account', accountRouter);
app.use('/issues', issuesRouter);
app.use('/organisations', organisationsRouter);
app.use('/buildings', buildingsRouter);
app.use('/inspections', inspectionsRouter);
app.use((req, res) => {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) {
console.error(err);
}
const message = err.expose ? err.message : 'Something went wrong';
res.status(status).render('error', { title: 'Error', status, message });
});
<a class="link-button" href="/account">My access</a> <span>Signed in as <strong><%= currentUser.name %></strong></span>
Show the whole views/partials/nav.ejs after this change
<header class="site-header"> <div class="container header-inner"> <a class="brand" href="/">Caretaker</a> <nav class="main-nav" aria-label="Main"> <a href="/issues">Issues</a> <a href="/inspections">Inspections</a> <a href="/organisations">Organisations</a> </nav> <div class="user-nav"> <% if (currentUser) { %> <a class="link-button" href="/account">My access</a> <span>Signed in as <strong><%= currentUser.name %></strong></span> <form method="post" action="/logout"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="link-button">Log out</button></form> <% } else { %> <a class="link-button" href="/login">Log in</a> <% } %> </div> </div></header><header class="site-header">
<div class="container header-inner">
<a class="brand" href="/">Caretaker</a>
<nav class="main-nav" aria-label="Main">
<a href="/issues">Issues</a>
<a href="/inspections">Inspections</a>
<a href="/organisations">Organisations</a>
</nav>
<div class="user-nav">
<% if (currentUser) { %>
<a class="link-button" href="/account">My access</a>
<span>Signed in as <strong><%= currentUser.name %></strong></span>
<form method="post" action="/logout"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="link-button">Log out</button></form>
<% } else { %>
<a class="link-button" href="/login">Log in</a>
<% } %>
</div>
</div>
</header>
Run and inspect
LOG_SQL=1 npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000

Every request now runs the two access queries after loading the user. Log in as Alice with curl and look at the server log:
rm -f /tmp/alice.txt
TOKEN=$(curl -s -c /tmp/alice.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/alice.txt -c /tmp/alice.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=alice@example.test -d password=password123
curl -s -b /tmp/alice.txt -o /dev/null http://localhost:3000/account
(no output)
POST /login -> 303 (32 ms)
SQL 2ms SELECT id, email, name, created_at FROM users WHERE id = $1 [1]
SQL 1ms SELECT a.building_id, s.name AS building_name, s.organisation_id, a.role FROM building_role_assignments a JOIN buildings s ON s.id = a.building_id WHERE a.user_id = $1 AND a.revoked_at IS NULL ORDER BY s.id, a.role [1]
SQL 1ms SELECT m.organisation_id, o.name AS organisation_name, m.role FROM memberships m JOIN organisations o ON o.id = m.organisation_id WHERE m.user_id = $1 ORDER BY o.name [1]
GET /account -> 200 (6 ms)
The chain for this request: cookie → session row → userId 1 → users row → memberships and building_role_assignments rows → req.user.access.
The access matrix
This table is the specification. Every cell becomes a test in lesson 5.4 and stays green through Modules 6 to 8. "404" means the user may not even know the resource exists (lesson 5.2 explains when we answer 404 rather than 403).
| Request | alice | bob | carol | dave | nora | ravi |
|---|---|---|---|---|---|---|
| View issue 101 (building 10) | ✓ admin | 404 | ✓ inherited | ✓ inspector | 404 | 404 |
| Edit issue 101 | ✓ | 404 | ✓ | ✗ 403 | 404 | 404 |
| View issue 103 (building 20) | ✓ viewer | 404 | ✓ | ✓ reporter | 404 | 404 |
| Edit issue 103 (Dave's) | ✗ 403 | 404 | ✓ | ✓ own | 404 | 404 |
| Report an issue at building 20 | ✗ | ✗ | ✓ | ✓ | ✗ | ✗ |
| View issue 105 (building 30) | 404 | ✓ | 404 | 404 | 404 | 404 revoked |
| View issue 106 (building 40) | 404 | 404 (reported it, no role) | 404 | 404 | 404 | 404 |
| Approve inspection 201 (Dave's) | ✓ | 404 | ✓ | ✗ 403 | 404 | 404 |
| Approve inspection 202 (Alice's) | ✗ 403 (own inspection) | 404 | ✓ | ✗ 403 | 404 | 404 |
| Update organisation 1 | ✗ 403 | 404 | ✓ | ✗ 403 | 404 | 404 |
| Issues in the list | buildings 10, 20 | building 30 | buildings 10, 20 | buildings 10, 20 | none | none |
Read a few cells against the role table above. Bob reported issue 106 but holds no role at building 40, so he cannot see it: being the reporter is a fact about the issue, not a permission. Ravi's only role was revoked, so he is exactly where Nora is. Carol has no building assignments at all, yet sees buildings 10 and 20, because her role is on the organisation.
Experiment
Grant Nora a role directly in SQL, as an administrator might, and watch her existing session pick it up. Log Nora in once with curl and keep her cookie jar:
rm -f /tmp/nora.txt
TOKEN=$(curl -s -c /tmp/nora.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/nora.txt -c /tmp/nora.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=nora@example.test -d password=password123
curl -s -b /tmp/nora.txt http://localhost:3000/account | grep -E "empty|role-badge"
<p class="empty">You are not a member of any organisation.</p>
<p class="empty">You have no roles at any building.</p>
Now an administrator changes the data:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.INSERT INTO memberships (user_id, organisation_id, role) VALUES (5, 2, 'member');INSERT INTO building_role_assignments (user_id, building_id, role, granted_by) VALUES (5, 40, 'viewer', 2) RETURNING id, role, granted_at;
INSERT 0 1
id | role | granted_at
----+--------+-------------------------------
7 | viewer | 2026-11-28 14:41:31.613242+00
(1 row)
INSERT 0 1curl -s -b /tmp/nora.txt http://localhost:3000/account | grep -E "empty|role-badge|#40"
<tr><td>Harbour Lets</td><td><span class="badge role-badge">member</span></td></tr>
<tr><td>#40 Limerick House</td><td><span class="badge role-badge">viewer</span></td></tr>
Reveal Why it worked immediately
The session holds only userId. Everything else is loaded from the database for each request. Now revoke it the way the app will, by setting revoked_at, and ask again with the same cookie: the role disappears just as fast.
docker compose exec db psql -U caretaker caretaker, then paste the SQL.UPDATE building_role_assignments SET revoked_at = now(), revoked_by = 2 WHERE user_id = 5 AND revoked_at IS NULL;DELETE FROM memberships WHERE user_id = 5;SELECT user_id, building_id, role, revoked_at IS NOT NULL AS revoked FROM building_role_assignments WHERE user_id IN (5, 6) ORDER BY id;
UPDATE 1
DELETE 1
user_id | building_id | role | revoked
---------+-------------+--------+---------
6 | 30 | viewer | t
5 | 40 | viewer | t
(2 rows)curl -s -b /tmp/nora.txt http://localhost:3000/account | grep -E "empty|role-badge"
<p class="empty">You are not a member of any organisation.</p>
<p class="empty">You have no roles at any building.</p>
Both revoked rows stay in the table as history. Re-seed to return to the scenario:
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
Checkpoint
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { loadAccess } from '../src/models/access.js';import { resetDatabase, loginAs } from './helpers.js'; before(resetDatabase);after(() => pool.end()); const summary = (access) => ({ memberships: access.memberships.map((m) => `${m.organisation_id}:${m.role}`), assignments: access.assignments.map((a) => `${a.building_id}:${a.role}`),}); test('the scenario loads exactly as specified', async () => { assert.deepEqual(summary(await loadAccess(1)), { memberships: ['1:member'], assignments: ['10:building_admin', '20:viewer'] }); assert.deepEqual(summary(await loadAccess(2)), { memberships: ['2:member'], assignments: ['30:building_admin'] }); assert.deepEqual(summary(await loadAccess(3)), { memberships: ['1:org_admin'], assignments: [] }); assert.deepEqual(summary(await loadAccess(4)), { memberships: ['1:member'], assignments: ['10:inspector', '20:reporter'] }); assert.deepEqual(summary(await loadAccess(5)), { memberships: [], assignments: [] }); assert.deepEqual(summary(await loadAccess(6)), { memberships: ['2:member'], assignments: [] }, 'revoked roles are not loaded');}); test('only one active assignment per user, building and role', async () => { await assert.rejects( pool.query("INSERT INTO building_role_assignments (user_id, building_id, role) VALUES (1, 10, 'building_admin')"), { code: '23505' }, );}); test('a revoked role can be granted again', async () => { const { rowCount } = await pool.query("INSERT INTO building_role_assignments (user_id, building_id, role) VALUES (6, 30, 'viewer')"); assert.equal(rowCount, 1);}); test('the My access page shows what the server loaded', async () => { const dave = await loginAs('dave'); const res = await dave.get('/account'); assert.match(res.text, /#10 Dublin Offices<\/td><td><span class="badge role-badge">inspector/); assert.match(res.text, /#20 Cork Apartments<\/td><td><span class="badge role-badge">reporter/);});npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ the scenario loads exactly as specified (208.0645ms)
✔ only one active assignment per user, building and role (0.867666ms)
✔ a revoked role can be granted again (1.69125ms)
✔ the My access page shows what the server loaded (80.670042ms)
✔ a correct login creates a session and shows the user (278.741291ms)
✔ a wrong password or unknown email gets the same 401 (57.585583ms)
✔ registration validates, creates a user, and logs them in (50.626ms)
✔ registering an existing email is a field error (30.087583ms)
✔ logout destroys the session (60.400791ms)
✔ a building can be created inside an organisation (270.795041ms)
✔ a duplicate building name in the same organisation is a field error (5.29425ms)
✔ the same building name is allowed in another organisation (5.183125ms)
✔ a building with issues cannot be deleted (12.104542ms)
✔ an empty building can be deleted (9.630375ms)
✔ an organisation with buildings cannot be deleted, an empty one can (20.549458ms)
✔ a logged-in POST without a token is refused with 403 (272.148917ms)
✔ a token from another session is refused (36.036792ms)
✔ the right token in the form field works (11.02625ms)
✔ every POST form on every page carries the token (42.238958ms)
✔ the dashboard counts match the database (259.806416ms)
✔ every building appears with its organisation (4.525209ms)
✔ create a draft, edit it, submit it, approve it (287.032875ms)
✔ invalid transitions are refused with 409 and change nothing (11.4575ms)
✔ only drafts can be edited (4.939958ms)
✔ returning a submitted inspection makes it editable again (6.935875ms)
✔ concurrent approvals: exactly one wins (21.4045ms)
✔ unknown actions are 404 (3.257417ms)
✔ the list pages 10 at a time and reports the total (285.798292ms)
✔ pages do not overlap (15.594334ms)
✔ filters combine with AND (5.412792ms)
✔ sorting by priority puts critical first when descending (4.413375ms)
✔ unknown sort keys and SQL in the query string are ignored (25.07ms)
✔ GET /issues lists issues from the database (269.214916ms)
✔ GET /issues/101 shows one issue with its building (5.728042ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (13.238917ms)
✔ POST /issues re-renders the form with errors (4.5385ms)
Show 28 more lines
✔ POST /issues stores the issue and redirects to it (7.124041ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (3.929ms)
✔ the stored row has the cleaned values and ignores a client-sent status (5.478083ms)
✔ an issue time in the future is rejected (3.91775ms)
✔ GET /issues/101/edit shows the current values (3.881875ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.290959ms)
✔ POST /issues/:id/delete removes the issue (9.011166ms)
✔ GET /organisations lists organisations with building counts (263.935708ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (5.754ms)
✔ POST /organisations validates and creates (10.177208ms)
✔ POST /organisations/:id/edit renames the organisation (7.772916ms)
✔ unknown organisations are 404 (6.4125ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (339.187958ms)
✔ anonymous requests are redirected to the login page (216.874208ms)
✔ anonymous writes are refused and change nothing (11.326209ms)
✔ login and register pages stay public (5.254375ms)
✔ login issues a new session id (no session fixation) (32.804833ms)
✔ returnTo only follows local paths (28.341833ms)
✔ new issues and transitions record the logged-in user (76.299958ms)
✔ the session cookie has the attributes we chose (26.249834ms)
ℹ tests 56
ℹ suites 0
ℹ pass 56
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5289.676833
git add -A
git commit -m "Memberships and building roles"
[main 6947909] Memberships and building roles
9 files changed, 168 insertions(+), 2 deletions(-)
create mode 100644 migrations/005_create_memberships_and_building_roles.sql
create mode 100644 src/models/access.js
create mode 100644 src/routes/account.js
create mode 100644 test/access.test.js
create mode 100644 views/account.ejs
Symptom duplicate key value violates unique constraint "building_role_assignments_active_idx" in the seed
An assignment appears twice in the assignments list with the same user, building and role, and neither is revoked.
Symptom My access is empty for Alice
The seed did not run after the migration, or loadAccess filters out everything. Check SELECT * FROM building_role_assignments WHERE user_id = 1; in psql.
Recap and next step
Permissions are now data: memberships at organisation level, role assignments at building level, revocations kept as history. Every request loads the current user's active access from the database. And we have an exact access matrix, with the reasons behind each cell.
Nothing enforces it yet. Next lesson we write the first checks, for issues, in plain JavaScript.
Open the checkpoint files for lesson 5.1 (separate page; only files from this lesson and earlier)