Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 5.3

Lists and tenant isolation: checkpoint files

Git tag in the reference repository
lesson/m05-l03 (commit bbf92aa)
Replay result
All steps replayed from an empty folder
Tests at this point
pass (tests 69, pass 69, fail 0)

Compare your folder with the reference using Git, if you cloned it: git diff lesson/m05-l03 -- src.

Files changed in this lesson

src/app.js changed

src/app.js
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 { can } from './authz/rules.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.use((req, res, next) => {  res.locals.can = (action, resource) => can(req.user, action, resource);  next();}); app.get('/', async (req, res) => {  res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard(req.user.id) });}); 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/models/buildings.js changed

src/models/buildings.js
import { query } from '../db.js';import { visibleBuildingCondition } from './scope.js'; export async function listVisibleBuildings(userId) {  const { rows } = await query(    `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name     FROM buildings s     JOIN organisations o ON o.id = s.organisation_id     WHERE ${visibleBuildingCondition('s', '$1')}     ORDER BY o.name, s.name`,    [userId],  );  return rows;} export async function listBuildings() {  const { rows } = await query(    `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name     FROM buildings s     JOIN organisations o ON o.id = s.organisation_id     ORDER BY o.name, s.name`,  );  return rows;} export async function findBuilding(id) {  const { rows } = await query(    `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name, s.created_at, s.updated_at     FROM buildings s     JOIN organisations o ON o.id = s.organisation_id     WHERE s.id = $1`,    [id],  );  return rows[0] ?? null;} export async function createBuilding({ organisation_id, name }) {  const { rows } = await query(    'INSERT INTO buildings (organisation_id, name) VALUES ($1, $2) RETURNING id',    [organisation_id, name],  );  return rows[0];} export async function updateBuilding(id, { name }) {  const { rows } = await query('UPDATE buildings SET name = $2, updated_at = now() WHERE id = $1 RETURNING id', [id, name]);  return rows[0] ?? null;} export async function deleteBuilding(id) {  const { rowCount } = await query('DELETE FROM buildings WHERE id = $1', [id]);  return rowCount === 1;} export async function listBuildingsForOrganisation(organisationId) {  const { rows } = await query(    `SELECT s.id, s.name, count(e.id)::int AS issue_count     FROM buildings s     LEFT JOIN issues e ON e.building_id = s.id     WHERE s.organisation_id = $1     GROUP BY s.id     ORDER BY s.name`,    [organisationId],  );  return rows;}

src/models/dashboard.js changed

src/models/dashboard.js
import { query } from '../db.js';import { listIssues } from './issues.js';import { visibleBuildingCondition } from './scope.js'; export async function getDashboard(userId) {  const visible = visibleBuildingCondition('s', '$1');  const [issueCounts, inspectionCounts, buildings, recent] = await Promise.all([    query(      `SELECT count(*) FILTER (WHERE e.status <> 'closed')::int AS open_issues,              count(*) FILTER (WHERE e.status <> 'closed' AND e.priority IN ('high', 'critical'))::int AS serious_open_issues       FROM issues e       JOIN buildings s ON s.id = e.building_id       WHERE ${visible}`,      [userId],    ),    query(      `SELECT count(*)::int AS awaiting_approval       FROM inspections a       JOIN buildings s ON s.id = a.building_id       WHERE a.status = 'submitted' AND ${visible}`,      [userId],    ),    query(      `SELECT s.id, s.name, o.name AS organisation_name,              count(e.id) FILTER (WHERE e.status <> 'closed')::int AS open_issues,              count(e.id)::int AS total_issues       FROM buildings s       JOIN organisations o ON o.id = s.organisation_id       LEFT JOIN issues e ON e.building_id = s.id       WHERE ${visible}       GROUP BY s.id, o.name       ORDER BY o.name, s.name`,      [userId],    ),    listIssues({ userId, perPage: 5 }),  ]);  return {    ...issueCounts.rows[0],    ...inspectionCounts.rows[0],    buildings: buildings.rows,    recentIssues: recent.issues,  };}

