Checkpoint · Lesson 5.2
Authorizing issues in plain JavaScript: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m05-l02 -- src.
Files changed in this lesson
src/app.js changed
src/app.jsimport express from 'express';
import path from 'node:path';
import session from 'express-session';
import connectPgSimple from 'connect-pg-simple';
import { config } from './config.js';
import { pool } from './db.js';
import { loadUser, requireLogin } from './middleware/auth.js';
import { flash } from './middleware/flash.js';
import { 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() });
});
app.use('/account', accountRouter);
app.use('/issues', issuesRouter);
app.use('/organisations', organisationsRouter);
app.use('/buildings', buildingsRouter);
app.use('/inspections', inspectionsRouter);
app.use((req, res) => {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) {
console.error(err);
}
const message = err.expose ? err.message : 'Something went wrong';
res.status(status).render('error', { title: 'Error', status, message });
});
import express from 'express';import path from 'node:path';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { 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() });}); 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/authz/rules.js added
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);
}
}
const isOrgAdmin = user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');
if (isOrgAdmin) {
roles.add('building_admin');
}
return roles;
}
function hasAny(roles, wanted) {
return wanted.some((role) => roles.has(role));
}
export function can(user, action, resource) {
switch (action) {
// 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');
// resource: a building row { id, organisation_id, ... }. Creating an issue is an action on its building.
case 'CreateIssue':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', '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); } } const isOrgAdmin = user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin'); if (isOrgAdmin) { roles.add('building_admin'); } return roles;} function hasAny(roles, wanted) { return wanted.some((role) => roles.has(role));} export function can(user, action, resource) { switch (action) { // 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'); // resource: a building row { id, organisation_id, ... }. Creating an issue is an action on its building. case 'CreateIssue': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', '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/lib/http.js added
src/lib/http.jsexport function notFound(req, res) {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
}
export function forbidden(res, message = 'You do not have permission to do that.') {
res.status(403).render('forbidden', { title: 'Not allowed', message });
}
export function notFound(req, res) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });} export function forbidden(res, message = 'You do not have permission to do that.') { res.status(403).render('forbidden', { title: 'Not allowed', message });}src/routes/issues.js changed
src/routes/issues.jsimport express from 'express';
import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.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 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 });
const buildings = await listBuildings();
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');
});
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.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 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 }); const buildings = await listBuildings(); 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');});test/csrf.test.js changed
test/csrf.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
let alice;
before(async () => {
await resetDatabase();
alice = await loginAs('alice');
});
after(() => pool.end());
test('a logged-in POST without a token is refused with 403', async () => {
const res = await alice.post('/issues/129/delete').set('X-CSRF-Token', '');
assert.equal(res.status, 403);
assert.match(res.text, /did not come from Caretaker/);
assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 129')).rowCount, 1);
});
test('a token from another session is refused', async () => {
const bob = await loginAs('bob');
const bobToken = bob._defaults.find((d) => d.fn === 'set' && d.args[0] === 'X-CSRF-Token').args[1];
const res = await alice.post('/issues/129/delete').set('X-CSRF-Token', bobToken);
assert.equal(res.status, 403);
});
test('the right token in the form field works', async () => {
const page = await alice.get('/issues/129');
const token = page.text.match(/name="_csrf" value="([^"]+)"/)[1];
const res = await alice.post('/issues/129/delete').set('X-CSRF-Token', '').type('form').send({ _csrf: token });
assert.equal(res.status, 303);
});
test('every POST form on every page carries the token', async () => {
const pages = ['/', '/issues/new', '/issues/101', '/issues/101/edit', '/organisations/1', '/organisations/new', '/buildings/10', '/buildings/10/edit', '/inspections/new', '/inspections/201', '/inspections/203'];
for (const path of pages) {
const html = (await alice.get(path)).text;
const forms = (html.match(/<form method="post"/g) ?? []).length;
const tokens = (html.match(/<form method="post"[^>]*><input type="hidden" name="_csrf" value="[^"]+">/g) ?? []).length;
assert.ok(forms > 0, `${path} has a POST form`);
assert.equal(tokens, forms, `${path}: every POST form has a token`);
}
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let alice;before(async () => { await resetDatabase(); alice = await loginAs('alice');});after(() => pool.end()); test('a logged-in POST without a token is refused with 403', async () => { const res = await alice.post('/issues/129/delete').set('X-CSRF-Token', ''); assert.equal(res.status, 403); assert.match(res.text, /did not come from Caretaker/); assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 129')).rowCount, 1);}); test('a token from another session is refused', async () => { const bob = await loginAs('bob'); const bobToken = bob._defaults.find((d) => d.fn === 'set' && d.args[0] === 'X-CSRF-Token').args[1]; const res = await alice.post('/issues/129/delete').set('X-CSRF-Token', bobToken); assert.equal(res.status, 403);}); test('the right token in the form field works', async () => { const page = await alice.get('/issues/129'); const token = page.text.match(/name="_csrf" value="([^"]+)"/)[1]; const res = await alice.post('/issues/129/delete').set('X-CSRF-Token', '').type('form').send({ _csrf: token }); assert.equal(res.status, 303);}); test('every POST form on every page carries the token', async () => { const pages = ['/', '/issues/new', '/issues/101', '/issues/101/edit', '/organisations/1', '/organisations/new', '/buildings/10', '/buildings/10/edit', '/inspections/new', '/inspections/201', '/inspections/203']; for (const path of pages) { const html = (await alice.get(path)).text; const forms = (html.match(/<form method="post"/g) ?? []).length; const tokens = (html.match(/<form method="post"[^>]*><input type="hidden" name="_csrf" value="[^"]+">/g) ?? []).length; assert.ok(forms > 0, `${path} has a POST form`); assert.equal(tokens, forms, `${path}: every POST form has a token`); }});test/issue-authz.test.js added
test/issue-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) {
const result = {};
for (const name of USERS) result[name] = (await request(agents[name])).status;
return result;
}
test('view issue 101 (building 10)', async () => {
assert.deepEqual(await statusesFor((a) => a.get('/issues/101')),
{ alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });
});
test('open the edit form for issue 101', async () => {
assert.deepEqual(await statusesFor((a) => a.get('/issues/101/edit')),
{ alice: 200, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });
});
test('open the edit form for issue 103 (reported by dave, building 20)', async () => {
assert.deepEqual(await statusesFor((a) => a.get('/issues/103/edit')),
{ alice: 403, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });
});
test('view issue 105 (building 30) and 106 (building 40)', async () => {
assert.deepEqual(await statusesFor((a) => a.get('/issues/105')),
{ alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 404 });
assert.deepEqual(await statusesFor((a) => a.get('/issues/106')),
{ alice: 404, bob: 404, carol: 404, dave: 404, nora: 404, ravi: 404 });
});
test('report an issue at building 20', async () => {
const form = { title: 'Bins left by the back door', building_id: '20', priority: 'medium', occurred_at: '2026-11-22T09:00' };
const result = {};
for (const name of USERS) result[name] = (await agents[name].post('/issues').type('form').send(form)).status;
assert.deepEqual(result, { alice: 400, bob: 400, carol: 303, dave: 303, nora: 400, ravi: 400 });
});
test('a reporter cannot edit their own issue once it is closed', async () => {
await pool.query("UPDATE issues SET status = 'closed' WHERE id = 104");
assert.equal((await agents.dave.get('/issues/104/edit')).status, 403);
assert.equal((await agents.carol.get('/issues/104/edit')).status, 200);
});
test('only building admins may delete; refusals change nothing', async () => {
const refused = {};
for (const name of ['bob', 'dave', 'nora', 'ravi']) {
refused[name] = (await agents[name].post('/issues/102/delete')).status;
}
assert.deepEqual(refused, { bob: 404, dave: 403, nora: 404, ravi: 404 });
assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 102')).rowCount, 1);
assert.equal((await agents.alice.post('/issues/102/delete')).status, 303);
assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 102')).rowCount, 0);
});
test('the edit form cannot move an issue to another building', async () => {
const res = await agents.alice.post('/issues/101/edit').type('form')
.send({ title: 'Lift stuck between floors 2 and 3', building_id: '30', priority: 'high', status: 'open', occurred_at: '2026-11-02T09:15' });
assert.equal(res.status, 303);
const { rows } = await pool.query('SELECT building_id FROM issues WHERE id = 101');
assert.equal(rows[0].building_id, 10);
});
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) { const result = {}; for (const name of USERS) result[name] = (await request(agents[name])).status; return result;} test('view issue 101 (building 10)', async () => { assert.deepEqual(await statusesFor((a) => a.get('/issues/101')), { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });}); test('open the edit form for issue 101', async () => { assert.deepEqual(await statusesFor((a) => a.get('/issues/101/edit')), { alice: 200, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });}); test('open the edit form for issue 103 (reported by dave, building 20)', async () => { assert.deepEqual(await statusesFor((a) => a.get('/issues/103/edit')), { alice: 403, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });}); test('view issue 105 (building 30) and 106 (building 40)', async () => { assert.deepEqual(await statusesFor((a) => a.get('/issues/105')), { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 404 }); assert.deepEqual(await statusesFor((a) => a.get('/issues/106')), { alice: 404, bob: 404, carol: 404, dave: 404, nora: 404, ravi: 404 });}); test('report an issue at building 20', async () => { const form = { title: 'Bins left by the back door', building_id: '20', priority: 'medium', occurred_at: '2026-11-22T09:00' }; const result = {}; for (const name of USERS) result[name] = (await agents[name].post('/issues').type('form').send(form)).status; assert.deepEqual(result, { alice: 400, bob: 400, carol: 303, dave: 303, nora: 400, ravi: 400 });}); test('a reporter cannot edit their own issue once it is closed', async () => { await pool.query("UPDATE issues SET status = 'closed' WHERE id = 104"); assert.equal((await agents.dave.get('/issues/104/edit')).status, 403); assert.equal((await agents.carol.get('/issues/104/edit')).status, 200);}); test('only building admins may delete; refusals change nothing', async () => { const refused = {}; for (const name of ['bob', 'dave', 'nora', 'ravi']) { refused[name] = (await agents[name].post('/issues/102/delete')).status; } assert.deepEqual(refused, { bob: 404, dave: 403, nora: 404, ravi: 404 }); assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 102')).rowCount, 1); assert.equal((await agents.alice.post('/issues/102/delete')).status, 303); assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 102')).rowCount, 0);}); test('the edit form cannot move an issue to another building', async () => { const res = await agents.alice.post('/issues/101/edit').type('form') .send({ title: 'Lift stuck between floors 2 and 3', building_id: '30', priority: 'high', status: 'open', occurred_at: '2026-11-02T09:15' }); assert.equal(res.status, 303); const { rows } = await pool.query('SELECT building_id FROM issues WHERE id = 101'); assert.equal(rows[0].building_id, 10);});views/forbidden.ejs added
views/forbidden.ejs<%- include('partials/head') %>
<h1>Not allowed</h1>
<p><%= message %></p>
<p><a href="/">Go to the dashboard</a></p>
<%- include('partials/foot') %>
<%- include('partials/head') %><h1>Not allowed</h1><p><%= message %></p><p><a href="/">Go to the dashboard</a></p><%- include('partials/foot') %>views/issues/form.ejs changed
views/issues/form.ejs<%- include('../partials/head') %>
<h1><%= title %></h1>
<% if (Object.keys(errors).length > 0) { %>
<div class="error-summary" role="alert">
<p>Please fix the highlighted fields.</p>
</div>
<% } %>
<form method="post" action="<%= action %>" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<div class="field<%= errors.title ? ' has-error' : '' %>">
<label for="title">Title</label>
<input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200" required>
<% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %>
</div>
<% if (issue) { %>
<div class="field">
<label>Building</label>
<p><%= issue.building_name %></p>
</div>
<% } else { %>
<div class="field<%= errors.building_id ? ' has-error' : '' %>">
<label for="building_id">Building</label>
<select id="building_id" name="building_id">
<option value="">Choose…</option>
<% for (const building of buildings) { %>
<option value="<%= building.id %>"<%= values.building_id === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option>
<% } %>
</select>
<% if (errors.building_id) { %><p class="field-error"><%= errors.building_id %></p><% } %>
</div>
<% } %>
<div class="field<%= errors.occurred_at ? ' has-error' : '' %>">
<label for="occurred_at">Occurred at (UTC)</label>
<input id="occurred_at" name="occurred_at" type="datetime-local" value="<%= values.occurred_at ?? '' %>">
<% if (errors.occurred_at) { %><p class="field-error"><%= errors.occurred_at %></p><% } %>
</div>
<div class="field<%= errors.description ? ' has-error' : '' %>">
<label for="description">Description <span class="muted">(optional)</span></label>
<textarea id="description" name="description" maxlength="2000"><%= values.description ?? '' %></textarea>
<% if (errors.description) { %><p class="field-error"><%= errors.description %></p><% } %>
</div>
<div class="field<%= errors.priority ? ' has-error' : '' %>">
<label for="priority">Priority</label>
<select id="priority" name="priority">
<option value="">Choose…</option>
<% for (const s of priorities) { %>
<option value="<%= s %>"<%= values.priority === s ? ' selected' : '' %>><%= s %></option>
<% } %>
</select>
<% if (errors.priority) { %><p class="field-error"><%= errors.priority %></p><% } %>
</div>
<% if (issue) { %>
<div class="field<%= errors.status ? ' has-error' : '' %>">
<label for="status">Status</label>
<select id="status" name="status">
<% for (const s of statuses) { %>
<option value="<%= s %>"<%= values.status === s ? ' selected' : '' %>><%= s %></option>
<% } %>
</select>
<% if (errors.status) { %><p class="field-error"><%= errors.status %></p><% } %>
</div>
<% } %>
<div class="form-actions">
<button type="submit" class="btn btn-primary"><%= issue ? 'Save changes' : 'Save issue' %></button>
<a class="btn" href="<%= issue ? `/issues/${issue.id}` : '/issues' %>">Cancel</a>
</div>
</form>
<%- include('../partials/foot') %>
<%- include('../partials/head') %><h1><%= title %></h1> <% if (Object.keys(errors).length > 0) { %> <div class="error-summary" role="alert"> <p>Please fix the highlighted fields.</p> </div><% } %> <form method="post" action="<%= action %>" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <div class="field<%= errors.title ? ' has-error' : '' %>"> <label for="title">Title</label> <input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200" required> <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %> </div> <% if (issue) { %> <div class="field"> <label>Building</label> <p><%= issue.building_name %></p> </div> <% } else { %> <div class="field<%= errors.building_id ? ' has-error' : '' %>"> <label for="building_id">Building</label> <select id="building_id" name="building_id"> <option value="">Choose…</option> <% for (const building of buildings) { %> <option value="<%= building.id %>"<%= values.building_id === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option> <% } %> </select> <% if (errors.building_id) { %><p class="field-error"><%= errors.building_id %></p><% } %> </div> <% } %> <div class="field<%= errors.occurred_at ? ' has-error' : '' %>"> <label for="occurred_at">Occurred at (UTC)</label> <input id="occurred_at" name="occurred_at" type="datetime-local" value="<%= values.occurred_at ?? '' %>"> <% if (errors.occurred_at) { %><p class="field-error"><%= errors.occurred_at %></p><% } %> </div> <div class="field<%= errors.description ? ' has-error' : '' %>"> <label for="description">Description <span class="muted">(optional)</span></label> <textarea id="description" name="description" maxlength="2000"><%= values.description ?? '' %></textarea> <% if (errors.description) { %><p class="field-error"><%= errors.description %></p><% } %> </div> <div class="field<%= errors.priority ? ' has-error' : '' %>"> <label for="priority">Priority</label> <select id="priority" name="priority"> <option value="">Choose…</option> <% for (const s of priorities) { %> <option value="<%= s %>"<%= values.priority === s ? ' selected' : '' %>><%= s %></option> <% } %> </select> <% if (errors.priority) { %><p class="field-error"><%= errors.priority %></p><% } %> </div> <% if (issue) { %> <div class="field<%= errors.status ? ' has-error' : '' %>"> <label for="status">Status</label> <select id="status" name="status"> <% for (const s of statuses) { %> <option value="<%= s %>"<%= values.status === s ? ' selected' : '' %>><%= s %></option> <% } %> </select> <% if (errors.status) { %><p class="field-error"><%= errors.status %></p><% } %> </div> <% } %> <div class="form-actions"> <button type="submit" class="btn btn-primary"><%= issue ? 'Save changes' : 'Save issue' %></button> <a class="btn" href="<%= issue ? `/issues/${issue.id}` : '/issues' %>">Cancel</a> </div></form><%- include('../partials/foot') %>views/issues/show.ejs changed
views/issues/show.ejs<%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p>
<div class="page-header">
<h1><%= issue.title %></h1>
<div class="actions">
<% if (can('UpdateIssue', issue)) { %>
<a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a>
<% } %>
<% if (can('DeleteIssue', issue)) { %>
<form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
<% } %>
</div>
</div>
<dl class="details">
<dt>Building</dt><dd><%= issue.building_name %></dd>
<dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd>
<dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd>
<dt>Reported by</dt><dd><%= issue.reported_by_name ?? 'unknown' %></dd>
<dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd>
<dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd>
</dl>
<% if (issue.description) { %>
<h2>Description</h2>
<p class="prose"><%= issue.description %></p>
<% } %>
<%- include('../partials/foot') %>
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header"> <h1><%= issue.title %></h1> <div class="actions"> <% if (can('UpdateIssue', issue)) { %> <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a> <% } %> <% if (can('DeleteIssue', issue)) { %> <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <button type="submit" class="btn btn-danger">Delete</button> </form> <% } %> </div></div><dl class="details"> <dt>Building</dt><dd><%= issue.building_name %></dd> <dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd> <dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd> <dt>Reported by</dt><dd><%= issue.reported_by_name ?? 'unknown' %></dd> <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd> <dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd></dl><% if (issue.description) { %> <h2>Description</h2> <p class="prose"><%= issue.description %></p><% } %><%- 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/users.js
src/routes/account.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/access.test.js
test/auth.test.js
test/buildings.test.js
test/csrf.test.js
test/dashboard.test.js
test/helpers.js
test/inspections.test.js
test/issue-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