Checkpoint · Lesson 5.1
Memberships, building roles and the access matrix: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m05-l01 -- src.
Files changed in this lesson
migrations/005_create_memberships_and_building_roles.sql added
migrations/005_create_memberships_and_building_roles.sqlCREATE 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);
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);src/app.js changed
src/app.jsimport 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 });});src/middleware/auth.js changed
src/middleware/auth.jsimport { 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');}src/models/access.js added
src/models/access.jsimport { 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 };
}
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 };}src/routes/account.js added
src/routes/account.jsimport express from 'express';
export const accountRouter = express.Router();
accountRouter.get('/', (req, res) => {
res.render('account', { title: 'My access', access: req.user.access });
});
import express from 'express'; export const accountRouter = express.Router(); accountRouter.get('/', (req, res) => { res.render('account', { title: 'My access', access: req.user.access });});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()];
// 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; }}test/access.test.js added
test/access.test.jsimport { 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/);
});
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/);});views/account.ejs added
views/account.ejs<%- 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') %>
<%- 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') %>views/partials/nav.ejs changed
views/partials/nav.ejs<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>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
migrations/004_create_session_table.sql
migrations/005_create_memberships_and_building_roles.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/middleware/auth.js
src/middleware/csrf.js
src/middleware/flash.js
src/middleware/rate-limit.js
src/migrate.js
src/models/access.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/account.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/access.test.js
test/auth.test.js
test/buildings.test.js
test/csrf.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
test/rate-limit.test.js
test/require-login.test.js
views/account.ejs
views/auth/login.ejs
views/auth/register.ejs
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