src/models/inspections.js changed

src/models/inspections.js
import { query, withTransaction } from '../db.js';import { visibleBuildingCondition } from './scope.js'; // The workflow. Each action moves an inspection from exactly one status to another.export const INSPECTION_TRANSITIONS = {  submit: { from: 'draft', to: 'submitted' },  approve: { from: 'submitted', to: 'approved' },  return: { from: 'submitted', to: 'draft' },}; const INSPECTION_COLUMNS = `  a.id, a.building_id, s.name AS building_name, s.organisation_id, a.title, a.findings, a.status, a.created_by,  (SELECT u.name FROM users u WHERE u.id = a.created_by) AS created_by_name,  a.submitted_at, a.approved_at, a.created_at, a.updated_at`; export async function listInspections({ userId, status = null }) {  if (!userId) {    throw new Error('listInspections requires the id of the user the list is for');  }  const params = [userId];  let whereSql = `WHERE ${visibleBuildingCondition('s', '$1')}`;  if (status) {    params.push(status);    whereSql += ' AND a.status = $2';  }  const { rows } = await query(    `SELECT ${INSPECTION_COLUMNS}     FROM inspections a     JOIN buildings s ON s.id = a.building_id     ${whereSql}     ORDER BY a.updated_at DESC, a.id DESC`,    params,  );  return rows;} export async function findInspection(id) {  const { rows } = await query(`SELECT ${INSPECTION_COLUMNS} FROM inspections a JOIN buildings s ON s.id = a.building_id WHERE a.id = $1`, [id]);  return rows[0] ?? null;} export async function listInspectionHistory(inspectionId) {  const { rows } = await query(    `SELECT h.from_status, h.to_status, h.changed_at, u.name AS changed_by_name     FROM inspection_status_changes h LEFT JOIN users u ON u.id = h.changed_by     WHERE h.inspection_id = $1 ORDER BY h.changed_at, h.id`,    [inspectionId],  );  return rows;} export async function createInspection({ building_id, title, findings }, createdBy) {  const { rows } = await query(    'INSERT INTO inspections (building_id, title, findings, created_by) VALUES ($1, $2, $3, $4) RETURNING id',    [building_id, title, findings, createdBy],  );  return rows[0];} // Only drafts can be edited. Returns false if the inspection is not (or no longer) a draft.export async function updateDraftInspection(id, { title, findings }) {  const { rowCount } = await query(    "UPDATE inspections SET title = $2, findings = $3, updated_at = now() WHERE id = $1 AND status = 'draft'",    [id, title, findings],  );  return rowCount === 1;} // Applies a transition atomically. Returns false if the inspection was not in the expected status.export async function transitionInspection(id, action, changedBy) {  const transition = INSPECTION_TRANSITIONS[action];  if (!transition) {    throw new Error(`Unknown inspection action ${action}`);  }  return withTransaction(async (client) => {    const { rowCount } = await client.query(      `UPDATE inspections       SET status = $3,           updated_at = now(),           submitted_at = CASE WHEN $3 = 'submitted' THEN now() ELSE submitted_at END,           approved_at = CASE WHEN $3 = 'approved' THEN now() ELSE approved_at END       WHERE id = $1 AND status = $2`,      [id, transition.from, transition.to],    );    if (rowCount === 0) {      return false;    }    await client.query(      'INSERT INTO inspection_status_changes (inspection_id, from_status, to_status, changed_by) VALUES ($1, $2, $3, $4)',      [id, transition.from, transition.to, changedBy],    );    return true;  });}

src/models/issues.js changed

