Module 5 · Authorization before Cedar
5.2 Authorizing issues in plain JavaScript
Write a can(user, action, resource) function for issues, enforce it in every issue route, choose between 404 and 403, hide buttons the user cannot use, and test the issue rows of the access matrix.
Starting point
req.user.access holds the user's active memberships and building roles. Nothing checks them.
Outcome
src/authz/rules.js (new: can(), rolesAtBuilding())src/lib/http.js (new: notFound(), forbidden())views/forbidden.ejs (new)test/issue-authz.test.js (new)- Viewing, creating, editing and deleting a single issue follow the access matrix.
- A user who may not see an issue gets
404; a user who may see it but not change it gets403. - Edit and Delete buttons appear only when the action is allowed. The building picker offers only buildings where the user may report.
- An issue's building can no longer be changed through the edit form. (Moving issues returns in Module 8, with the checks it needs.)
The issues list still shows everything. Lesson 5.3 fixes lists; until then, the state is local-only.
The problem
Log in as Dave in the browser and try to edit issue 101. Dave is an inspector at building 10: he may read issues there, not edit them. Today:
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000

He can also post the edit form for Bob's issue 105, in another company. We need a rule for every action, enforced on the server, at the moment of the action.
Build it
1. The rules, in one place
Create 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}`); }}Read it as the access matrix in code:
rolesAtBuildingturns the raw data into "what Alice is at building 10". It is the only place that knowsorg_adminimpliesbuilding_admin, which is how Carol inherits access.- The resource's
organisation_idcomes from the database row (findIssuejoinsbuildings), never from the request. UpdateIssuemixes roles and attributes: a reporter may edit an issue only if they reported it (reported_by) and it is not closed (status). That is ownership, layered on top of a role.- The action names (
ViewIssue,UpdateIssue, ...) are deliberate. Cedar uses actions too, and in Module 6 these same names become Cedar actions. - Unknown actions throw. Returning
falsewould hide a missing rule; returningtruewould be a hole.
2. 404 or 403?
Two small response helpers. Create src/lib/http.js:
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 });}<%- include('partials/head') %><h1>Not allowed</h1><p><%= message %></p><p><a href="/">Go to the dashboard</a></p><%- include('partials/foot') %>The rule we follow:
- If the user may not view a resource, answer
404 Not Found, exactly as if it did not exist. OtherwiseGET /issues/105returning403would confirm to Alice that issue 105 exists in some other company, and she could enumerate IDs to count another tenant's issues. - If the user may view it but not perform this action, answer
403 Forbidden. They can already see the issue, so the status reveals nothing new, and "not allowed" is more helpful than "not found".
3. Enforce it in the issues router
The changes go into five places in src/routes/issues.js. First the imports:
import { listBuildings } from '../models/buildings.js';import { listBuildings, findBuilding } from '../models/buildings.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';
Show the whole src/routes/issues.js after this change
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 (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(res, status, { issue = null, values = {}, errors = {} } = {}) { const buildings = await listBuildings(); 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) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl }); 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(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(res, 400, { values, errors }); } let created; try { created = await createIssue(record, req.user.id); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(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; await renderIssueForm(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; const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true }); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { issue, values, errors }); } try { await updateIssue(issue.id, record); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; 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 (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(res, status, { issue = null, values = {}, errors = {} } = {}) {
const buildings = await listBuildings();
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) {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
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(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(res, 400, { values, errors });
}
let created;
try {
created = await createIssue(record, req.user.id);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(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;
await renderIssueForm(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;
const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });
if (Object.keys(errors).length > 0) {
return renderIssueForm(res, 400, { issue, values, errors });
}
try {
await updateIssue(issue.id, record);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } });
}
throw err;
}
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/delete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
await deleteIssue(issue.id);
res.redirect(303, '/issues');
});
The building is chosen only when creating an issue:
if (buildingId === null) { if (!editing && buildingId === null) { errors.building_id = 'Choose a building.'; } if (!occurredAt) {
Show the whole src/routes/issues.js after this change
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(res, status, { issue = null, values = {}, errors = {} } = {}) { const buildings = await listBuildings(); 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) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl }); 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(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(res, 400, { values, errors }); } let created; try { created = await createIssue(record, req.user.id); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(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; await renderIssueForm(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; const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true }); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { issue, values, errors }); } try { await updateIssue(issue.id, record); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; 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(res, status, { issue = null, values = {}, errors = {} } = {}) {
const buildings = await listBuildings();
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) {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
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(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(res, 400, { values, errors });
}
let created;
try {
created = await createIssue(record, req.user.id);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(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;
await renderIssueForm(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;
const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });
if (Object.keys(errors).length > 0) {
return renderIssueForm(res, 400, { issue, values, errors });
}
try {
await updateIssue(issue.id, record);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } });
}
throw err;
}
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/delete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
await deleteIssue(issue.id);
res.redirect(303, '/issues');
});
The form offers only buildings where the user may report. It needs req, so the helper's signature changes:
async function renderIssueForm(res, status, { issue = null, values = {}, errors = {} } = {}) { const buildings = await listBuildings();async function renderIssueForm(req, res, status, { issue = null, values = {}, errors = {} } = {}) { const buildings = (await listBuildings()).filter((building) => can(req.user, 'CreateIssue', building));
Show the whole src/routes/issues.js after this change
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) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl }); 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(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(res, 400, { values, errors }); } let created; try { created = await createIssue(record, req.user.id); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(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; await renderIssueForm(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; const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true }); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { issue, values, errors }); } try { await updateIssue(issue.id, record); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; 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) {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
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(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(res, 400, { values, errors });
}
let created;
try {
created = await createIssue(record, req.user.id);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(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;
await renderIssueForm(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;
const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });
if (Object.keys(errors).length > 0) {
return renderIssueForm(res, 400, { issue, values, errors });
}
try {
await updateIssue(issue.id, record);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } });
}
throw err;
}
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/delete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
await deleteIssue(issue.id);
res.redirect(303, '/issues');
});
loadIssue now answers 404 for issues the user may not view. Every route that loads an issue goes through it, so viewing is checked everywhere at once:
const issue = id === null ? null : await findIssue(id); if (!issue) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl }); if (!issue || !can(req.user, 'ViewIssue', issue)) { notFound(req, res); return null; } return issue;
Show the whole src/routes/issues.js after this change
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(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(res, 400, { values, errors }); } let created; try { created = await createIssue(record, req.user.id); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(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; await renderIssueForm(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; const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true }); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { issue, values, errors }); } try { await updateIssue(issue.id, record); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; 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(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(res, 400, { values, errors });
}
let created;
try {
created = await createIssue(record, req.user.id);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(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;
await renderIssueForm(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;
const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });
if (Object.keys(errors).length > 0) {
return renderIssueForm(res, 400, { issue, values, errors });
}
try {
await updateIssue(issue.id, record);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } });
}
throw err;
}
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/delete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
await deleteIssue(issue.id);
res.redirect(303, '/issues');
});
Finally the routes themselves. Replace everything from issuesRouter.get('/new' to the end of the file:
issuesRouter.get('/new', async (req, res) => { await renderIssueForm(res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } }); 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(res, 400, { values, errors }); 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(res, 400, { values, errors: { building_id: 'Choose a building.' } }); 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; await renderIssueForm(res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } }); 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(res, 400, { issue, values, errors }); } try { await updateIssue(issue.id, record); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { issue, values, errors: { building_id: 'Choose a building.' } }); } throw err; 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');});
Show the whole src/routes/issues.js after this change
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');});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');
});
The pattern in every route is the same three steps, in this order:
- Load the resource from the database (
loadIssue), which also checksViewIssue. - Authorize the specific action against the loaded row.
- Act.
Authorizing before loading is impossible (we need the row's building and reporter); acting before authorizing is the bug we are fixing. For creation there is no issue yet, so the resource is the building the issue will belong to, loaded from the database by the ID in the form.
4. Let templates ask the same question
Templates should not repeat the rules. Give them the same can function. Add this to src/app.js, right after requireLogin:
import { flash } from './middleware/flash.js';import { can } from './authz/rules.js';
app.use(requireLogin);app.use((req, res, next) => { res.locals.can = (action, resource) => can(req.user, action, resource); next();});
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { 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 });
});
Show the buttons only when they would work:
<div class="actions"> <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a> <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> <% 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>
Show the whole views/issues/show.ejs after this change
<%- 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') %>
Hiding a button is not a security control; the routes enforce the rules. It just stops users from clicking things that will fail.
In the form, the building becomes read-only text when editing:
<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> <% 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> <% } %>
Show the whole views/issues/form.ejs after this change
<%- 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') %>
Run and inspect
Write tests for the issue rows of the access matrix. Each row lists the expected status for every user:
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);});Look closely at the "report at building 20" row: Alice is a viewer there, so for her 20 is not a valid choice and the form comes back with 400. Bob, Nora and Ravi get the same answer for the same reason.
Run the whole suite:
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ the scenario loads exactly as specified (242.143708ms)
✔ only one active assignment per user, building and role (0.936167ms)
✔ a revoked role can be granted again (1.294667ms)
✔ the My access page shows what the server loaded (75.160417ms)
✔ a correct login creates a session and shows the user (259.319542ms)
✔ a wrong password or unknown email gets the same 401 (52.877875ms)
✔ registration validates, creates a user, and logs them in (45.377542ms)
✔ registering an existing email is a field error (30.385583ms)
✔ logout destroys the session (56.198ms)
✔ a building can be created inside an organisation (278.998291ms)
✔ a duplicate building name in the same organisation is a field error (5.396333ms)
✔ the same building name is allowed in another organisation (4.8895ms)
✔ a building with issues cannot be deleted (12.892167ms)
✔ an empty building can be deleted (10.188834ms)
✔ an organisation with buildings cannot be deleted, an empty one can (21.337792ms)
✔ a logged-in POST without a token is refused with 403 (268.290666ms)
✔ a token from another session is refused (36.090459ms)
✖ the right token in the form field works (9.599792ms)
✔ every POST form on every page carries the token (41.15ms)
✔ the dashboard counts match the database (265.958625ms)
✔ every building appears with its organisation (5.103833ms)
✔ create a draft, edit it, submit it, approve it (314.178083ms)
✔ invalid transitions are refused with 409 and change nothing (11.502708ms)
✔ only drafts can be edited (4.646792ms)
✔ returning a submitted inspection makes it editable again (6.619541ms)
✔ concurrent approvals: exactly one wins (25.8685ms)
✔ unknown actions are 404 (3.325167ms)
✔ view issue 101 (building 10) (468.574042ms)
✔ open the edit form for issue 101 (22.062167ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (16.411584ms)
✔ view issue 105 (building 30) and 106 (building 40) (33.509958ms)
✔ report an issue at building 20 (20.264042ms)
✔ a reporter cannot edit their own issue once it is closed (6.30025ms)
✔ only building admins may delete; refusals change nothing (17.198333ms)
✔ the edit form cannot move an issue to another building (3.413417ms)
✔ the list pages 10 at a time and reports the total (289.628958ms)
Show 56 more lines
✔ pages do not overlap (18.9285ms)
✔ filters combine with AND (5.605459ms)
✔ sorting by priority puts critical first when descending (4.815584ms)
✔ unknown sort keys and SQL in the query string are ignored (25.937ms)
✔ GET /issues lists issues from the database (290.919125ms)
✔ GET /issues/101 shows one issue with its building (5.810292ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (15.267958ms)
✔ POST /issues re-renders the form with errors (4.434792ms)
✔ POST /issues stores the issue and redirects to it (7.33325ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (3.345209ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.445ms)
✔ an issue time in the future is rejected (3.543542ms)
✔ GET /issues/101/edit shows the current values (3.945042ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.033875ms)
✔ POST /issues/:id/delete removes the issue (8.459292ms)
✔ GET /organisations lists organisations with building counts (271.10725ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.200542ms)
✔ POST /organisations validates and creates (10.607208ms)
✔ POST /organisations/:id/edit renames the organisation (8.5615ms)
✔ unknown organisations are 404 (6.713041ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (366.8165ms)
✔ anonymous requests are redirected to the login page (213.822292ms)
✔ anonymous writes are refused and change nothing (11.034125ms)
✔ login and register pages stay public (5.489ms)
✔ login issues a new session id (no session fixation) (31.824ms)
✔ returnTo only follows local paths (31.526583ms)
✔ new issues and transitions record the logged-in user (72.535ms)
✔ the session cookie has the attributes we chose (28.952541ms)
ℹ tests 64
ℹ suites 0
ℹ pass 63
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6151.020625
✖ failing tests:
test at test/csrf.test.js:28:1
✖ the right token in the form field works (9.599792ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
403 !== 303
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/csrf.test.js:32:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 403,
expected: 303,
operator: 'strictEqual',
diff: 'simple'
}
One old test fails: "the right token in the form field works" in test/csrf.test.js. It logs in as Alice and deletes issue 130, which is at building 20, where Alice is only a viewer. Before this lesson anyone could delete anything, so the test passed for the wrong reason. Authorization now refuses with 403, which is correct. The test is about CSRF, not about Alice's rights, so give it an issue Alice may delete: issue 129, at building 10.
const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', ''); 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 = 130')).rowCount, 1); assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 129')).rowCount, 1);
const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', bobToken); const res = await alice.post('/issues/129/delete').set('X-CSRF-Token', bobToken);
const page = await alice.get('/issues/130'); const page = await alice.get('/issues/129'); const token = page.text.match(/name="_csrf" value="([^"]+)"/)[1]; const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', '').type('form').send({ _csrf: token }); const res = await alice.post('/issues/129/delete').set('X-CSRF-Token', '').type('form').send({ _csrf: token });
Show the whole test/csrf.test.js after this change
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`); }});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`);
}
});
This will happen again in this module: tests written before authorization existed sometimes relied on "everyone can do everything". Each time, decide whether the test was about permissions (then the new answer is the right one) or about something else (then pick data the user is allowed to touch).
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ the scenario loads exactly as specified (202.496417ms)
✔ only one active assignment per user, building and role (0.87375ms)
✔ a revoked role can be granted again (1.498667ms)
✔ the My access page shows what the server loaded (73.155666ms)
✔ a correct login creates a session and shows the user (261.66625ms)
✔ a wrong password or unknown email gets the same 401 (52.59925ms)
✔ registration validates, creates a user, and logs them in (47.595041ms)
✔ registering an existing email is a field error (34.580833ms)
✔ logout destroys the session (55.651ms)
✔ a building can be created inside an organisation (298.719625ms)
✔ a duplicate building name in the same organisation is a field error (4.222875ms)
✔ the same building name is allowed in another organisation (4.977416ms)
✔ a building with issues cannot be deleted (12.344333ms)
✔ an empty building can be deleted (10.352375ms)
✔ an organisation with buildings cannot be deleted, an empty one can (22.801042ms)
✔ a logged-in POST without a token is refused with 403 (268.786625ms)
✔ a token from another session is refused (36.989583ms)
✔ the right token in the form field works (8.936625ms)
✔ every POST form on every page carries the token (40.540875ms)
✔ the dashboard counts match the database (272.18525ms)
✔ every building appears with its organisation (4.5075ms)
✔ create a draft, edit it, submit it, approve it (304.04325ms)
✔ invalid transitions are refused with 409 and change nothing (12.620625ms)
✔ only drafts can be edited (4.764417ms)
✔ returning a submitted inspection makes it editable again (6.800792ms)
✔ concurrent approvals: exactly one wins (22.44775ms)
✔ unknown actions are 404 (2.896041ms)
✔ view issue 101 (building 10) (465.3565ms)
✔ open the edit form for issue 101 (24.057292ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (17.193167ms)
✔ view issue 105 (building 30) and 106 (building 40) (35.793334ms)
✔ report an issue at building 20 (18.315834ms)
✔ a reporter cannot edit their own issue once it is closed (5.9075ms)
✔ only building admins may delete; refusals change nothing (12.751458ms)
✔ the edit form cannot move an issue to another building (3.438542ms)
✔ the list pages 10 at a time and reports the total (267.571709ms)
Show 36 more lines
✔ pages do not overlap (15.091584ms)
✔ filters combine with AND (5.273125ms)
✔ sorting by priority puts critical first when descending (4.510542ms)
✔ unknown sort keys and SQL in the query string are ignored (25.027209ms)
✔ GET /issues lists issues from the database (276.311083ms)
✔ GET /issues/101 shows one issue with its building (5.565292ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (17.996834ms)
✔ POST /issues re-renders the form with errors (4.670458ms)
✔ POST /issues stores the issue and redirects to it (7.402ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (3.693208ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.357125ms)
✔ an issue time in the future is rejected (4.240458ms)
✔ GET /issues/101/edit shows the current values (4.054625ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.250042ms)
✔ POST /issues/:id/delete removes the issue (8.9095ms)
✔ GET /organisations lists organisations with building counts (316.800417ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.378167ms)
✔ POST /organisations validates and creates (11.827209ms)
✔ POST /organisations/:id/edit renames the organisation (9.336083ms)
✔ unknown organisations are 404 (7.706792ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (359.584875ms)
✔ anonymous requests are redirected to the login page (212.755834ms)
✔ anonymous writes are refused and change nothing (11.186333ms)
✔ login and register pages stay public (6.359792ms)
✔ login issues a new session id (no session fixation) (33.039208ms)
✔ returnTo only follows local paths (28.528291ms)
✔ new issues and transitions record the logged-in user (67.670667ms)
✔ the session cookie has the attributes we chose (26.235542ms)
ℹ tests 64
ℹ suites 0
ℹ pass 64
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6170.676125
All the earlier issue tests still pass: they log in as Carol, who is building_admin at buildings 10 and 20 through her organisation role.
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000


Experiment
/issues/105 into the address bar. What does she see, and does the response tell her that issue 105 exists?rm -f /tmp/alice.txt
TOKEN=$(curl -s -c /tmp/alice.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/alice.txt -c /tmp/alice.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=alice@example.test -d password=password123
for id in 105 99999; do curl -si -b /tmp/alice.txt http://localhost:3000/issues/$id | head -1; done
HTTP/1.1 404 Not Found
HTTP/1.1 404 Not Found
Reveal Answer
Both answer 404 Not Found with the same page. Alice cannot distinguish "exists in another company" from "does not exist". Now open /issues as Alice: the list still shows issue 105's title. We closed the front door and left a window open. That is the next lesson.
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ the scenario loads exactly as specified (196.287083ms)
✔ only one active assignment per user, building and role (0.927542ms)
✔ a revoked role can be granted again (1.311625ms)
✔ the My access page shows what the server loaded (73.984625ms)
✔ a correct login creates a session and shows the user (282.261292ms)
✔ a wrong password or unknown email gets the same 401 (53.680917ms)
✔ registration validates, creates a user, and logs them in (39.78125ms)
✔ registering an existing email is a field error (27.801ms)
✔ logout destroys the session (43.745792ms)
✔ a building can be created inside an organisation (325.325583ms)
✔ a duplicate building name in the same organisation is a field error (4.788292ms)
✔ the same building name is allowed in another organisation (4.596166ms)
✔ a building with issues cannot be deleted (12.529125ms)
✔ an empty building can be deleted (10.3565ms)
✔ an organisation with buildings cannot be deleted, an empty one can (22.020709ms)
✔ a logged-in POST without a token is refused with 403 (278.62175ms)
✔ a token from another session is refused (39.403792ms)
✔ the right token in the form field works (11.246042ms)
✔ every POST form on every page carries the token (50.543375ms)
✔ the dashboard counts match the database (272.727167ms)
✔ every building appears with its organisation (4.5475ms)
✔ create a draft, edit it, submit it, approve it (288.951334ms)
✔ invalid transitions are refused with 409 and change nothing (11.633125ms)
✔ only drafts can be edited (4.813458ms)
✔ returning a submitted inspection makes it editable again (14.386208ms)
✔ concurrent approvals: exactly one wins (22.093333ms)
✔ unknown actions are 404 (3.10875ms)
✔ view issue 101 (building 10) (465.507959ms)
✔ open the edit form for issue 101 (20.321209ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (17.397625ms)
✔ view issue 105 (building 30) and 106 (building 40) (32.917625ms)
✔ report an issue at building 20 (20.048167ms)
✔ a reporter cannot edit their own issue once it is closed (6.316125ms)
✔ only building admins may delete; refusals change nothing (13.528708ms)
✔ the edit form cannot move an issue to another building (3.111917ms)
✔ the list pages 10 at a time and reports the total (297.775084ms)
Show 36 more lines
✔ pages do not overlap (20.156125ms)
✔ filters combine with AND (5.812417ms)
✔ sorting by priority puts critical first when descending (5.055416ms)
✔ unknown sort keys and SQL in the query string are ignored (27.797917ms)
✔ GET /issues lists issues from the database (283.460458ms)
✔ GET /issues/101 shows one issue with its building (6.51325ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.55975ms)
✔ POST /issues re-renders the form with errors (5.0525ms)
✔ POST /issues stores the issue and redirects to it (8.582375ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (3.811875ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.201959ms)
✔ an issue time in the future is rejected (3.418292ms)
✔ GET /issues/101/edit shows the current values (4.330417ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.717708ms)
✔ POST /issues/:id/delete removes the issue (11.49775ms)
✔ GET /organisations lists organisations with building counts (274.2525ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (5.928333ms)
✔ POST /organisations validates and creates (12.203417ms)
✔ POST /organisations/:id/edit renames the organisation (8.452ms)
✔ unknown organisations are 404 (6.301292ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (341.146125ms)
✔ anonymous requests are redirected to the login page (212.784625ms)
✔ anonymous writes are refused and change nothing (11.1165ms)
✔ login and register pages stay public (7.0225ms)
✔ login issues a new session id (no session fixation) (34.856875ms)
✔ returnTo only follows local paths (28.189791ms)
✔ new issues and transitions record the logged-in user (64.857375ms)
✔ the session cookie has the attributes we chose (27.334583ms)
ℹ tests 64
ℹ suites 0
ℹ pass 64
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6174.787291
git add -A
git commit -m "Authorize issues in JavaScript"
[main e320b77] Authorize issues in JavaScript
9 files changed, 195 insertions(+), 38 deletions(-)
create mode 100644 src/authz/rules.js
create mode 100644 src/lib/http.js
create mode 100644 test/issue-authz.test.js
create mode 100644 views/forbidden.ejs
Symptom Every issue page is 404 for everyone
findIssue must return organisation_id (it does, from the join with buildings), and loadAccess must return numbers. If you changed a query to return building_id as text, === comparisons fail.
Symptom Error: No authorization rule for action ...
A route or template asks about an action that can() does not handle yet. Check the spelling; we add more actions in the next lesson.
Recap and next step
can(user, action, resource) holds the issue rules: roles per building, organisation inheritance, and ownership. Every issue route loads, authorizes, then acts; invisible resources are 404, visible-but-forbidden actions are 403. Templates ask the same function, so buttons match the rules. The edit form can no longer move an issue across buildings.
Lists, buildings, organisations, inspections and the dashboard are still unprotected. Next we isolate tenants everywhere, and meet the problem of lists.
Open the checkpoint files for lesson 5.2 (separate page; only files from this lesson and earlier)