Checkpoint · Lesson 5.4
Buildings, organisations and inspections: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m05-l04 -- src.
Files changed in this lesson
src/authz/rules.js changed
src/authz/rules.js// Authorization rules in plain JavaScript (Module 5).
// Every route asks can(user, action, resource). Module 6 keeps this question
// and moves the answer into Cedar policies.
const ANY_BUILDING_ROLE = ['viewer', 'reporter', 'inspector', 'building_admin'];
// The roles a user effectively holds at one building: the roles assigned there,
// plus building_admin if they are org_admin of the organisation that owns the building.
export function rolesAtBuilding(user, buildingId, organisationId) {
const roles = new Set();
for (const assignment of user.access.assignments) {
if (assignment.building_id === buildingId) {
roles.add(assignment.role);
}
}
if (isOrgAdmin(user, organisationId)) {
roles.add('building_admin');
}
return roles;
}
function isMember(user, organisationId) {
return user.access.memberships.some((m) => m.organisation_id === organisationId);
}
function isOrgAdmin(user, organisationId) {
return user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');
}
function hasAny(roles, wanted) {
return wanted.some((role) => roles.has(role));
}
export function can(user, action, resource) {
switch (action) {
// Organisations. resource: an organisation row { id, ... }
case 'ViewOrganisation':
return isMember(user, resource.id);
case 'UpdateOrganisation':
case 'DeleteOrganisation':
case 'CreateBuilding':
return isOrgAdmin(user, resource.id);
// Buildings. resource: a building row { id, organisation_id, ... }
case 'ViewBuilding':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ANY_BUILDING_ROLE);
case 'UpdateBuilding':
return rolesAtBuilding(user, resource.id, resource.organisation_id).has('building_admin');
case 'DeleteBuilding':
return isOrgAdmin(user, resource.organisation_id);
case 'CreateIssue':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', 'building_admin']);
case 'CreateInspection':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['inspector', 'building_admin']);
// Issues. resource: an issue row { building_id, organisation_id, reported_by, status, ... }
case 'ViewIssue':
return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE);
case 'UpdateIssue': {
const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id);
if (roles.has('building_admin')) {
return true;
}
return roles.has('reporter') && resource.reported_by === user.id && resource.status !== 'closed';
}
case 'DeleteIssue':
return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
// Inspections. resource: an inspection row { building_id, organisation_id, created_by, status, ... }
case 'ViewInspection':
return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE);
case 'UpdateInspection':
case 'SubmitInspection': {
const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id);
if (roles.has('building_admin')) {
return true;
}
return roles.has('inspector') && resource.created_by === user.id;
}
case 'ApproveInspection':
case 'ReturnInspection':
return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
default:
// An action without a rule is a bug. Fail loudly rather than allow.
throw new Error(`No authorization rule for action ${action}`);
}
}
// Authorization rules in plain JavaScript (Module 5).// Every route asks can(user, action, resource). Module 6 keeps this question// and moves the answer into Cedar policies. const ANY_BUILDING_ROLE = ['viewer', 'reporter', 'inspector', 'building_admin']; // The roles a user effectively holds at one building: the roles assigned there,// plus building_admin if they are org_admin of the organisation that owns the building.export function rolesAtBuilding(user, buildingId, organisationId) { const roles = new Set(); for (const assignment of user.access.assignments) { if (assignment.building_id === buildingId) { roles.add(assignment.role); } } if (isOrgAdmin(user, organisationId)) { roles.add('building_admin'); } return roles;} function isMember(user, organisationId) { return user.access.memberships.some((m) => m.organisation_id === organisationId);} function isOrgAdmin(user, organisationId) { return user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');} function hasAny(roles, wanted) { return wanted.some((role) => roles.has(role));} export function can(user, action, resource) { switch (action) { // Organisations. resource: an organisation row { id, ... } case 'ViewOrganisation': return isMember(user, resource.id); case 'UpdateOrganisation': case 'DeleteOrganisation': case 'CreateBuilding': return isOrgAdmin(user, resource.id); // Buildings. resource: a building row { id, organisation_id, ... } case 'ViewBuilding': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ANY_BUILDING_ROLE); case 'UpdateBuilding': return rolesAtBuilding(user, resource.id, resource.organisation_id).has('building_admin'); case 'DeleteBuilding': return isOrgAdmin(user, resource.organisation_id); case 'CreateIssue': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', 'building_admin']); case 'CreateInspection': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['inspector', 'building_admin']); // Issues. resource: an issue row { building_id, organisation_id, reported_by, status, ... } case 'ViewIssue': return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE); case 'UpdateIssue': { const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id); if (roles.has('building_admin')) { return true; } return roles.has('reporter') && resource.reported_by === user.id && resource.status !== 'closed'; } case 'DeleteIssue': return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin'); // Inspections. resource: an inspection row { building_id, organisation_id, created_by, status, ... } case 'ViewInspection': return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE); case 'UpdateInspection': case 'SubmitInspection': { const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id); if (roles.has('building_admin')) { return true; } return roles.has('inspector') && resource.created_by === user.id; } case 'ApproveInspection': case 'ReturnInspection': return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin'); default: // An action without a rule is a bug. Fail loudly rather than allow. throw new Error(`No authorization rule for action ${action}`); }}src/models/organisations.js changed
src/models/organisations.jsimport { query, withTransaction } 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;
}
// Creates the organisation and makes its creator org_admin, in one transaction.
export async function createOrganisation({ name }, creatorId) {
return withTransaction(async (client) => {
const { rows } = await client.query('INSERT INTO organisations (name) VALUES ($1) RETURNING id', [name]);
await client.query("INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, 'org_admin')", [creatorId, rows[0].id]);
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;
}
import { query, withTransaction } 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;} // Creates the organisation and makes its creator org_admin, in one transaction.export async function createOrganisation({ name }, creatorId) { return withTransaction(async (client) => { const { rows } = await client.query('INSERT INTO organisations (name) VALUES ($1) RETURNING id', [name]); await client.query("INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, 'org_admin')", [creatorId, rows[0].id]); 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/routes/buildings.js changed
src/routes/buildings.jsimport express from 'express';
import { findBuilding, updateBuilding, deleteBuilding } from '../models/buildings.js';
import { listRecentIssuesForBuilding } from '../models/issues.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { validateName } from '../lib/validation.js';
import { can } from '../authz/rules.js';
import { notFound, forbidden } from '../lib/http.js';
export const buildingsRouter = express.Router();
async function loadBuilding(req, res) {
const id = parseId(req.params.id);
const building = id === null ? null : await findBuilding(id);
if (!building || !can(req.user, 'ViewBuilding', building)) {
notFound(req, res);
return null;
}
return building;
}
async function renderBuildingPage(res, status, building, error = null) {
const issues = await listRecentIssuesForBuilding(building.id);
res.status(status).render('buildings/show', { title: building.name, building, issues, error });
}
function renderEditForm(res, status, { building, values, errors = {} }) {
res.status(status).render('buildings/form', {
title: `Edit ${building.name}`,
action: `/buildings/${building.id}/edit`,
cancelUrl: `/buildings/${building.id}`,
building,
values,
errors,
});
}
buildingsRouter.get('/:id', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
await renderBuildingPage(res, 200, building);
});
buildingsRouter.get('/:id/edit', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res);
renderEditForm(res, 200, { building, values: building });
});
buildingsRouter.post('/:id/edit', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res);
const { errors, values } = validateName(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderEditForm(res, 400, { building, values, errors });
}
try {
await updateBuilding(building.id, values);
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return renderEditForm(res, 400, { building, values, errors: { name: 'This organisation already has a building with that name.' } });
}
throw err;
}
res.redirect(303, `/buildings/${building.id}`);
});
buildingsRouter.post('/:id/delete', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'DeleteBuilding', building)) return forbidden(res);
try {
await deleteBuilding(building.id);
} catch (err) {
if (err.code === PG_ERRORS.RESTRICT_VIOLATION) {
return renderBuildingPage(res, 409, building, 'This building still has maintenance issues, so it cannot be deleted.');
}
throw err;
}
res.redirect(303, `/organisations/${building.organisation_id}`);
});
import express from 'express';import { findBuilding, updateBuilding, deleteBuilding } from '../models/buildings.js';import { listRecentIssuesForBuilding } from '../models/issues.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js'; export const buildingsRouter = express.Router(); async function loadBuilding(req, res) { const id = parseId(req.params.id); const building = id === null ? null : await findBuilding(id); if (!building || !can(req.user, 'ViewBuilding', building)) { notFound(req, res); return null; } return building;} async function renderBuildingPage(res, status, building, error = null) { const issues = await listRecentIssuesForBuilding(building.id); res.status(status).render('buildings/show', { title: building.name, building, issues, error });} function renderEditForm(res, status, { building, values, errors = {} }) { res.status(status).render('buildings/form', { title: `Edit ${building.name}`, action: `/buildings/${building.id}/edit`, cancelUrl: `/buildings/${building.id}`, building, values, errors, });} buildingsRouter.get('/:id', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; await renderBuildingPage(res, 200, building);}); buildingsRouter.get('/:id/edit', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res); renderEditForm(res, 200, { building, values: building });}); buildingsRouter.post('/:id/edit', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res); const { errors, values } = validateName(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderEditForm(res, 400, { building, values, errors }); } try { await updateBuilding(building.id, values); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderEditForm(res, 400, { building, values, errors: { name: 'This organisation already has a building with that name.' } }); } throw err; } res.redirect(303, `/buildings/${building.id}`);}); buildingsRouter.post('/:id/delete', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'DeleteBuilding', building)) return forbidden(res); try { await deleteBuilding(building.id); } catch (err) { if (err.code === PG_ERRORS.RESTRICT_VIOLATION) { return renderBuildingPage(res, 409, building, 'This building still has maintenance issues, so it cannot be deleted.'); } throw err; } res.redirect(303, `/organisations/${building.organisation_id}`);});src/routes/inspections.js changed
src/routes/inspections.jsimport express from 'express';
import { listInspections, findInspection, listInspectionHistory, createInspection, updateDraftInspection, transitionInspection, INSPECTION_TRANSITIONS } from '../models/inspections.js';
import { listBuildings, findBuilding } 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 inspectionsRouter = express.Router();
const INSPECTION_STATUSES = ['draft', 'submitted', 'approved'];
const TRANSITION_ACTIONS = { submit: 'SubmitInspection', approve: 'ApproveInspection', return: 'ReturnInspection' };
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(req, 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()).filter((building) => can(req.user, 'CreateInspection', building)),
});
}
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 || !can(req.user, 'ViewInspection', inspection)) {
notFound(req, res);
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(req, res, 200);
});
inspectionsRouter.post('/', async (req, res) => {
const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: true });
if (Object.keys(errors).length > 0) {
return renderInspectionForm(req, res, 400, { values, errors });
}
const building = await findBuilding(values.building_id);
if (!building || !can(req.user, 'CreateInspection', building)) {
return renderInspectionForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can create inspections.' } });
}
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(req, 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 (!can(req.user, 'UpdateInspection', inspection)) return forbidden(res);
if (inspection.status !== 'draft') {
return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');
}
await renderInspectionForm(req, res, 200, { inspection, values: inspection });
});
inspectionsRouter.post('/:id/edit', async (req, res) => {
const inspection = await loadInspection(req, res);
if (!inspection) return;
if (!can(req.user, 'UpdateInspection', inspection)) return forbidden(res);
const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false });
if (Object.keys(errors).length > 0) {
return renderInspectionForm(req, 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;
if (!can(req.user, TRANSITION_ACTIONS[req.params.action], inspection)) return forbidden(res);
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}`);
});
import express from 'express';import { listInspections, findInspection, listInspectionHistory, createInspection, updateDraftInspection, transitionInspection, INSPECTION_TRANSITIONS } from '../models/inspections.js';import { listBuildings, findBuilding } 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 inspectionsRouter = express.Router(); const INSPECTION_STATUSES = ['draft', 'submitted', 'approved'];const TRANSITION_ACTIONS = { submit: 'SubmitInspection', approve: 'ApproveInspection', return: 'ReturnInspection' }; 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(req, 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()).filter((building) => can(req.user, 'CreateInspection', building)), });} 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 || !can(req.user, 'ViewInspection', inspection)) { notFound(req, res); 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(req, res, 200);}); inspectionsRouter.post('/', async (req, res) => { const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: true }); if (Object.keys(errors).length > 0) { return renderInspectionForm(req, res, 400, { values, errors }); } const building = await findBuilding(values.building_id); if (!building || !can(req.user, 'CreateInspection', building)) { return renderInspectionForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can create inspections.' } }); } 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(req, 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 (!can(req.user, 'UpdateInspection', inspection)) return forbidden(res); if (inspection.status !== 'draft') { return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.'); } await renderInspectionForm(req, res, 200, { inspection, values: inspection });}); inspectionsRouter.post('/:id/edit', async (req, res) => { const inspection = await loadInspection(req, res); if (!inspection) return; if (!can(req.user, 'UpdateInspection', inspection)) return forbidden(res); const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false }); if (Object.keys(errors).length > 0) { return renderInspectionForm(req, 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; if (!can(req.user, TRANSITION_ACTIONS[req.params.action], inspection)) return forbidden(res); 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/organisations.js changed
src/routes/organisations.jsimport 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';
import { can } from '../authz/rules.js';
import { notFound, forbidden } from '../lib/http.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 || !can(req.user, 'ViewOrganisation', organisation)) {
notFound(req, res);
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, req.user.id);
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;
if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);
renderForm(res, 200, { organisation, values: organisation });
});
organisationsRouter.post('/:id/edit', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);
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;
if (!can(req.user, 'DeleteOrganisation', organisation)) return forbidden(res);
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;
if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);
renderBuildingForm(res, 200, { organisation });
});
organisationsRouter.post('/:id/buildings', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);
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;
}
});
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';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.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 || !can(req.user, 'ViewOrganisation', organisation)) { notFound(req, res); 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, req.user.id); 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; if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res); renderForm(res, 200, { organisation, values: organisation });}); organisationsRouter.post('/:id/edit', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res); 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; if (!can(req.user, 'DeleteOrganisation', organisation)) return forbidden(res); 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; if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res); renderBuildingForm(res, 200, { organisation });}); organisationsRouter.post('/:id/buildings', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res); 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/buildings.test.js changed
test/buildings.test.jsimport { 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('a building can be created inside an organisation', async () => {
const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Galway Townhouse' });
assert.equal(res.status, 303);
const page = await agent.get(res.headers.location);
assert.match(page.text, /<h1>Galway Townhouse<\/h1>/);
assert.match(page.text, /Liffey Estates/);
});
test('a duplicate building name in the same organisation is a field error', async () => {
const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Cork Apartments' });
assert.equal(res.status, 400);
assert.match(res.text, /already has a building with that name/);
});
test('the same building name is allowed in another organisation', async () => {
const created = await agent.post('/organisations').type('form').send({ name: 'Carol Consulting' });
const res = await agent.post(`${created.headers.location}/buildings`).type('form').send({ name: 'Cork Apartments' });
assert.equal(res.status, 303);
});
test('a building with issues cannot be deleted', async () => {
const res = await agent.post('/buildings/10/delete');
assert.equal(res.status, 409);
assert.match(res.text, /still has maintenance issues/);
assert.equal((await agent.get('/buildings/10')).status, 200);
});
test('an empty building can be deleted', async () => {
const created = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Temporary Annex' });
const res = await agent.post(`${created.headers.location}/delete`);
assert.equal(res.status, 303);
assert.equal(res.headers.location, '/organisations/1');
assert.equal((await agent.get(created.headers.location)).status, 404);
});
test('an organisation with buildings cannot be deleted, an empty one can', async () => {
const blocked = await agent.post('/organisations/1/delete');
assert.equal(blocked.status, 409);
assert.match(blocked.text, /still has buildings/);
const created = await agent.post('/organisations').type('form').send({ name: 'Short-lived Ltd' });
const res = await agent.post(`${created.headers.location}/delete`);
assert.equal(res.status, 303);
assert.equal((await agent.get(created.headers.location)).status, 404);
});
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('a building can be created inside an organisation', async () => { const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Galway Townhouse' }); assert.equal(res.status, 303); const page = await agent.get(res.headers.location); assert.match(page.text, /<h1>Galway Townhouse<\/h1>/); assert.match(page.text, /Liffey Estates/);}); test('a duplicate building name in the same organisation is a field error', async () => { const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Cork Apartments' }); assert.equal(res.status, 400); assert.match(res.text, /already has a building with that name/);}); test('the same building name is allowed in another organisation', async () => { const created = await agent.post('/organisations').type('form').send({ name: 'Carol Consulting' }); const res = await agent.post(`${created.headers.location}/buildings`).type('form').send({ name: 'Cork Apartments' }); assert.equal(res.status, 303);}); test('a building with issues cannot be deleted', async () => { const res = await agent.post('/buildings/10/delete'); assert.equal(res.status, 409); assert.match(res.text, /still has maintenance issues/); assert.equal((await agent.get('/buildings/10')).status, 200);}); test('an empty building can be deleted', async () => { const created = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Temporary Annex' }); const res = await agent.post(`${created.headers.location}/delete`); assert.equal(res.status, 303); assert.equal(res.headers.location, '/organisations/1'); assert.equal((await agent.get(created.headers.location)).status, 404);}); test('an organisation with buildings cannot be deleted, an empty one can', async () => { const blocked = await agent.post('/organisations/1/delete'); assert.equal(blocked.status, 409); assert.match(blocked.text, /still has buildings/); const created = await agent.post('/organisations').type('form').send({ name: 'Short-lived Ltd' }); const res = await agent.post(`${created.headers.location}/delete`); assert.equal(res.status, 303); assert.equal((await agent.get(created.headers.location)).status, 404);});test/organisations.test.js changed
test/organisations.test.jsimport { 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/1/edit').type('form').send({ name: 'Liffey Estates Ltd' });
assert.equal(res.status, 303);
const page = await agent.get('/organisations/1');
assert.match(page.text, /<h1>Liffey Estates 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);
});
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/1/edit').type('form').send({ name: 'Liffey Estates Ltd' }); assert.equal(res.status, 303); const page = await agent.get('/organisations/1'); assert.match(page.text, /<h1>Liffey Estates 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);});test/require-login.test.js changed
test/require-login.test.jsimport { 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, anonymousAgent, csrfTokenFrom } from './helpers.js';
before(resetDatabase);
after(() => pool.end());
function sessionId(res) {
const cookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('caretaker.sid='));
return cookie ? cookie.split(';')[0] : null;
}
test('anonymous requests are redirected to the login page', async () => {
for (const path of ['/', '/issues', '/issues/101', '/organisations', '/inspections/201', '/buildings/10']) {
const res = await request(app).get(path);
assert.equal(res.status, 303, path);
assert.equal(res.headers.location, '/login', path);
}
});
test('anonymous writes are refused and change nothing', async () => {
const withoutToken = await request(app).post('/issues/101/delete');
assert.equal(withoutToken.status, 403);
const agent = await anonymousAgent();
const withToken = await agent.post('/issues/101/delete');
assert.equal(withToken.status, 303);
assert.equal(withToken.headers.location, '/login');
const { rowCount } = await pool.query('SELECT 1 FROM issues WHERE id = 101');
assert.equal(rowCount, 1);
});
test('login and register pages stay public', async () => {
assert.equal((await request(app).get('/login')).status, 200);
assert.equal((await request(app).get('/register')).status, 200);
assert.equal((await request(app).get('/css/style.css')).status, 200);
});
test('login issues a new session id (no session fixation)', async () => {
const agent = request.agent(app);
await agent.get('/issues');
const page = await agent.get('/login');
const before = sessionId(page) ?? 'cookie set by the first request';
const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) });
const afterLogin = sessionId(login);
assert.ok(afterLogin);
assert.notEqual(afterLogin, before);
assert.equal(login.headers.location, '/issues', 'returns to the page the user wanted');
});
test('returnTo only follows local paths', async () => {
const agent = request.agent(app);
await agent.get('//evil.test/phish');
const page = await agent.get('/login');
const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) });
assert.equal(login.headers.location, '/');
});
test('new issues and transitions record the logged-in user', async () => {
const dave = await loginAs('dave');
const res = await dave.post('/issues').type('form').send({ title: 'Loose handrail on stairs', building_id: '20', priority: 'medium', occurred_at: '2026-11-21T08:00', reported_by: '1' });
const id = Number(res.headers.location.split('/').pop());
const { rows } = await pool.query('SELECT reported_by FROM issues WHERE id = $1', [id]);
assert.equal(rows[0].reported_by, 4, 'reported_by comes from the session, not the form');
const inspection = await dave.post('/inspections').type('form').send({ building_id: '10', title: 'Lift alarm check', findings: '' });
const inspectionId = Number(inspection.headers.location.split('/').pop());
await dave.post(`/inspections/${inspectionId}/submit`);
const history = await pool.query("SELECT changed_by FROM inspection_status_changes WHERE inspection_id = $1 AND to_status = 'submitted'", [inspectionId]);
assert.equal(history.rows[0].changed_by, 4);
});
test('the session cookie has the attributes we chose', async () => {
const agent = await anonymousAgent();
const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' });
const cookie = res.headers['set-cookie'].find((c) => c.startsWith('caretaker.sid='));
assert.match(cookie, /HttpOnly/);
assert.match(cookie, /SameSite=Lax/);
assert.match(cookie, /Expires=/);
assert.doesNotMatch(cookie, /Secure/, 'not Secure in tests: they use plain HTTP');
});
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, anonymousAgent, csrfTokenFrom } from './helpers.js'; before(resetDatabase);after(() => pool.end()); function sessionId(res) { const cookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('caretaker.sid=')); return cookie ? cookie.split(';')[0] : null;} test('anonymous requests are redirected to the login page', async () => { for (const path of ['/', '/issues', '/issues/101', '/organisations', '/inspections/201', '/buildings/10']) { const res = await request(app).get(path); assert.equal(res.status, 303, path); assert.equal(res.headers.location, '/login', path); }}); test('anonymous writes are refused and change nothing', async () => { const withoutToken = await request(app).post('/issues/101/delete'); assert.equal(withoutToken.status, 403); const agent = await anonymousAgent(); const withToken = await agent.post('/issues/101/delete'); assert.equal(withToken.status, 303); assert.equal(withToken.headers.location, '/login'); const { rowCount } = await pool.query('SELECT 1 FROM issues WHERE id = 101'); assert.equal(rowCount, 1);}); test('login and register pages stay public', async () => { assert.equal((await request(app).get('/login')).status, 200); assert.equal((await request(app).get('/register')).status, 200); assert.equal((await request(app).get('/css/style.css')).status, 200);}); test('login issues a new session id (no session fixation)', async () => { const agent = request.agent(app); await agent.get('/issues'); const page = await agent.get('/login'); const before = sessionId(page) ?? 'cookie set by the first request'; const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) }); const afterLogin = sessionId(login); assert.ok(afterLogin); assert.notEqual(afterLogin, before); assert.equal(login.headers.location, '/issues', 'returns to the page the user wanted');}); test('returnTo only follows local paths', async () => { const agent = request.agent(app); await agent.get('//evil.test/phish'); const page = await agent.get('/login'); const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) }); assert.equal(login.headers.location, '/');}); test('new issues and transitions record the logged-in user', async () => { const dave = await loginAs('dave'); const res = await dave.post('/issues').type('form').send({ title: 'Loose handrail on stairs', building_id: '20', priority: 'medium', occurred_at: '2026-11-21T08:00', reported_by: '1' }); const id = Number(res.headers.location.split('/').pop()); const { rows } = await pool.query('SELECT reported_by FROM issues WHERE id = $1', [id]); assert.equal(rows[0].reported_by, 4, 'reported_by comes from the session, not the form'); const inspection = await dave.post('/inspections').type('form').send({ building_id: '10', title: 'Lift alarm check', findings: '' }); const inspectionId = Number(inspection.headers.location.split('/').pop()); await dave.post(`/inspections/${inspectionId}/submit`); const history = await pool.query("SELECT changed_by FROM inspection_status_changes WHERE inspection_id = $1 AND to_status = 'submitted'", [inspectionId]); assert.equal(history.rows[0].changed_by, 4);}); test('the session cookie has the attributes we chose', async () => { const agent = await anonymousAgent(); const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' }); const cookie = res.headers['set-cookie'].find((c) => c.startsWith('caretaker.sid=')); assert.match(cookie, /HttpOnly/); assert.match(cookie, /SameSite=Lax/); assert.match(cookie, /Expires=/); assert.doesNotMatch(cookie, /Secure/, 'not Secure in tests: they use plain HTTP');});test/resource-authz.test.js added
test/resource-authz.test.jsimport { 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 USERS = ['alice', 'bob', 'carol', 'dave', 'nora', 'ravi'];
const agents = {};
before(async () => {
await resetDatabase();
for (const name of USERS) agents[name] = await loginAs(name);
});
after(() => pool.end());
async function statusesFor(request, users = USERS) {
const result = {};
for (const name of users) result[name] = (await request(agents[name])).status;
return result;
}
test('organisation 1: view and update', async () => {
assert.deepEqual(await statusesFor((a) => a.get('/organisations/1')),
{ alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });
assert.deepEqual(await statusesFor((a) => a.get('/organisations/1/edit')),
{ alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });
});
test('ravi is still a member of organisation 2 but can see none of its buildings', async () => {
assert.equal((await agents.ravi.get('/organisations/2')).status, 200);
assert.equal((await agents.ravi.get('/buildings/30')).status, 404);
});
test('building 10: view, update, delete', async () => {
assert.deepEqual(await statusesFor((a) => a.get('/buildings/10')),
{ alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });
assert.deepEqual(await statusesFor((a) => a.get('/buildings/10/edit')),
{ alice: 200, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });
assert.deepEqual(await statusesFor((a) => a.post('/buildings/10/delete'), ['alice', 'bob', 'dave', 'nora']),
{ alice: 403, bob: 404, dave: 403, nora: 404 }, 'only org_admin may delete a building');
});
test('creating buildings needs org_admin', async () => {
assert.deepEqual(await statusesFor((a) => a.get('/organisations/1/buildings/new')),
{ alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });
});
test('creating an organisation makes the creator its admin', async () => {
const res = await agents.nora.post('/organisations').type('form').send({ name: 'Nora Property Services' });
assert.equal(res.status, 303);
assert.equal((await agents.nora.get(`${res.headers.location}/edit`)).status, 200);
assert.equal((await agents.alice.get(res.headers.location)).status, 404);
});
test('inspections: view 201, open the edit form for draft 203', async () => {
assert.deepEqual(await statusesFor((a) => a.get('/inspections/201')),
{ alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });
assert.deepEqual(await statusesFor((a) => a.get('/inspections/203/edit')),
{ alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 }, '203 is carol\'s draft at building 20');
});
test('approve inspection 201 (dave\'s): only building admins', async () => {
assert.deepEqual(await statusesFor((a) => a.post('/inspections/201/approve'), ['bob', 'dave', 'nora', 'ravi']),
{ bob: 404, dave: 403, nora: 404, ravi: 404 });
assert.equal((await agents.alice.post('/inspections/201/approve')).status, 303);
});
test('creating an inspection needs inspector or building_admin at the chosen building', async () => {
const form = (building) => ({ building_id: String(building), title: 'Spot check', findings: '' });
assert.equal((await agents.dave.post('/inspections').type('form').send(form(10))).status, 303, 'dave is inspector at 10');
assert.equal((await agents.dave.post('/inspections').type('form').send(form(20))).status, 400, 'dave is only reporter at 20');
assert.equal((await agents.alice.post('/inspections').type('form').send(form(30))).status, 400, 'building 30 is another tenant');
});
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 USERS = ['alice', 'bob', 'carol', 'dave', 'nora', 'ravi'];const agents = {};before(async () => { await resetDatabase(); for (const name of USERS) agents[name] = await loginAs(name);});after(() => pool.end()); async function statusesFor(request, users = USERS) { const result = {}; for (const name of users) result[name] = (await request(agents[name])).status; return result;} test('organisation 1: view and update', async () => { assert.deepEqual(await statusesFor((a) => a.get('/organisations/1')), { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 }); assert.deepEqual(await statusesFor((a) => a.get('/organisations/1/edit')), { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });}); test('ravi is still a member of organisation 2 but can see none of its buildings', async () => { assert.equal((await agents.ravi.get('/organisations/2')).status, 200); assert.equal((await agents.ravi.get('/buildings/30')).status, 404);}); test('building 10: view, update, delete', async () => { assert.deepEqual(await statusesFor((a) => a.get('/buildings/10')), { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 }); assert.deepEqual(await statusesFor((a) => a.get('/buildings/10/edit')), { alice: 200, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 }); assert.deepEqual(await statusesFor((a) => a.post('/buildings/10/delete'), ['alice', 'bob', 'dave', 'nora']), { alice: 403, bob: 404, dave: 403, nora: 404 }, 'only org_admin may delete a building');}); test('creating buildings needs org_admin', async () => { assert.deepEqual(await statusesFor((a) => a.get('/organisations/1/buildings/new')), { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });}); test('creating an organisation makes the creator its admin', async () => { const res = await agents.nora.post('/organisations').type('form').send({ name: 'Nora Property Services' }); assert.equal(res.status, 303); assert.equal((await agents.nora.get(`${res.headers.location}/edit`)).status, 200); assert.equal((await agents.alice.get(res.headers.location)).status, 404);}); test('inspections: view 201, open the edit form for draft 203', async () => { assert.deepEqual(await statusesFor((a) => a.get('/inspections/201')), { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 }); assert.deepEqual(await statusesFor((a) => a.get('/inspections/203/edit')), { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 }, '203 is carol\'s draft at building 20');}); test('approve inspection 201 (dave\'s): only building admins', async () => { assert.deepEqual(await statusesFor((a) => a.post('/inspections/201/approve'), ['bob', 'dave', 'nora', 'ravi']), { bob: 404, dave: 403, nora: 404, ravi: 404 }); assert.equal((await agents.alice.post('/inspections/201/approve')).status, 303);}); test('creating an inspection needs inspector or building_admin at the chosen building', async () => { const form = (building) => ({ building_id: String(building), title: 'Spot check', findings: '' }); assert.equal((await agents.dave.post('/inspections').type('form').send(form(10))).status, 303, 'dave is inspector at 10'); assert.equal((await agents.dave.post('/inspections').type('form').send(form(20))).status, 400, 'dave is only reporter at 20'); assert.equal((await agents.alice.post('/inspections').type('form').send(form(30))).status, 400, 'building 30 is another tenant');});views/buildings/show.ejs changed
views/buildings/show.ejs<%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/organisations/<%= building.organisation_id %>"><%= building.organisation_name %></a> / Building #<%= building.id %></p>
<div class="page-header">
<h1><%= building.name %></h1>
<div class="actions">
<% if (can('UpdateBuilding', building)) { %>
<a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a>
<% } %>
<% if (can('DeleteBuilding', building)) { %>
<form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
<% } %>
</div>
</div>
<% if (error) { %>
<div class="flash flash-error" role="alert"><%= error %></div>
<% } %>
<h2>Latest issues</h2>
<% if (issues.length === 0) { %>
<p class="empty">No issues at this building.</p>
<% } else { %>
<table class="data">
<thead><tr><th>Title</th><th>Priority</th><th>Status</th><th>Occurred</th></tr></thead>
<tbody>
<% for (const issue of issues) { %>
<tr>
<td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td>
<td><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></td>
<td><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td>
<td><%= formatDate(issue.occurred_at) %></td>
</tr>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations/<%= building.organisation_id %>"><%= building.organisation_name %></a> / Building #<%= building.id %></p><div class="page-header"> <h1><%= building.name %></h1> <div class="actions"> <% if (can('UpdateBuilding', building)) { %> <a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a> <% } %> <% if (can('DeleteBuilding', building)) { %> <form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <button type="submit" class="btn btn-danger">Delete</button> </form> <% } %> </div></div><% if (error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Latest issues</h2><% if (issues.length === 0) { %> <p class="empty">No issues at this building.</p><% } else { %> <table class="data"> <thead><tr><th>Title</th><th>Priority</th><th>Status</th><th>Occurred</th></tr></thead> <tbody> <% for (const issue of issues) { %> <tr> <td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td> <td><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></td> <td><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td> <td><%= formatDate(issue.occurred_at) %></td> </tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %>views/inspections/show.ejs changed
views/inspections/show.ejs<%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/inspections">Inspections</a> / #<%= inspection.id %></p>
<div class="page-header">
<h1><%= inspection.title %></h1>
<div class="actions">
<% if (inspection.status === 'draft' && can('UpdateInspection', inspection)) { %>
<a class="btn" href="/inspections/<%= inspection.id %>/edit">Edit</a>
<% } %>
<% if (inspection.status === 'draft' && can('SubmitInspection', inspection)) { %>
<form method="post" action="/inspections/<%= inspection.id %>/submit"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Submit for approval</button></form>
<% } %>
<% if (inspection.status === 'submitted' && can('ReturnInspection', inspection)) { %>
<form method="post" action="/inspections/<%= inspection.id %>/return"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn">Return to draft</button></form>
<% } %>
<% if (inspection.status === 'submitted' && can('ApproveInspection', inspection)) { %>
<form method="post" action="/inspections/<%= inspection.id %>/approve" data-confirm="Approve this inspection? Approved inspections cannot be changed."><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Approve</button></form>
<% } %>
</div>
</div>
<% if (error) { %>
<div class="flash flash-error" role="alert"><%= error %></div>
<% } %>
<dl class="details">
<dt>Building</dt><dd><a href="/buildings/<%= inspection.building_id %>"><%= inspection.building_name %></a></dd>
<dt>Status</dt><dd><span class="badge status-<%= inspection.status %>"><%= inspection.status %></span></dd>
<dt>Created by</dt><dd><%= inspection.created_by_name ?? 'unknown' %></dd>
<% if (inspection.submitted_at) { %><dt>Submitted</dt><dd><%= formatDate(inspection.submitted_at) %> UTC</dd><% } %>
<% if (inspection.approved_at) { %><dt>Approved</dt><dd><%= formatDate(inspection.approved_at) %> UTC</dd><% } %>
</dl>
<h2>Findings</h2>
<% if (inspection.findings) { %><p class="prose"><%= inspection.findings %></p><% } else { %><p class="empty">No findings recorded yet.</p><% } %>
<h2>History</h2>
<% if (history.length === 0) { %>
<p class="muted">No status changes yet.</p>
<% } else { %>
<table class="data">
<thead><tr><th>When (UTC)</th><th>Change</th><th>By</th></tr></thead>
<tbody>
<% for (const h of history) { %>
<tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td><td><%= h.changed_by_name ?? 'unknown' %></td></tr>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/inspections">Inspections</a> / #<%= inspection.id %></p><div class="page-header"> <h1><%= inspection.title %></h1> <div class="actions"> <% if (inspection.status === 'draft' && can('UpdateInspection', inspection)) { %> <a class="btn" href="/inspections/<%= inspection.id %>/edit">Edit</a> <% } %> <% if (inspection.status === 'draft' && can('SubmitInspection', inspection)) { %> <form method="post" action="/inspections/<%= inspection.id %>/submit"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Submit for approval</button></form> <% } %> <% if (inspection.status === 'submitted' && can('ReturnInspection', inspection)) { %> <form method="post" action="/inspections/<%= inspection.id %>/return"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn">Return to draft</button></form> <% } %> <% if (inspection.status === 'submitted' && can('ApproveInspection', inspection)) { %> <form method="post" action="/inspections/<%= inspection.id %>/approve" data-confirm="Approve this inspection? Approved inspections cannot be changed."><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Approve</button></form> <% } %> </div></div><% if (error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %><dl class="details"> <dt>Building</dt><dd><a href="/buildings/<%= inspection.building_id %>"><%= inspection.building_name %></a></dd> <dt>Status</dt><dd><span class="badge status-<%= inspection.status %>"><%= inspection.status %></span></dd> <dt>Created by</dt><dd><%= inspection.created_by_name ?? 'unknown' %></dd> <% if (inspection.submitted_at) { %><dt>Submitted</dt><dd><%= formatDate(inspection.submitted_at) %> UTC</dd><% } %> <% if (inspection.approved_at) { %><dt>Approved</dt><dd><%= formatDate(inspection.approved_at) %> UTC</dd><% } %></dl><h2>Findings</h2><% if (inspection.findings) { %><p class="prose"><%= inspection.findings %></p><% } else { %><p class="empty">No findings recorded yet.</p><% } %><h2>History</h2><% if (history.length === 0) { %> <p class="muted">No status changes yet.</p><% } else { %> <table class="data"> <thead><tr><th>When (UTC)</th><th>Change</th><th>By</th></tr></thead> <tbody> <% for (const h of history) { %> <tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td><td><%= h.changed_by_name ?? 'unknown' %></td></tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %>views/organisations/show.ejs changed
views/organisations/show.ejs<%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/organisations">Organisations</a> / #<%= organisation.id %></p>
<div class="page-header">
<h1><%= organisation.name %></h1>
<div class="actions">
<% if (can('UpdateOrganisation', organisation)) { %>
<a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a>
<% } %>
<% if (can('CreateBuilding', organisation)) { %>
<a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a>
<% } %>
<% if (can('DeleteOrganisation', organisation)) { %>
<form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
<% } %>
</div>
</div>
<% if (typeof error !== 'undefined' && error) { %>
<div class="flash flash-error" role="alert"><%= error %></div>
<% } %>
<h2>Buildings</h2>
<% if (buildings.length === 0) { %>
<p class="empty">This organisation has no buildings yet.</p>
<% } else { %>
<table class="data">
<thead><tr><th>Building</th><th>Issues</th></tr></thead>
<tbody>
<% for (const building of buildings) { %>
<% const buildingRef = { id: building.id, organisation_id: organisation.id }; %>
<% if (can('ViewBuilding', buildingRef)) { %>
<tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>
<% } else { %>
<tr><td><%= building.name %></td><td class="muted">no access</td></tr>
<% } %>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations">Organisations</a> / #<%= organisation.id %></p><div class="page-header"> <h1><%= organisation.name %></h1> <div class="actions"> <% if (can('UpdateOrganisation', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a> <% } %> <% if (can('CreateBuilding', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a> <% } %> <% if (can('DeleteOrganisation', organisation)) { %> <form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <button type="submit" class="btn btn-danger">Delete</button> </form> <% } %> </div></div><% if (typeof error !== 'undefined' && error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Buildings</h2><% if (buildings.length === 0) { %> <p class="empty">This organisation has no buildings yet.</p><% } else { %> <table class="data"> <thead><tr><th>Building</th><th>Issues</th></tr></thead> <tbody> <% for (const building of buildings) { %> <% const buildingRef = { id: building.id, organisation_id: organisation.id }; %> <% if (can('ViewBuilding', buildingRef)) { %> <tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr> <% } else { %> <tr><td><%= building.name %></td><td class="muted">no access</td></tr> <% } %> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %>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
test/resource-authz.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