src/models/issues.js
import { query } from '../db.js';import { visibleBuildingCondition } from './scope.js'; const ISSUE_COLUMNS = `  e.id, e.building_id, s.name AS building_name, s.organisation_id,  e.title, e.description, e.priority, e.status, e.reported_by,  (SELECT u.name FROM users u WHERE u.id = e.reported_by) AS reported_by_name,  e.occurred_at, e.created_at, e.updated_at`; // Sort keys a client may ask for. Keys come from the URL; the SQL is ours.export const ISSUE_SORTS = {  occurred_at: 'e.occurred_at',  title: 'e.title',  building: 's.name',  priority: "array_position(ARRAY['low', 'medium', 'high', 'critical'], e.priority)",  status: "array_position(ARRAY['open', 'investigating', 'closed'], e.status)",}; export async function listIssues({ userId, page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null }) {  if (!userId) {    throw new Error('listIssues requires the id of the user the list is for');  }  const params = [userId];  const where = [visibleBuildingCondition('s', '$1')];  if (status) {    params.push(status);    where.push(`e.status = $${params.length}`);  }  if (priority) {    params.push(priority);    where.push(`e.priority = $${params.length}`);  }  if (buildingId) {    params.push(buildingId);    where.push(`e.building_id = $${params.length}`);  }  const whereSql = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';  const direction = dir === 'asc' ? 'ASC' : 'DESC';  const orderSql = `${ISSUE_SORTS[sort] ?? ISSUE_SORTS.occurred_at} ${direction}, e.id ${direction}`;   const countResult = await query(    `SELECT count(*)::int AS total FROM issues e JOIN buildings s ON s.id = e.building_id ${whereSql}`,    params,  );  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     ${whereSql}     ORDER BY ${orderSql}     LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,    [...params, perPage, (page - 1) * perPage],  );  return { issues: rows, total: countResult.rows[0].total };} export async function listRecentIssuesForBuilding(buildingId, limit = 10) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     WHERE e.building_id = $1     ORDER BY e.occurred_at DESC, e.id DESC     LIMIT $2`,    [buildingId, limit],  );  return rows;} export async function findIssue(id) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     WHERE e.id = $1`,    [id],  );  return rows[0] ?? null;} export async function createIssue({ building_id, title, description, priority, occurred_at }, reportedBy) {  const { rows } = await query(    `INSERT INTO issues (building_id, title, description, priority, occurred_at, reported_by)     VALUES ($1, $2, $3, $4, $5, $6)     RETURNING id`,    [building_id, title, description, priority, occurred_at, reportedBy],  );  return rows[0];} export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) {  const { rows } = await query(    `UPDATE issues     SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now()     WHERE id = $1     RETURNING id`,    [id, building_id, title, description, priority, status, occurred_at],  );  return rows[0] ?? null;} export async function deleteIssue(id) {  const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]);  return rowCount === 1;}

src/models/organisations.js changed

src/models/organisations.js
import { query } from '../db.js'; export async function listOrganisations(userId) {  if (!userId) {    throw new Error('listOrganisations requires the id of the user the list is for');  }  const { rows } = await query(    `SELECT o.id, o.name, count(s.id)::int AS building_count     FROM organisations o     LEFT JOIN buildings s ON s.organisation_id = o.id     WHERE o.id IN (SELECT organisation_id FROM memberships WHERE user_id = $1)     GROUP BY o.id     ORDER BY o.name`,    [userId],  );  return rows;} export async function findOrganisation(id) {  const { rows } = await query('SELECT id, name, created_at, updated_at FROM organisations WHERE id = $1', [id]);  return rows[0] ?? null;} export async function createOrganisation({ name }) {  const { rows } = await query('INSERT INTO organisations (name) VALUES ($1) RETURNING id', [name]);  return rows[0];} export async function deleteOrganisation(id) {  const { rowCount } = await query('DELETE FROM organisations WHERE id = $1', [id]);  return rowCount === 1;} export async function updateOrganisation(id, { name }) {  const { rows } = await query(    'UPDATE organisations SET name = $2, updated_at = now() WHERE id = $1 RETURNING id',    [id, name],  );  return rows[0] ?? null;}

src/models/scope.js added

src/models/scope.js
// SQL condition that is true when the building aliased `buildingAlias` is visible to the user// whose id is the SQL parameter `userParam` (for example '$3').//// It MUST agree with rolesAtBuilding() in src/authz/rules.js: a building is visible if the user// holds any active role there, or is org_admin of the organisation that owns it.export function visibleBuildingCondition(buildingAlias, userParam) {  return `(    ${buildingAlias}.id IN (      SELECT building_id FROM building_role_assignments WHERE user_id = ${userParam} AND revoked_at IS NULL    )    OR ${buildingAlias}.organisation_id IN (      SELECT organisation_id FROM memberships WHERE user_id = ${userParam} AND role = 'org_admin'    )  )`;}

src/routes/inspections.js changed

src/routes/inspections.js
import express from 'express';import { listInspections, findInspection, listInspectionHistory, createInspection, updateDraftInspection, transitionInspection, INSPECTION_TRANSITIONS } from '../models/inspections.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const inspectionsRouter = express.Router(); const INSPECTION_STATUSES = ['draft', 'submitted', 'approved']; function validateInspection(input, { requireBuilding }) {  const errors = {};  const title = cleanText(input.title, { min: 3, max: 200 });  const findings = cleanText(input.findings, { max: 5000 });  const buildingId = parseId(input.building_id);  if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.';  if (!findings.ok) errors.findings = 'Findings must be at most 5000 characters.';  if (requireBuilding && buildingId === null) errors.building_id = 'Choose a building.';  return { errors, values: { title: title.text, findings: findings.text, building_id: buildingId } };} async function renderInspectionForm(res, status, { inspection = null, values = {}, errors = {} } = {}) {  res.status(status).render('inspections/form', {    title: inspection ? `Edit inspection #${inspection.id}` : 'New inspection',    action: inspection ? `/inspections/${inspection.id}/edit` : '/inspections',    inspection,    values,    errors,    buildings: inspection ? [] : await listBuildings(),  });} async function renderInspectionPage(res, status, inspection, error = null) {  const history = await listInspectionHistory(inspection.id);  res.status(status).render('inspections/show', { title: inspection.title, inspection, history, error });} async function loadInspection(req, res) {  const id = parseId(req.params.id);  const inspection = id === null ? null : await findInspection(id);  if (!inspection) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });    return null;  }  return inspection;} inspectionsRouter.get('/', async (req, res) => {  const status = INSPECTION_STATUSES.includes(req.query.status) ? req.query.status : null;  res.render('inspections/index', { title: 'Inspections', inspections: await listInspections({ status, userId: req.user.id }), status, statuses: INSPECTION_STATUSES });}); inspectionsRouter.get('/new', async (req, res) => {  await renderInspectionForm(res, 200);}); inspectionsRouter.post('/', async (req, res) => {  const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: true });  if (Object.keys(errors).length > 0) {    return renderInspectionForm(res, 400, { values, errors });  }  try {    const created = await createInspection(values, req.user.id);    res.redirect(303, `/inspections/${created.id}`);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderInspectionForm(res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }}); inspectionsRouter.get('/:id', async (req, res) => {  const inspection = await loadInspection(req, res);  if (!inspection) return;  await renderInspectionPage(res, 200, inspection);}); inspectionsRouter.get('/:id/edit', async (req, res) => {  const inspection = await loadInspection(req, res);  if (!inspection) return;  if (inspection.status !== 'draft') {    return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');  }  await renderInspectionForm(res, 200, { inspection, values: inspection });}); inspectionsRouter.post('/:id/edit', async (req, res) => {  const inspection = await loadInspection(req, res);  if (!inspection) return;  const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false });  if (Object.keys(errors).length > 0) {    return renderInspectionForm(res, 400, { inspection, values, errors });  }  const updated = await updateDraftInspection(inspection.id, values);  if (!updated) {    return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');  }  res.redirect(303, `/inspections/${inspection.id}`);}); // POST /inspections/:id/submit, /approve and /return share one handler.inspectionsRouter.post('/:id/:action', async (req, res, next) => {  if (!Object.hasOwn(INSPECTION_TRANSITIONS, req.params.action)) {    return next();  }  const inspection = await loadInspection(req, res);  if (!inspection) return;  const changed = await transitionInspection(inspection.id, req.params.action, req.user.id);  if (!changed) {    const fresh = await findInspection(inspection.id);    return renderInspectionPage(res, 409, fresh, `This inspection is ${fresh.status}; it cannot be ${req.params.action === 'return' ? 'returned' : `${req.params.action}d`} now.`);  }  res.redirect(303, `/inspections/${inspection.id}`);});

src/routes/issues.js changed

src/routes/issues.js
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.js';import { listBuildings, findBuilding, listVisibleBuildings } from '../models/buildings.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const issuesRouter = express.Router(); export const PRIORITIES = ['low', 'medium', 'high', 'critical'];export const STATUSES = ['open', 'investigating', 'closed'];const FIVE_MINUTES = 5 * 60 * 1000; // <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.function parseDateTimeLocal(value) {  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) {    return null;  }  const date = new Date(`${value}:00Z`);  return Number.isNaN(date.getTime()) ? null : date;} // The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.function toDateTimeLocal(date) {  return new Date(date).toISOString().slice(0, 16);} function validateIssue(input, { editing }) {  const errors = {};  const title = cleanText(input.title, { min: 3, max: 200 });  const description = cleanText(input.description, { max: 2000 });  const buildingId = parseId(input.building_id);  const occurredAt = parseDateTimeLocal(input.occurred_at);  const status = editing ? input.status : 'open';  if (!title.ok) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!description.ok) {    errors.description = 'Description must be at most 2000 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (!editing && buildingId === null) {    errors.building_id = 'Choose a building.';  }  if (!occurredAt) {    errors.occurred_at = 'Enter the date and time it happened (UTC).';  } else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) {    errors.occurred_at = 'That time is in the future.';  }  if (!STATUSES.includes(status)) {    errors.status = `Status must be one of: ${STATUSES.join(', ')}.`;  }  // values: what the form shows again. record: what we store.  const values = {    title: title.text,    description: description.text,    priority: input.priority,    building_id: buildingId,    status,    occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '',  };  const record = { ...values, occurred_at: occurredAt };  return { errors, values, record };} async function renderIssueForm(req, res, status, { issue = null, values = {}, errors = {} } = {}) {  const buildings = (await listBuildings()).filter((building) => can(req.user, 'CreateIssue', building));  res.status(status).render('issues/form', {    title: issue ? `Edit issue #${issue.id}` : 'Report an issue',    action: issue ? `/issues/${issue.id}/edit` : '/issues',    issue,    values,    errors,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,  });} const PER_PAGE = 10; // Converts the query string into list options. Invalid values become defaults.function parseListQuery(query) {  const page = parseId(query.page) ?? 1;  return {    page,    sort: Object.hasOwn(ISSUE_SORTS, query.sort) ? query.sort : 'occurred_at',    dir: query.dir === 'asc' ? 'asc' : 'desc',    status: STATUSES.includes(query.status) ? query.status : null,    priority: PRIORITIES.includes(query.priority) ? query.priority : null,    building: parseId(query.building),  };} // Builds a /issues URL from the current options plus overrides, dropping defaults.function listUrl(options, overrides = {}) {  const merged = { ...options, ...overrides };  const params = new URLSearchParams();  for (const [key, value] of Object.entries(merged)) {    const isDefault = value === null || (key === 'page' && value === 1) || (key === 'sort' && value === 'occurred_at') || (key === 'dir' && value === 'desc');    if (!isDefault) params.set(key, String(value));  }  const qs = params.toString();  return qs ? `/issues?${qs}` : '/issues';} async function loadIssue(req, res) {  const id = parseId(req.params.id);  const issue = id === null ? null : await findIssue(id);  if (!issue || !can(req.user, 'ViewIssue', issue)) {    notFound(req, res);    return null;  }  return issue;} issuesRouter.get('/', async (req, res) => {  const options = parseListQuery(req.query);  const { issues, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id });  const buildings = await listVisibleBuildings(req.user.id);  res.render('issues/index', {    title: 'Maintenance issues',    issues,    total,    options,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,    totalPages: Math.max(1, Math.ceil(total / PER_PAGE)),    listUrl: (overrides) => listUrl(options, overrides),  });}); issuesRouter.get('/new', async (req, res) => {  await renderIssueForm(req, res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } });}); issuesRouter.post('/', async (req, res) => {  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false });  if (Object.keys(errors).length > 0) {    return renderIssueForm(req, res, 400, { values, errors });  }  // The building id came from the form. Load the real building and check the user may report there.  const building = await findBuilding(record.building_id);  if (!building || !can(req.user, 'CreateIssue', building)) {    return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can report issues.' } });  }  let created;  try {    created = await createIssue(record, req.user.id);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${created.id}`);}); issuesRouter.get('/:id', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  res.render('issues/show', { title: issue.title, issue });}); issuesRouter.get('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);  await renderIssueForm(req, res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });}); issuesRouter.post('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });  if (Object.keys(errors).length > 0) {    return renderIssueForm(req, res, 400, { issue, values, errors });  }  // The edit form cannot move an issue: the building stays the one we loaded.  await updateIssue(issue.id, { ...record, building_id: issue.building_id });  res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'DeleteIssue', issue)) return forbidden(res);  await deleteIssue(issue.id);  res.redirect(303, '/issues');});

src/routes/organisations.js changed

src/routes/organisations.js
import express from 'express';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js'; export const organisationsRouter = express.Router(); const validateOrganisation = validateName; function renderForm(res, status, { organisation = null, values = {}, errors = {} }) {  res.status(status).render('organisations/form', {    title: organisation ? `Edit ${organisation.name}` : 'New organisation',    action: organisation ? `/organisations/${organisation.id}/edit` : '/organisations',    organisation,    values,    errors,  });} // Loads the organisation named by :id, or answers 404. Returns null when it answered.async function loadOrganisation(req, res) {  const id = parseId(req.params.id);  const organisation = id === null ? null : await findOrganisation(id);  if (!organisation) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });    return null;  }  return organisation;} organisationsRouter.get('/', async (req, res) => {  res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations(req.user.id) });}); organisationsRouter.get('/new', (req, res) => {  renderForm(res, 200, {});}); organisationsRouter.post('/', async (req, res) => {  const { errors, values } = validateOrganisation(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderForm(res, 400, { values, errors });  }  const created = await createOrganisation(values);  res.redirect(303, `/organisations/${created.id}`);}); organisationsRouter.get('/:id', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  const buildings = await listBuildingsForOrganisation(organisation.id);  res.render('organisations/show', { title: organisation.name, organisation, buildings });}); organisationsRouter.get('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  renderForm(res, 200, { organisation, values: organisation });}); organisationsRouter.post('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  const { errors, values } = validateOrganisation(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderForm(res, 400, { organisation, values, errors });  }  await updateOrganisation(organisation.id, values);  res.redirect(303, `/organisations/${organisation.id}`);}); organisationsRouter.post('/:id/delete', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  try {    await deleteOrganisation(organisation.id);  } catch (err) {    if (err.code === PG_ERRORS.RESTRICT_VIOLATION) {      const buildings = await listBuildingsForOrganisation(organisation.id);      return res.status(409).render('organisations/show', {        title: organisation.name,        organisation,        buildings,        error: 'This organisation still has buildings. Delete its buildings first.',      });    }    throw err;  }  res.redirect(303, '/organisations');}); function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) {  res.status(status).render('buildings/form', {    title: `New building in ${organisation.name}`,    action: `/organisations/${organisation.id}/buildings`,    cancelUrl: `/organisations/${organisation.id}`,    building: null,    values,    errors,  });} organisationsRouter.get('/:id/buildings/new', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  renderBuildingForm(res, 200, { organisation });}); organisationsRouter.post('/:id/buildings', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  const { errors, values } = validateName(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderBuildingForm(res, 400, { organisation, values, errors });  }  try {    const building = await createBuilding({ organisation_id: organisation.id, name: values.name });    res.redirect(303, `/buildings/${building.id}`);  } catch (err) {    if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {      return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } });    }    throw err;  }});

test/dashboard.test.js changed

test/dashboard.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => {  await resetDatabase();  agent = await loginAs('carol');});after(() => pool.end()); test('the dashboard counts match the database', async () => {  const res = await agent.get('/');  assert.equal(res.status, 200);  const { rows } = await pool.query("SELECT count(*)::int AS n FROM issues WHERE status <> 'closed' AND building_id IN (10, 20)");  assert.match(res.text, new RegExp(`<h3>Open issues</h3><div class="stat">${rows[0].n}</div>`));  assert.match(res.text, /<h3>Inspections awaiting approval<\/h3><div class="stat">2<\/div>/);}); test('only the buildings carol can see appear', async () => {  const res = await agent.get('/');  for (const name of ['Dublin Offices', 'Cork Apartments']) {    assert.match(res.text, new RegExp(name));  }  for (const name of ['Galway Studios', 'Limerick House']) {    assert.doesNotMatch(res.text, new RegExp(name));  }});

test/isolation.test.js added

test/isolation.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; const agents = {};before(async () => {  await resetDatabase();  for (const name of ['alice', 'bob', 'carol', 'dave', 'nora', 'ravi']) agents[name] = await loginAs(name);});after(() => pool.end()); function linkedIds(html, kind) {  return [...html.matchAll(new RegExp(`<td><a href="/${kind}/(\\d+)">`, 'g'))].map((m) => Number(m[1]));} async function allIssueIds(agent) {  const ids = [];  for (let page = 1; page <= 4; page++) ids.push(...linkedIds((await agent.get(`/issues?page=${page}`)).text, 'issues'));  return ids;} async function buildingsOf(issueIds) {  if (issueIds.length === 0) return [];  const { rows } = await pool.query('SELECT DISTINCT building_id FROM issues WHERE id = ANY($1) ORDER BY building_id', [issueIds]);  return rows.map((r) => r.building_id);} test('the issues list contains only issues from visible buildings', async () => {  const expected = { alice: [10, 20], bob: [30], carol: [10, 20], dave: [10, 20], nora: [], ravi: [] };  for (const [name, buildings] of Object.entries(expected)) {    assert.deepEqual(await buildingsOf(await allIssueIds(agents[name])), buildings, name);  }}); test('a filter for another tenant\'s building returns nothing', async () => {  const res = await agents.alice.get('/issues?building=30');  assert.deepEqual(linkedIds(res.text, 'issues'), []);  assert.match(res.text, /0 issues/);}); test('the inspections list is scoped too', async () => {  assert.deepEqual(linkedIds((await agents.alice.get('/inspections')).text, 'inspections').sort(), [201, 202, 203]);  assert.deepEqual(linkedIds((await agents.bob.get('/inspections')).text, 'inspections'), [204]);  assert.deepEqual(linkedIds((await agents.nora.get('/inspections')).text, 'inspections'), []);}); test('organisations are listed for their members only', async () => {  assert.match((await agents.ravi.get('/organisations')).text, /Harbour Lets/, 'ravi is still a member');  assert.doesNotMatch((await agents.ravi.get('/organisations')).text, /Liffey/);  assert.doesNotMatch((await agents.nora.get('/organisations')).text, /<td><a href/);}); test('the dashboard counts only visible data', async () => {  const bob = (await agents.bob.get('/')).text;  assert.match(bob, /<h3>Open issues<\/h3><div class="stat">1<\/div>/);  assert.doesNotMatch(bob, /Dublin Offices/);  const nora = (await agents.nora.get('/')).text;  assert.match(nora, /<h3>Open issues<\/h3><div class="stat">0<\/div>/);});

test/issue-list.test.js changed

test/issue-list.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => {  await resetDatabase();  agent = await loginAs('carol');});after(() => pool.end()); // The issue ids linked from the table rows, in order.function issueIds(html) {  return [...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1]));} test('the list pages 10 at a time and reports the total', async () => {  const first = await agent.get('/issues');  assert.equal(issueIds(first.text).length, 10);  assert.match(first.text, /28 issues/, 'carol sees the 28 issues at buildings 10 and 20');  const third = await agent.get('/issues?page=3');  assert.equal(issueIds(third.text).length, 8);  const fourth = await agent.get('/issues?page=4');  assert.equal(issueIds(fourth.text).length, 0);}); test('pages do not overlap', async () => {  const ids = [];  for (const page of [1, 2, 3]) ids.push(...issueIds((await agent.get(`/issues?page=${page}`)).text));  assert.equal(new Set(ids).size, 28);}); test('filters combine with AND', async () => {  const res = await agent.get('/issues?status=open&building=20');  const ids = issueIds(res.text);  assert.ok(ids.length > 0);  const { rows } = await pool.query('SELECT id FROM issues WHERE status = $1 AND building_id = $2', ['open', 20]);  assert.deepEqual(new Set(ids), new Set(rows.map((r) => r.id)));}); test('sorting by priority puts critical first when descending', async () => {  const res = await agent.get('/issues?sort=priority&dir=desc');  assert.match(res.text, /<span class="badge sev-critical">/);  const firstBadge = res.text.match(/class="badge sev-(\w+)"/)[1];  assert.equal(firstBadge, 'critical');}); test('unknown sort keys and SQL in the query string are ignored', async () => {  for (const qs of ['sort=(SELECT%201/0)', 'sort=toString', 'dir=sideways', 'page=-1', 'status=%27%3B--', 'building=abc']) {    const res = await agent.get(`/issues?${qs}`);    assert.equal(res.status, 200, qs);    assert.equal(issueIds(res.text).length, 10, qs);  }});

test/organisations.test.js changed

test/organisations.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => {  await resetDatabase();  agent = await loginAs('carol');});after(() => pool.end()); test('GET /organisations lists organisations with building counts', async () => {  const res = await agent.get('/organisations');  assert.equal(res.status, 200);  assert.match(res.text, /Liffey Estates<\/a><\/td>\s*<td>2<\/td>/);  assert.doesNotMatch(res.text, /Harbour Lets/, 'carol is not a member of Harbour Lets');}); test('GET /organisations/1 shows its buildings, not other organisations\' buildings', async () => {  const res = await agent.get('/organisations/1');  assert.equal(res.status, 200);  assert.match(res.text, /Dublin Offices/);  assert.match(res.text, /Cork Apartments/);  assert.doesNotMatch(res.text, /Galway Studios/);}); test('POST /organisations validates and creates', async () => {  const bad = await agent.post('/organisations').type('form').send({ name: ' ' });  assert.equal(bad.status, 400);  assert.match(bad.text, /Name must be between 2 and 100 characters/);   const good = await agent.post('/organisations').type('form').send({ name: 'Riverside Lettings' });  assert.equal(good.status, 303);  const page = await agent.get(good.headers.location);  assert.match(page.text, /<h1>Riverside Lettings<\/h1>/);}); test('POST /organisations/:id/edit renames the organisation', async () => {  const res = await agent.post('/organisations/2/edit').type('form').send({ name: 'Harbour Lets Ltd' });  assert.equal(res.status, 303);  const page = await agent.get('/organisations/2');  assert.match(page.text, /<h1>Harbour Lets Ltd<\/h1>/);}); test('unknown organisations are 404', async () => {  assert.equal((await agent.get('/organisations/999')).status, 404);  assert.equal((await agent.post('/organisations/999/edit').type('form').send({ name: 'Nope' })).status, 404);});

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/authz/rules.js
src/config.js
src/db.js
src/lib/http.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/scope.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/isolation.test.js
test/issue-authz.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/forbidden.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

Back to lesson 5.3