Checkpoint · Lesson 4.3
Require login, and keep sessions safe: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m04-l03 -- src.
Files changed in this lesson
src/app.js changed
src/app.jsimport express from 'express';
import path from 'node:path';
import session from 'express-session';
import connectPgSimple from 'connect-pg-simple';
import { config } from './config.js';
import { pool } from './db.js';
import { loadUser, requireLogin } from './middleware/auth.js';
import { flash } from './middleware/flash.js';
import { authRouter } from './routes/auth.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;
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(authRouter);
app.use(requireLogin);
app.get('/', async (req, res) => {
res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });
});
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 { authRouter } from './routes/auth.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; 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(authRouter);app.use(requireLogin); app.get('/', async (req, res) => { res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });}); app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); app.use((req, res) => { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });}); app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) { console.error(err); } const message = err.expose ? err.message : 'Something went wrong'; res.status(status).render('error', { title: 'Error', status, message });});src/config.js changed
src/config.jsfunction required(name) {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`);
}
return value;
}
export const config = {
port: Number(process.env.PORT ?? 3000),
databaseUrl: required('DATABASE_URL'),
logSql: process.env.LOG_SQL === '1',
env: process.env.NODE_ENV ?? 'development',
sessionSecret: required('SESSION_SECRET'),
// Set COOKIE_SECURE=1 when the app is served over HTTPS (always, in production).
cookieSecure: process.env.COOKIE_SECURE === '1',
};
function required(name) { const value = process.env[name]; if (!value) { throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`); } return value;} export const config = { port: Number(process.env.PORT ?? 3000), databaseUrl: required('DATABASE_URL'), logSql: process.env.LOG_SQL === '1', env: process.env.NODE_ENV ?? 'development', sessionSecret: required('SESSION_SECRET'), // Set COOKIE_SECURE=1 when the app is served over HTTPS (always, in production). cookieSecure: process.env.COOKIE_SECURE === '1',};src/middleware/auth.js changed
src/middleware/auth.jsimport { findUserById } from '../models/users.js';
// Turns the session's userId into req.user (or null) for every request.
export async function loadUser(req, res, next) {
req.user = null;
if (req.session.userId) {
req.user = await findUserById(req.session.userId);
if (!req.user) {
// The account no longer exists. Forget it.
delete req.session.userId;
}
}
res.locals.currentUser = req.user;
next();
}
// Everything mounted after this middleware needs a logged-in user.
export function requireLogin(req, res, next) {
if (req.user) {
return next();
}
if (req.method === 'GET') {
req.session.returnTo = req.originalUrl;
}
req.flash('error', 'Please log in to continue.');
res.redirect(303, '/login');
}
import { findUserById } from '../models/users.js'; // Turns the session's userId into req.user (or null) for every request.export async function loadUser(req, res, next) { req.user = null; if (req.session.userId) { req.user = await findUserById(req.session.userId); if (!req.user) { // The account no longer exists. Forget it. delete req.session.userId; } } res.locals.currentUser = req.user; next();} // Everything mounted after this middleware needs a logged-in user.export function requireLogin(req, res, next) { if (req.user) { return next(); } if (req.method === 'GET') { req.session.returnTo = req.originalUrl; } req.flash('error', 'Please log in to continue.'); res.redirect(303, '/login');}src/middleware/flash.js added
src/middleware/flash.js// One-time messages: req.flash('success', 'Saved.') now, shown on the next page.
export function flash(req, res, next) {
res.locals.flash = req.session.flash ?? null;
delete req.session.flash;
req.flash = (type, message) => {
req.session.flash = { type, message };
};
next();
}
// One-time messages: req.flash('success', 'Saved.') now, shown on the next page.export function flash(req, res, next) { res.locals.flash = req.session.flash ?? null; delete req.session.flash; req.flash = (type, message) => { req.session.flash = { type, message }; }; next();}src/models/inspections.js changed
src/models/inspections.jsimport { query, withTransaction } from '../db.js';
// The workflow. Each action moves an inspection from exactly one status to another.
export const INSPECTION_TRANSITIONS = {
submit: { from: 'draft', to: 'submitted' },
approve: { from: 'submitted', to: 'approved' },
return: { from: 'submitted', to: 'draft' },
};
const INSPECTION_COLUMNS = `
a.id, a.building_id, s.name AS building_name, s.organisation_id, a.title, a.findings, a.status, a.created_by,
(SELECT u.name FROM users u WHERE u.id = a.created_by) AS created_by_name,
a.submitted_at, a.approved_at, a.created_at, a.updated_at`;
export async function listInspections({ status = null } = {}) {
const params = [];
let whereSql = '';
if (status) {
params.push(status);
whereSql = 'WHERE a.status = $1';
}
const { rows } = await query(
`SELECT ${INSPECTION_COLUMNS}
FROM inspections a
JOIN buildings s ON s.id = a.building_id
${whereSql}
ORDER BY a.updated_at DESC, a.id DESC`,
params,
);
return rows;
}
export async function findInspection(id) {
const { rows } = await query(`SELECT ${INSPECTION_COLUMNS} FROM inspections a JOIN buildings s ON s.id = a.building_id WHERE a.id = $1`, [id]);
return rows[0] ?? null;
}
export async function listInspectionHistory(inspectionId) {
const { rows } = await query(
`SELECT h.from_status, h.to_status, h.changed_at, u.name AS changed_by_name
FROM inspection_status_changes h LEFT JOIN users u ON u.id = h.changed_by
WHERE h.inspection_id = $1 ORDER BY h.changed_at, h.id`,
[inspectionId],
);
return rows;
}
export async function createInspection({ building_id, title, findings }, createdBy) {
const { rows } = await query(
'INSERT INTO inspections (building_id, title, findings, created_by) VALUES ($1, $2, $3, $4) RETURNING id',
[building_id, title, findings, createdBy],
);
return rows[0];
}
// Only drafts can be edited. Returns false if the inspection is not (or no longer) a draft.
export async function updateDraftInspection(id, { title, findings }) {
const { rowCount } = await query(
"UPDATE inspections SET title = $2, findings = $3, updated_at = now() WHERE id = $1 AND status = 'draft'",
[id, title, findings],
);
return rowCount === 1;
}
// Applies a transition atomically. Returns false if the inspection was not in the expected status.
export async function transitionInspection(id, action, changedBy) {
const transition = INSPECTION_TRANSITIONS[action];
if (!transition) {
throw new Error(`Unknown inspection action ${action}`);
}
return withTransaction(async (client) => {
const { rowCount } = await client.query(
`UPDATE inspections
SET status = $3,
updated_at = now(),
submitted_at = CASE WHEN $3 = 'submitted' THEN now() ELSE submitted_at END,
approved_at = CASE WHEN $3 = 'approved' THEN now() ELSE approved_at END
WHERE id = $1 AND status = $2`,
[id, transition.from, transition.to],
);
if (rowCount === 0) {
return false;
}
await client.query(
'INSERT INTO inspection_status_changes (inspection_id, from_status, to_status, changed_by) VALUES ($1, $2, $3, $4)',
[id, transition.from, transition.to, changedBy],
);
return true;
});
}
import { query, withTransaction } from '../db.js'; // The workflow. Each action moves an inspection from exactly one status to another.export const INSPECTION_TRANSITIONS = { submit: { from: 'draft', to: 'submitted' }, approve: { from: 'submitted', to: 'approved' }, return: { from: 'submitted', to: 'draft' },}; const INSPECTION_COLUMNS = ` a.id, a.building_id, s.name AS building_name, s.organisation_id, a.title, a.findings, a.status, a.created_by, (SELECT u.name FROM users u WHERE u.id = a.created_by) AS created_by_name, a.submitted_at, a.approved_at, a.created_at, a.updated_at`; export async function listInspections({ status = null } = {}) { const params = []; let whereSql = ''; if (status) { params.push(status); whereSql = 'WHERE a.status = $1'; } const { rows } = await query( `SELECT ${INSPECTION_COLUMNS} FROM inspections a JOIN buildings s ON s.id = a.building_id ${whereSql} ORDER BY a.updated_at DESC, a.id DESC`, params, ); return rows;} export async function findInspection(id) { const { rows } = await query(`SELECT ${INSPECTION_COLUMNS} FROM inspections a JOIN buildings s ON s.id = a.building_id WHERE a.id = $1`, [id]); return rows[0] ?? null;} export async function listInspectionHistory(inspectionId) { const { rows } = await query( `SELECT h.from_status, h.to_status, h.changed_at, u.name AS changed_by_name FROM inspection_status_changes h LEFT JOIN users u ON u.id = h.changed_by WHERE h.inspection_id = $1 ORDER BY h.changed_at, h.id`, [inspectionId], ); return rows;} export async function createInspection({ building_id, title, findings }, createdBy) { const { rows } = await query( 'INSERT INTO inspections (building_id, title, findings, created_by) VALUES ($1, $2, $3, $4) RETURNING id', [building_id, title, findings, createdBy], ); return rows[0];} // Only drafts can be edited. Returns false if the inspection is not (or no longer) a draft.export async function updateDraftInspection(id, { title, findings }) { const { rowCount } = await query( "UPDATE inspections SET title = $2, findings = $3, updated_at = now() WHERE id = $1 AND status = 'draft'", [id, title, findings], ); return rowCount === 1;} // Applies a transition atomically. Returns false if the inspection was not in the expected status.export async function transitionInspection(id, action, changedBy) { const transition = INSPECTION_TRANSITIONS[action]; if (!transition) { throw new Error(`Unknown inspection action ${action}`); } return withTransaction(async (client) => { const { rowCount } = await client.query( `UPDATE inspections SET status = $3, updated_at = now(), submitted_at = CASE WHEN $3 = 'submitted' THEN now() ELSE submitted_at END, approved_at = CASE WHEN $3 = 'approved' THEN now() ELSE approved_at END WHERE id = $1 AND status = $2`, [id, transition.from, transition.to], ); if (rowCount === 0) { return false; } await client.query( 'INSERT INTO inspection_status_changes (inspection_id, from_status, to_status, changed_by) VALUES ($1, $2, $3, $4)', [id, transition.from, transition.to, changedBy], ); return true; });}src/models/issues.js changed
src/models/issues.jsimport { query } from '../db.js';
const ISSUE_COLUMNS = `
e.id, e.building_id, s.name AS building_name, s.organisation_id,
e.title, e.description, e.priority, e.status, e.reported_by,
(SELECT u.name FROM users u WHERE u.id = e.reported_by) AS reported_by_name,
e.occurred_at, e.created_at, e.updated_at`;
// Sort keys a client may ask for. Keys come from the URL; the SQL is ours.
export const ISSUE_SORTS = {
occurred_at: 'e.occurred_at',
title: 'e.title',
building: 's.name',
priority: "array_position(ARRAY['low', 'medium', 'high', 'critical'], e.priority)",
status: "array_position(ARRAY['open', 'investigating', 'closed'], e.status)",
};
export async function listIssues({ page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null } = {}) {
const where = [];
const params = [];
if (status) {
params.push(status);
where.push(`e.status = $${params.length}`);
}
if (priority) {
params.push(priority);
where.push(`e.priority = $${params.length}`);
}
if (buildingId) {
params.push(buildingId);
where.push(`e.building_id = $${params.length}`);
}
const whereSql = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
const direction = dir === 'asc' ? 'ASC' : 'DESC';
const orderSql = `${ISSUE_SORTS[sort] ?? ISSUE_SORTS.occurred_at} ${direction}, e.id ${direction}`;
const countResult = await query(
`SELECT count(*)::int AS total FROM issues e JOIN buildings s ON s.id = e.building_id ${whereSql}`,
params,
);
const { rows } = await query(
`SELECT ${ISSUE_COLUMNS}
FROM issues e
JOIN buildings s ON s.id = e.building_id
${whereSql}
ORDER BY ${orderSql}
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
[...params, perPage, (page - 1) * perPage],
);
return { issues: rows, total: countResult.rows[0].total };
}
export async function listRecentIssuesForBuilding(buildingId, limit = 10) {
const { rows } = await query(
`SELECT ${ISSUE_COLUMNS}
FROM issues e
JOIN buildings s ON s.id = e.building_id
WHERE e.building_id = $1
ORDER BY e.occurred_at DESC, e.id DESC
LIMIT $2`,
[buildingId, limit],
);
return rows;
}
export async function findIssue(id) {
const { rows } = await query(
`SELECT ${ISSUE_COLUMNS}
FROM issues e
JOIN buildings s ON s.id = e.building_id
WHERE e.id = $1`,
[id],
);
return rows[0] ?? null;
}
export async function createIssue({ building_id, title, description, priority, occurred_at }, reportedBy) {
const { rows } = await query(
`INSERT INTO issues (building_id, title, description, priority, occurred_at, reported_by)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id`,
[building_id, title, description, priority, occurred_at, reportedBy],
);
return rows[0];
}
export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) {
const { rows } = await query(
`UPDATE issues
SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now()
WHERE id = $1
RETURNING id`,
[id, building_id, title, description, priority, status, occurred_at],
);
return rows[0] ?? null;
}
export async function deleteIssue(id) {
const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]);
return rowCount === 1;
}
import { query } from '../db.js'; const ISSUE_COLUMNS = ` e.id, e.building_id, s.name AS building_name, s.organisation_id, e.title, e.description, e.priority, e.status, e.reported_by, (SELECT u.name FROM users u WHERE u.id = e.reported_by) AS reported_by_name, e.occurred_at, e.created_at, e.updated_at`; // Sort keys a client may ask for. Keys come from the URL; the SQL is ours.export const ISSUE_SORTS = { occurred_at: 'e.occurred_at', title: 'e.title', building: 's.name', priority: "array_position(ARRAY['low', 'medium', 'high', 'critical'], e.priority)", status: "array_position(ARRAY['open', 'investigating', 'closed'], e.status)",}; export async function listIssues({ page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null } = {}) { const where = []; const params = []; if (status) { params.push(status); where.push(`e.status = $${params.length}`); } if (priority) { params.push(priority); where.push(`e.priority = $${params.length}`); } if (buildingId) { params.push(buildingId); where.push(`e.building_id = $${params.length}`); } const whereSql = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''; const direction = dir === 'asc' ? 'ASC' : 'DESC'; const orderSql = `${ISSUE_SORTS[sort] ?? ISSUE_SORTS.occurred_at} ${direction}, e.id ${direction}`; const countResult = await query( `SELECT count(*)::int AS total FROM issues e JOIN buildings s ON s.id = e.building_id ${whereSql}`, params, ); const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id ${whereSql} ORDER BY ${orderSql} LIMIT $${params.length + 1} OFFSET $${params.length + 2}`, [...params, perPage, (page - 1) * perPage], ); return { issues: rows, total: countResult.rows[0].total };} export async function listRecentIssuesForBuilding(buildingId, limit = 10) { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id WHERE e.building_id = $1 ORDER BY e.occurred_at DESC, e.id DESC LIMIT $2`, [buildingId, limit], ); return rows;} export async function findIssue(id) { const { rows } = await query( `SELECT ${ISSUE_COLUMNS} FROM issues e JOIN buildings s ON s.id = e.building_id WHERE e.id = $1`, [id], ); return rows[0] ?? null;} export async function createIssue({ building_id, title, description, priority, occurred_at }, reportedBy) { const { rows } = await query( `INSERT INTO issues (building_id, title, description, priority, occurred_at, reported_by) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`, [building_id, title, description, priority, occurred_at, reportedBy], ); return rows[0];} export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) { const { rows } = await query( `UPDATE issues SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now() WHERE id = $1 RETURNING id`, [id, building_id, title, description, priority, status, occurred_at], ); return rows[0] ?? null;} export async function deleteIssue(id) { const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]); return rowCount === 1;}src/routes/auth.js changed
src/routes/auth.jsimport express from 'express';
import { createUser, verifyCredentials, normaliseEmail } from '../models/users.js';
import { PG_ERRORS } from '../db.js';
import { cleanText } from '../lib/validation.js';
export const authRouter = express.Router();
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// Replace the current session with a brand-new one (new ID) that belongs to userId.
function startSession(req, userId) {
return new Promise((resolve, reject) => {
req.session.regenerate((err) => {
if (err) return reject(err);
req.session.userId = userId;
req.session.save((saveErr) => (saveErr ? reject(saveErr) : resolve()));
});
});
}
// Only follow returnTo if it is a path on this site. "//evil.test" would be another host.
function safeReturnTo(value) {
return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') ? value : '/';
}
function validateRegistration(input) {
const errors = {};
const name = cleanText(input.name, { min: 1, max: 100 });
const email = normaliseEmail(input.email);
const password = typeof input.password === 'string' ? input.password : '';
if (!name.ok) errors.name = 'Enter your name (up to 100 characters).';
if (!EMAIL_PATTERN.test(email) || email.length > 254) errors.email = 'Enter a valid email address.';
if (password.length < 10 || password.length > 200) errors.password = 'Use a password of 10 to 200 characters.';
return { errors, values: { name: name.text, email }, password };
}
authRouter.get('/register', (req, res) => {
res.render('auth/register', { title: 'Create an account', values: {}, errors: {} });
});
authRouter.post('/register', async (req, res) => {
const { errors, values, password } = validateRegistration(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(400).render('auth/register', { title: 'Create an account', values, errors });
}
let user;
try {
user = await createUser({ ...values, password });
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return res.status(400).render('auth/register', { title: 'Create an account', values, errors: { email: 'An account with this email already exists.' } });
}
throw err;
}
await startSession(req, user.id);
req.flash('success', `Welcome to Caretaker, ${user.name}.`);
res.redirect(303, '/');
});
authRouter.get('/login', (req, res) => {
res.render('auth/login', { title: 'Log in', email: '', error: null });
});
authRouter.post('/login', async (req, res) => {
const email = normaliseEmail(req.body?.email);
const user = await verifyCredentials(email, req.body?.password);
if (!user) {
return res.status(401).render('auth/login', { title: 'Log in', email, error: 'Email or password is incorrect.' });
}
const returnTo = safeReturnTo(req.session.returnTo);
await startSession(req, user.id);
res.redirect(303, returnTo);
});
authRouter.post('/logout', (req, res, next) => {
req.session.destroy((err) => {
if (err) return next(err);
res.clearCookie('caretaker.sid');
res.redirect(303, '/login');
});
});
import express from 'express';import { createUser, verifyCredentials, normaliseEmail } from '../models/users.js';import { PG_ERRORS } from '../db.js';import { cleanText } from '../lib/validation.js'; export const authRouter = express.Router(); const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Replace the current session with a brand-new one (new ID) that belongs to userId.function startSession(req, userId) { return new Promise((resolve, reject) => { req.session.regenerate((err) => { if (err) return reject(err); req.session.userId = userId; req.session.save((saveErr) => (saveErr ? reject(saveErr) : resolve())); }); });} // Only follow returnTo if it is a path on this site. "//evil.test" would be another host.function safeReturnTo(value) { return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') ? value : '/';} function validateRegistration(input) { const errors = {}; const name = cleanText(input.name, { min: 1, max: 100 }); const email = normaliseEmail(input.email); const password = typeof input.password === 'string' ? input.password : ''; if (!name.ok) errors.name = 'Enter your name (up to 100 characters).'; if (!EMAIL_PATTERN.test(email) || email.length > 254) errors.email = 'Enter a valid email address.'; if (password.length < 10 || password.length > 200) errors.password = 'Use a password of 10 to 200 characters.'; return { errors, values: { name: name.text, email }, password };} authRouter.get('/register', (req, res) => { res.render('auth/register', { title: 'Create an account', values: {}, errors: {} });}); authRouter.post('/register', async (req, res) => { const { errors, values, password } = validateRegistration(req.body ?? {}); if (Object.keys(errors).length > 0) { return res.status(400).render('auth/register', { title: 'Create an account', values, errors }); } let user; try { user = await createUser({ ...values, password }); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return res.status(400).render('auth/register', { title: 'Create an account', values, errors: { email: 'An account with this email already exists.' } }); } throw err; } await startSession(req, user.id); req.flash('success', `Welcome to Caretaker, ${user.name}.`); res.redirect(303, '/');}); authRouter.get('/login', (req, res) => { res.render('auth/login', { title: 'Log in', email: '', error: null });}); authRouter.post('/login', async (req, res) => { const email = normaliseEmail(req.body?.email); const user = await verifyCredentials(email, req.body?.password); if (!user) { return res.status(401).render('auth/login', { title: 'Log in', email, error: 'Email or password is incorrect.' }); } const returnTo = safeReturnTo(req.session.returnTo); await startSession(req, user.id); res.redirect(303, returnTo);}); authRouter.post('/logout', (req, res, next) => { req.session.destroy((err) => { if (err) return next(err); res.clearCookie('caretaker.sid'); res.redirect(303, '/login'); });});src/routes/inspections.js changed
src/routes/inspections.jsimport express from 'express';
import { listInspections, findInspection, listInspectionHistory, createInspection, updateDraftInspection, transitionInspection, INSPECTION_TRANSITIONS } from '../models/inspections.js';
import { listBuildings } from '../models/buildings.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { cleanText } from '../lib/validation.js';
export const inspectionsRouter = express.Router();
const INSPECTION_STATUSES = ['draft', 'submitted', 'approved'];
function validateInspection(input, { requireBuilding }) {
const errors = {};
const title = cleanText(input.title, { min: 3, max: 200 });
const findings = cleanText(input.findings, { max: 5000 });
const buildingId = parseId(input.building_id);
if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.';
if (!findings.ok) errors.findings = 'Findings must be at most 5000 characters.';
if (requireBuilding && buildingId === null) errors.building_id = 'Choose a building.';
return { errors, values: { title: title.text, findings: findings.text, building_id: buildingId } };
}
async function renderInspectionForm(res, status, { inspection = null, values = {}, errors = {} } = {}) {
res.status(status).render('inspections/form', {
title: inspection ? `Edit inspection #${inspection.id}` : 'New inspection',
action: inspection ? `/inspections/${inspection.id}/edit` : '/inspections',
inspection,
values,
errors,
buildings: inspection ? [] : await listBuildings(),
});
}
async function renderInspectionPage(res, status, inspection, error = null) {
const history = await listInspectionHistory(inspection.id);
res.status(status).render('inspections/show', { title: inspection.title, inspection, history, error });
}
async function loadInspection(req, res) {
const id = parseId(req.params.id);
const inspection = id === null ? null : await findInspection(id);
if (!inspection) {
res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });
return null;
}
return inspection;
}
inspectionsRouter.get('/', async (req, res) => {
const status = INSPECTION_STATUSES.includes(req.query.status) ? req.query.status : null;
res.render('inspections/index', { title: 'Inspections', inspections: await listInspections({ status }), status, statuses: INSPECTION_STATUSES });
});
inspectionsRouter.get('/new', async (req, res) => {
await renderInspectionForm(res, 200);
});
inspectionsRouter.post('/', async (req, res) => {
const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: true });
if (Object.keys(errors).length > 0) {
return renderInspectionForm(res, 400, { values, errors });
}
try {
const created = await createInspection(values, req.user.id);
res.redirect(303, `/inspections/${created.id}`);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderInspectionForm(res, 400, { values, errors: { building_id: 'Choose a building.' } });
}
throw err;
}
});
inspectionsRouter.get('/:id', async (req, res) => {
const inspection = await loadInspection(req, res);
if (!inspection) return;
await renderInspectionPage(res, 200, inspection);
});
inspectionsRouter.get('/:id/edit', async (req, res) => {
const inspection = await loadInspection(req, res);
if (!inspection) return;
if (inspection.status !== 'draft') {
return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');
}
await renderInspectionForm(res, 200, { inspection, values: inspection });
});
inspectionsRouter.post('/:id/edit', async (req, res) => {
const inspection = await loadInspection(req, res);
if (!inspection) return;
const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false });
if (Object.keys(errors).length > 0) {
return renderInspectionForm(res, 400, { inspection, values, errors });
}
const updated = await updateDraftInspection(inspection.id, values);
if (!updated) {
return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');
}
res.redirect(303, `/inspections/${inspection.id}`);
});
// POST /inspections/:id/submit, /approve and /return share one handler.
inspectionsRouter.post('/:id/:action', async (req, res, next) => {
if (!Object.hasOwn(INSPECTION_TRANSITIONS, req.params.action)) {
return next();
}
const inspection = await loadInspection(req, res);
if (!inspection) return;
const changed = await transitionInspection(inspection.id, req.params.action, req.user.id);
if (!changed) {
const fresh = await findInspection(inspection.id);
return renderInspectionPage(res, 409, fresh, `This inspection is ${fresh.status}; it cannot be ${req.params.action === 'return' ? 'returned' : `${req.params.action}d`} now.`);
}
res.redirect(303, `/inspections/${inspection.id}`);
});
import express from 'express';import { listInspections, findInspection, listInspectionHistory, createInspection, updateDraftInspection, transitionInspection, INSPECTION_TRANSITIONS } from '../models/inspections.js';import { listBuildings } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const inspectionsRouter = express.Router(); const INSPECTION_STATUSES = ['draft', 'submitted', 'approved']; function validateInspection(input, { requireBuilding }) { const errors = {}; const title = cleanText(input.title, { min: 3, max: 200 }); const findings = cleanText(input.findings, { max: 5000 }); const buildingId = parseId(input.building_id); if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.'; if (!findings.ok) errors.findings = 'Findings must be at most 5000 characters.'; if (requireBuilding && buildingId === null) errors.building_id = 'Choose a building.'; return { errors, values: { title: title.text, findings: findings.text, building_id: buildingId } };} async function renderInspectionForm(res, status, { inspection = null, values = {}, errors = {} } = {}) { res.status(status).render('inspections/form', { title: inspection ? `Edit inspection #${inspection.id}` : 'New inspection', action: inspection ? `/inspections/${inspection.id}/edit` : '/inspections', inspection, values, errors, buildings: inspection ? [] : await listBuildings(), });} async function renderInspectionPage(res, status, inspection, error = null) { const history = await listInspectionHistory(inspection.id); res.status(status).render('inspections/show', { title: inspection.title, inspection, history, error });} async function loadInspection(req, res) { const id = parseId(req.params.id); const inspection = id === null ? null : await findInspection(id); if (!inspection) { res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl }); return null; } return inspection;} inspectionsRouter.get('/', async (req, res) => { const status = INSPECTION_STATUSES.includes(req.query.status) ? req.query.status : null; res.render('inspections/index', { title: 'Inspections', inspections: await listInspections({ status }), status, statuses: INSPECTION_STATUSES });}); inspectionsRouter.get('/new', async (req, res) => { await renderInspectionForm(res, 200);}); inspectionsRouter.post('/', async (req, res) => { const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: true }); if (Object.keys(errors).length > 0) { return renderInspectionForm(res, 400, { values, errors }); } try { const created = await createInspection(values, req.user.id); res.redirect(303, `/inspections/${created.id}`); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderInspectionForm(res, 400, { values, errors: { building_id: 'Choose a building.' } }); } throw err; }}); inspectionsRouter.get('/:id', async (req, res) => { const inspection = await loadInspection(req, res); if (!inspection) return; await renderInspectionPage(res, 200, inspection);}); inspectionsRouter.get('/:id/edit', async (req, res) => { const inspection = await loadInspection(req, res); if (!inspection) return; if (inspection.status !== 'draft') { return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.'); } await renderInspectionForm(res, 200, { inspection, values: inspection });}); inspectionsRouter.post('/:id/edit', async (req, res) => { const inspection = await loadInspection(req, res); if (!inspection) return; const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false }); if (Object.keys(errors).length > 0) { return renderInspectionForm(res, 400, { inspection, values, errors }); } const updated = await updateDraftInspection(inspection.id, values); if (!updated) { return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.'); } res.redirect(303, `/inspections/${inspection.id}`);}); // POST /inspections/:id/submit, /approve and /return share one handler.inspectionsRouter.post('/:id/:action', async (req, res, next) => { if (!Object.hasOwn(INSPECTION_TRANSITIONS, req.params.action)) { return next(); } const inspection = await loadInspection(req, res); if (!inspection) return; const changed = await transitionInspection(inspection.id, req.params.action, req.user.id); if (!changed) { const fresh = await findInspection(inspection.id); return renderInspectionPage(res, 409, fresh, `This inspection is ${fresh.status}; it cannot be ${req.params.action === 'return' ? 'returned' : `${req.params.action}d`} now.`); } res.redirect(303, `/inspections/${inspection.id}`);});src/routes/issues.js changed
src/routes/issues.jsimport express from 'express';
import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.js';
import { listBuildings } from '../models/buildings.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { cleanText } from '../lib/validation.js';
export const 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 } from '../models/buildings.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');});test/auth.test.js changed
test/auth.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase } from './helpers.js';
before(resetDatabase);
after(() => pool.end());
test('a correct login creates a session and shows the user', async () => {
const agent = request.agent(app);
const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' });
assert.equal(res.status, 303);
assert.match(res.headers['set-cookie'][0], /^caretaker\.sid=s%3A.+; Path=\/; Expires=.+; HttpOnly; SameSite=Lax$/);
const home = await agent.get('/');
assert.match(home.text, /Signed in as <strong>Alice Byrne<\/strong>/);
});
test('a wrong password or unknown email gets the same 401 and no session', async () => {
for (const email of ['alice@example.test', 'mallory@example.test']) {
const res = await request(app).post('/login').type('form').send({ email, password: 'wrong-password' });
assert.equal(res.status, 401);
assert.match(res.text, /Email or password is incorrect/);
assert.equal(res.headers['set-cookie'], undefined);
}
});
test('registration validates, creates a user, and logs them in', async () => {
const agent = request.agent(app);
const bad = await agent.post('/register').type('form').send({ name: 'Erin', email: 'not-an-email', password: 'short' });
assert.equal(bad.status, 400);
assert.match(bad.text, /Enter a valid email address/);
assert.match(bad.text, /Use a password of 10 to 200 characters/);
const good = await agent.post('/register').type('form').send({ name: 'Erin Walsh', email: 'Erin@Example.test', password: 'correct horse battery' });
assert.equal(good.status, 303);
assert.match((await agent.get('/')).text, /Signed in as <strong>Erin Walsh<\/strong>/);
const { rows } = await pool.query("SELECT email FROM users WHERE name = 'Erin Walsh'");
assert.deepEqual(rows, [{ email: 'erin@example.test' }]);
});
test('registering an existing email is a field error', async () => {
const res = await request(app).post('/register').type('form').send({ name: 'Alice Again', email: 'alice@example.test', password: 'another long password' });
assert.equal(res.status, 400);
assert.match(res.text, /already exists/);
});
test('logout destroys the session', async () => {
const agent = request.agent(app);
await agent.post('/login').type('form').send({ email: 'bob@example.test', password: 'password123' });
await agent.post('/logout');
const home = await agent.get('/');
assert.equal(home.status, 303);
assert.equal(home.headers.location, '/login');
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('a correct login creates a session and shows the user', async () => { const agent = request.agent(app); const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' }); assert.equal(res.status, 303); assert.match(res.headers['set-cookie'][0], /^caretaker\.sid=s%3A.+; Path=\/; Expires=.+; HttpOnly; SameSite=Lax$/); const home = await agent.get('/'); assert.match(home.text, /Signed in as <strong>Alice Byrne<\/strong>/);}); test('a wrong password or unknown email gets the same 401 and no session', async () => { for (const email of ['alice@example.test', 'mallory@example.test']) { const res = await request(app).post('/login').type('form').send({ email, password: 'wrong-password' }); assert.equal(res.status, 401); assert.match(res.text, /Email or password is incorrect/); assert.equal(res.headers['set-cookie'], undefined); }}); test('registration validates, creates a user, and logs them in', async () => { const agent = request.agent(app); const bad = await agent.post('/register').type('form').send({ name: 'Erin', email: 'not-an-email', password: 'short' }); assert.equal(bad.status, 400); assert.match(bad.text, /Enter a valid email address/); assert.match(bad.text, /Use a password of 10 to 200 characters/); const good = await agent.post('/register').type('form').send({ name: 'Erin Walsh', email: 'Erin@Example.test', password: 'correct horse battery' }); assert.equal(good.status, 303); assert.match((await agent.get('/')).text, /Signed in as <strong>Erin Walsh<\/strong>/); const { rows } = await pool.query("SELECT email FROM users WHERE name = 'Erin Walsh'"); assert.deepEqual(rows, [{ email: 'erin@example.test' }]);}); test('registering an existing email is a field error', async () => { const res = await request(app).post('/register').type('form').send({ name: 'Alice Again', email: 'alice@example.test', password: 'another long password' }); assert.equal(res.status, 400); assert.match(res.text, /already exists/);}); test('logout destroys the session', async () => { const agent = request.agent(app); await agent.post('/login').type('form').send({ email: 'bob@example.test', password: 'password123' }); await agent.post('/logout'); const home = await agent.get('/'); assert.equal(home.status, 303); assert.equal(home.headers.location, '/login');});test/buildings.test.js changed
test/buildings.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
let agent;
before(async () => {
await resetDatabase();
agent = await loginAs('carol');
});
after(() => pool.end());
test('a building can be created inside an organisation', async () => {
const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Galway Townhouse' });
assert.equal(res.status, 303);
const page = await agent.get(res.headers.location);
assert.match(page.text, /<h1>Galway Townhouse<\/h1>/);
assert.match(page.text, /Liffey Estates/);
});
test('a duplicate building name in the same organisation is a field error', async () => {
const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Cork Apartments' });
assert.equal(res.status, 400);
assert.match(res.text, /already has a building with that name/);
});
test('the same building name is allowed in another organisation', async () => {
const res = await agent.post('/organisations/2/buildings').type('form').send({ name: 'Cork Apartments' });
assert.equal(res.status, 303);
});
test('a building with issues cannot be deleted', async () => {
const res = await agent.post('/buildings/10/delete');
assert.equal(res.status, 409);
assert.match(res.text, /still has maintenance issues/);
assert.equal((await agent.get('/buildings/10')).status, 200);
});
test('an empty building can be deleted', async () => {
const created = await agent.post('/organisations/2/buildings').type('form').send({ name: 'Temporary Annex' });
const res = await agent.post(`${created.headers.location}/delete`);
assert.equal(res.status, 303);
assert.equal(res.headers.location, '/organisations/2');
assert.equal((await agent.get(created.headers.location)).status, 404);
});
test('an organisation with buildings cannot be deleted, an empty one can', async () => {
const blocked = await agent.post('/organisations/1/delete');
assert.equal(blocked.status, 409);
assert.match(blocked.text, /still has buildings/);
const created = await agent.post('/organisations').type('form').send({ name: 'Short-lived Ltd' });
const res = await agent.post(`${created.headers.location}/delete`);
assert.equal(res.status, 303);
assert.equal((await agent.get(created.headers.location)).status, 404);
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => { await resetDatabase(); agent = await loginAs('carol');});after(() => pool.end()); test('a building can be created inside an organisation', async () => { const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Galway Townhouse' }); assert.equal(res.status, 303); const page = await agent.get(res.headers.location); assert.match(page.text, /<h1>Galway Townhouse<\/h1>/); assert.match(page.text, /Liffey Estates/);}); test('a duplicate building name in the same organisation is a field error', async () => { const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Cork Apartments' }); assert.equal(res.status, 400); assert.match(res.text, /already has a building with that name/);}); test('the same building name is allowed in another organisation', async () => { const res = await agent.post('/organisations/2/buildings').type('form').send({ name: 'Cork Apartments' }); assert.equal(res.status, 303);}); test('a building with issues cannot be deleted', async () => { const res = await agent.post('/buildings/10/delete'); assert.equal(res.status, 409); assert.match(res.text, /still has maintenance issues/); assert.equal((await agent.get('/buildings/10')).status, 200);}); test('an empty building can be deleted', async () => { const created = await agent.post('/organisations/2/buildings').type('form').send({ name: 'Temporary Annex' }); const res = await agent.post(`${created.headers.location}/delete`); assert.equal(res.status, 303); assert.equal(res.headers.location, '/organisations/2'); assert.equal((await agent.get(created.headers.location)).status, 404);}); test('an organisation with buildings cannot be deleted, an empty one can', async () => { const blocked = await agent.post('/organisations/1/delete'); assert.equal(blocked.status, 409); assert.match(blocked.text, /still has buildings/); const created = await agent.post('/organisations').type('form').send({ name: 'Short-lived Ltd' }); const res = await agent.post(`${created.headers.location}/delete`); assert.equal(res.status, 303); assert.equal((await agent.get(created.headers.location)).status, 404);});test/dashboard.test.js changed
test/dashboard.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
let agent;
before(async () => {
await resetDatabase();
agent = await loginAs('carol');
});
after(() => pool.end());
test('the dashboard counts match the database', async () => {
const res = await agent.get('/');
assert.equal(res.status, 200);
const { rows } = await pool.query("SELECT count(*)::int AS n FROM issues WHERE status <> 'closed'");
assert.match(res.text, new RegExp(`<h3>Open issues</h3><div class="stat">${rows[0].n}</div>`));
assert.match(res.text, /<h3>Inspections awaiting approval<\/h3><div class="stat">2<\/div>/);
});
test('every building appears with its organisation', async () => {
const res = await agent.get('/');
for (const name of ['Dublin Offices', 'Cork Apartments', 'Galway Studios', 'Limerick House']) {
assert.match(res.text, new RegExp(name));
}
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => { await resetDatabase(); agent = await loginAs('carol');});after(() => pool.end()); test('the dashboard counts match the database', async () => { const res = await agent.get('/'); assert.equal(res.status, 200); const { rows } = await pool.query("SELECT count(*)::int AS n FROM issues WHERE status <> 'closed'"); assert.match(res.text, new RegExp(`<h3>Open issues</h3><div class="stat">${rows[0].n}</div>`)); assert.match(res.text, /<h3>Inspections awaiting approval<\/h3><div class="stat">2<\/div>/);}); test('every building appears with its organisation', async () => { const res = await agent.get('/'); for (const name of ['Dublin Offices', 'Cork Apartments', 'Galway Studios', 'Limerick House']) { assert.match(res.text, new RegExp(name)); }});test/helpers.js changed
test/helpers.jsimport request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { config } from '../src/config.js';
import { migrate } from '../src/migrate.js';
import { seed, SEED_PASSWORD } from '../src/seed.js';
// Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.
export async function loginAs(name, password = SEED_PASSWORD) {
const agent = request.agent(app);
const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password });
if (res.status !== 303) {
throw new Error(`Login as ${name} failed with status ${res.status}`);
}
return agent;
}
export async function resetDatabase() {
if (!config.databaseUrl.endsWith('/caretaker_test')) {
throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`);
}
await migrate(config.databaseUrl, { log: () => {} });
const client = await pool.connect();
try {
await seed(client);
} finally {
client.release();
}
}
import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { config } from '../src/config.js';import { migrate } from '../src/migrate.js';import { seed, SEED_PASSWORD } from '../src/seed.js'; // Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.export async function loginAs(name, password = SEED_PASSWORD) { const agent = request.agent(app); const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password }); if (res.status !== 303) { throw new Error(`Login as ${name} failed with status ${res.status}`); } return agent;} export async function resetDatabase() { if (!config.databaseUrl.endsWith('/caretaker_test')) { throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`); } await migrate(config.databaseUrl, { log: () => {} }); const client = await pool.connect(); try { await seed(client); } finally { client.release(); }}test/inspections.test.js changed
test/inspections.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
let agent;
before(async () => {
await resetDatabase();
agent = await loginAs('carol');
});
after(() => pool.end());
async function history(inspectionId) {
const { rows } = await pool.query('SELECT from_status, to_status FROM inspection_status_changes WHERE inspection_id = $1 ORDER BY id', [inspectionId]);
return rows.map((r) => `${r.from_status}->${r.to_status}`);
}
test('create a draft, edit it, submit it, approve it', async () => {
const created = await agent.post('/inspections').type('form').send({ building_id: '20', title: 'Stairwell lighting check', findings: '' });
assert.equal(created.status, 303);
const url = created.headers.location;
assert.equal((await agent.post(`${url}/edit`).type('form').send({ title: 'Stairwell lighting check', findings: 'All bulbs working.' })).status, 303);
assert.equal((await agent.post(`${url}/submit`)).status, 303);
assert.equal((await agent.post(`${url}/approve`)).status, 303);
const id = Number(url.split('/').pop());
assert.deepEqual(await history(id), ['draft->submitted', 'submitted->approved']);
const page = await agent.get(url);
assert.match(page.text, /All bulbs working/);
assert.match(page.text, /badge status-approved/);
});
test('invalid transitions are refused with 409 and change nothing', async () => {
assert.equal((await agent.post('/inspections/203/approve')).status, 409);
assert.equal((await agent.post('/inspections/203/return')).status, 409);
assert.deepEqual(await history(203), []);
});
test('only drafts can be edited', async () => {
const res = await agent.post('/inspections/201/edit').type('form').send({ title: 'Changed after submission', findings: '' });
assert.equal(res.status, 409);
const { rows } = await pool.query('SELECT title FROM inspections WHERE id = 201');
assert.equal(rows[0].title, 'Q4 lift maintenance inspection');
});
test('returning a submitted inspection makes it editable again', async () => {
assert.equal((await agent.post('/inspections/202/return')).status, 303);
assert.equal((await agent.get('/inspections/202/edit')).status, 200);
});
test('concurrent approvals: exactly one wins', async () => {
const results = await Promise.all(Array.from({ length: 8 }, () => agent.post('/inspections/201/approve')));
assert.deepEqual(results.map((r) => r.status).sort(), [303, 409, 409, 409, 409, 409, 409, 409]);
assert.deepEqual(await history(201), ['draft->submitted', 'submitted->approved']);
});
test('unknown actions are 404', async () => {
assert.equal((await agent.post('/inspections/201/delete')).status, 404);
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => { await resetDatabase(); agent = await loginAs('carol');});after(() => pool.end()); async function history(inspectionId) { const { rows } = await pool.query('SELECT from_status, to_status FROM inspection_status_changes WHERE inspection_id = $1 ORDER BY id', [inspectionId]); return rows.map((r) => `${r.from_status}->${r.to_status}`);} test('create a draft, edit it, submit it, approve it', async () => { const created = await agent.post('/inspections').type('form').send({ building_id: '20', title: 'Stairwell lighting check', findings: '' }); assert.equal(created.status, 303); const url = created.headers.location; assert.equal((await agent.post(`${url}/edit`).type('form').send({ title: 'Stairwell lighting check', findings: 'All bulbs working.' })).status, 303); assert.equal((await agent.post(`${url}/submit`)).status, 303); assert.equal((await agent.post(`${url}/approve`)).status, 303); const id = Number(url.split('/').pop()); assert.deepEqual(await history(id), ['draft->submitted', 'submitted->approved']); const page = await agent.get(url); assert.match(page.text, /All bulbs working/); assert.match(page.text, /badge status-approved/);}); test('invalid transitions are refused with 409 and change nothing', async () => { assert.equal((await agent.post('/inspections/203/approve')).status, 409); assert.equal((await agent.post('/inspections/203/return')).status, 409); assert.deepEqual(await history(203), []);}); test('only drafts can be edited', async () => { const res = await agent.post('/inspections/201/edit').type('form').send({ title: 'Changed after submission', findings: '' }); assert.equal(res.status, 409); const { rows } = await pool.query('SELECT title FROM inspections WHERE id = 201'); assert.equal(rows[0].title, 'Q4 lift maintenance inspection');}); test('returning a submitted inspection makes it editable again', async () => { assert.equal((await agent.post('/inspections/202/return')).status, 303); assert.equal((await agent.get('/inspections/202/edit')).status, 200);}); test('concurrent approvals: exactly one wins', async () => { const results = await Promise.all(Array.from({ length: 8 }, () => agent.post('/inspections/201/approve'))); assert.deepEqual(results.map((r) => r.status).sort(), [303, 409, 409, 409, 409, 409, 409, 409]); assert.deepEqual(await history(201), ['draft->submitted', 'submitted->approved']);}); test('unknown actions are 404', async () => { assert.equal((await agent.post('/inspections/201/delete')).status, 404);});test/issue-list.test.js changed
test/issue-list.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
let agent;
before(async () => {
await resetDatabase();
agent = await loginAs('carol');
});
after(() => pool.end());
// The issue ids linked from the table rows, in order.
function issueIds(html) {
return [...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1]));
}
test('the list pages 10 at a time and reports the total', async () => {
const first = await agent.get('/issues');
assert.equal(issueIds(first.text).length, 10);
assert.match(first.text, /30 issues/);
const third = await agent.get('/issues?page=3');
assert.equal(issueIds(third.text).length, 10);
const fourth = await agent.get('/issues?page=4');
assert.equal(issueIds(fourth.text).length, 0);
});
test('pages do not overlap', async () => {
const ids = [];
for (const page of [1, 2, 3]) ids.push(...issueIds((await agent.get(`/issues?page=${page}`)).text));
assert.equal(new Set(ids).size, 30);
});
test('filters combine with AND', async () => {
const res = await agent.get('/issues?status=open&building=20');
const ids = issueIds(res.text);
assert.ok(ids.length > 0);
const { rows } = await pool.query('SELECT id FROM issues WHERE status = $1 AND building_id = $2', ['open', 20]);
assert.deepEqual(new Set(ids), new Set(rows.map((r) => r.id)));
});
test('sorting by priority puts critical first when descending', async () => {
const res = await agent.get('/issues?sort=priority&dir=desc');
assert.match(res.text, /<span class="badge sev-critical">/);
const firstBadge = res.text.match(/class="badge sev-(\w+)"/)[1];
assert.equal(firstBadge, 'critical');
});
test('unknown sort keys and SQL in the query string are ignored', async () => {
for (const qs of ['sort=(SELECT%201/0)', 'sort=toString', 'dir=sideways', 'page=-1', 'status=%27%3B--', 'building=abc']) {
const res = await agent.get(`/issues?${qs}`);
assert.equal(res.status, 200, qs);
assert.equal(issueIds(res.text).length, 10, qs);
}
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => { await resetDatabase(); agent = await loginAs('carol');});after(() => pool.end()); // The issue ids linked from the table rows, in order.function issueIds(html) { return [...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1]));} test('the list pages 10 at a time and reports the total', async () => { const first = await agent.get('/issues'); assert.equal(issueIds(first.text).length, 10); assert.match(first.text, /30 issues/); const third = await agent.get('/issues?page=3'); assert.equal(issueIds(third.text).length, 10); const fourth = await agent.get('/issues?page=4'); assert.equal(issueIds(fourth.text).length, 0);}); test('pages do not overlap', async () => { const ids = []; for (const page of [1, 2, 3]) ids.push(...issueIds((await agent.get(`/issues?page=${page}`)).text)); assert.equal(new Set(ids).size, 30);}); test('filters combine with AND', async () => { const res = await agent.get('/issues?status=open&building=20'); const ids = issueIds(res.text); assert.ok(ids.length > 0); const { rows } = await pool.query('SELECT id FROM issues WHERE status = $1 AND building_id = $2', ['open', 20]); assert.deepEqual(new Set(ids), new Set(rows.map((r) => r.id)));}); test('sorting by priority puts critical first when descending', async () => { const res = await agent.get('/issues?sort=priority&dir=desc'); assert.match(res.text, /<span class="badge sev-critical">/); const firstBadge = res.text.match(/class="badge sev-(\w+)"/)[1]; assert.equal(firstBadge, 'critical');}); test('unknown sort keys and SQL in the query string are ignored', async () => { for (const qs of ['sort=(SELECT%201/0)', 'sort=toString', 'dir=sideways', 'page=-1', 'status=%27%3B--', 'building=abc']) { const res = await agent.get(`/issues?${qs}`); assert.equal(res.status, 200, qs); assert.equal(issueIds(res.text).length, 10, qs); }});test/issues.test.js changed
test/issues.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
let agent;
before(async () => {
await resetDatabase();
agent = await loginAs('carol');
});
after(() => pool.end());
const validIssue = { title: 'Water leak by the staff entrance', building_id: '10', priority: 'low', occurred_at: '2026-11-20T10:30' };
test('GET /issues lists issues from the database', async () => {
const res = await agent.get('/issues');
assert.equal(res.status, 200);
assert.match(res.text, /Lift stuck between floors 2 and 3/);
});
test('GET /issues/101 shows one issue with its building', async () => {
const res = await agent.get('/issues/101');
assert.equal(res.status, 200);
assert.match(res.text, /<h1>Lift stuck between floors 2 and 3<\/h1>/);
assert.match(res.text, /Dublin Offices/);
});
test('GET /issues/:id answers 404 for unknown or malformed ids', async () => {
for (const id of ['999999', 'abc', '0', '99999999999']) {
const res = await agent.get(`/issues/${id}`);
assert.equal(res.status, 404, `id ${id}`);
}
});
test('POST /issues re-renders the form with errors', async () => {
const res = await agent.post('/issues').type('form').send({ title: '', building_id: '', priority: '', occurred_at: '' });
assert.equal(res.status, 400);
assert.match(res.text, /Choose a building/);
assert.match(res.text, /Enter the date and time it happened/);
});
test('POST /issues stores the issue and redirects to it', async () => {
const res = await agent.post('/issues').type('form').send(validIssue);
assert.equal(res.status, 303);
const page = await agent.get(res.headers.location);
assert.equal(page.status, 200);
assert.match(page.text, /Water leak by the staff entrance/);
assert.match(page.text, /20 Nov 2026, 10:30 UTC/);
});
test('POST /issues with a building that does not exist is a form error, not a 500', async () => {
const res = await agent.post('/issues').type('form').send({ ...validIssue, building_id: '999' });
assert.equal(res.status, 400);
assert.match(res.text, /Choose a building/);
});
test('the stored row has the cleaned values and ignores a client-sent status', async () => {
await agent.post('/issues').type('form').send({ ...validIssue, title: ' Spaces around ', building_id: '20', status: 'closed' });
const { rows } = await pool.query("SELECT title, building_id, status FROM issues WHERE title = 'Spaces around'");
assert.deepEqual(rows, [{ title: 'Spaces around', building_id: 20, status: 'open' }]);
});
test('an issue time in the future is rejected', async () => {
const res = await agent.post('/issues').type('form').send({ ...validIssue, occurred_at: '2099-01-01T00:00' });
assert.equal(res.status, 400);
assert.match(res.text, /That time is in the future/);
});
test('GET /issues/101/edit shows the current values', async () => {
const res = await agent.get('/issues/101/edit');
assert.equal(res.status, 200);
assert.match(res.text, /value="2026-11-02T09:15"/);
assert.match(res.text, /<option value="open" selected>open<\/option>/);
});
test('POST /issues/:id/edit changes the status and updated_at', async () => {
const before = (await pool.query('SELECT updated_at FROM issues WHERE id = 103')).rows[0].updated_at;
const res = await agent.post('/issues/103/edit').type('form')
.send({ title: 'Front door lock sticks at entrance 4', building_id: '20', priority: 'medium', status: 'investigating', occurred_at: '2026-11-08T07:05' });
assert.equal(res.status, 303);
const { rows } = await pool.query('SELECT status, updated_at FROM issues WHERE id = 103');
assert.equal(rows[0].status, 'investigating');
assert.ok(rows[0].updated_at > before);
});
test('POST /issues/:id/delete removes the issue', async () => {
const created = await agent.post('/issues').type('form').send({ ...validIssue, title: 'Delete me please' });
const res = await agent.post(`${created.headers.location}/delete`);
assert.equal(res.status, 303);
assert.equal((await agent.get(created.headers.location)).status, 404);
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => { await resetDatabase(); agent = await loginAs('carol');});after(() => pool.end()); const validIssue = { title: 'Water leak by the staff entrance', building_id: '10', priority: 'low', occurred_at: '2026-11-20T10:30' }; test('GET /issues lists issues from the database', async () => { const res = await agent.get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('GET /issues/101 shows one issue with its building', async () => { const res = await agent.get('/issues/101'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Lift stuck between floors 2 and 3<\/h1>/); assert.match(res.text, /Dublin Offices/);}); test('GET /issues/:id answers 404 for unknown or malformed ids', async () => { for (const id of ['999999', 'abc', '0', '99999999999']) { const res = await agent.get(`/issues/${id}`); assert.equal(res.status, 404, `id ${id}`); }}); test('POST /issues re-renders the form with errors', async () => { const res = await agent.post('/issues').type('form').send({ title: '', building_id: '', priority: '', occurred_at: '' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/); assert.match(res.text, /Enter the date and time it happened/);}); test('POST /issues stores the issue and redirects to it', async () => { const res = await agent.post('/issues').type('form').send(validIssue); assert.equal(res.status, 303); const page = await agent.get(res.headers.location); assert.equal(page.status, 200); assert.match(page.text, /Water leak by the staff entrance/); assert.match(page.text, /20 Nov 2026, 10:30 UTC/);}); test('POST /issues with a building that does not exist is a form error, not a 500', async () => { const res = await agent.post('/issues').type('form').send({ ...validIssue, building_id: '999' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/);}); test('the stored row has the cleaned values and ignores a client-sent status', async () => { await agent.post('/issues').type('form').send({ ...validIssue, title: ' Spaces around ', building_id: '20', status: 'closed' }); const { rows } = await pool.query("SELECT title, building_id, status FROM issues WHERE title = 'Spaces around'"); assert.deepEqual(rows, [{ title: 'Spaces around', building_id: 20, status: 'open' }]);}); test('an issue time in the future is rejected', async () => { const res = await agent.post('/issues').type('form').send({ ...validIssue, occurred_at: '2099-01-01T00:00' }); assert.equal(res.status, 400); assert.match(res.text, /That time is in the future/);}); test('GET /issues/101/edit shows the current values', async () => { const res = await agent.get('/issues/101/edit'); assert.equal(res.status, 200); assert.match(res.text, /value="2026-11-02T09:15"/); assert.match(res.text, /<option value="open" selected>open<\/option>/);}); test('POST /issues/:id/edit changes the status and updated_at', async () => { const before = (await pool.query('SELECT updated_at FROM issues WHERE id = 103')).rows[0].updated_at; const res = await agent.post('/issues/103/edit').type('form') .send({ title: 'Front door lock sticks at entrance 4', building_id: '20', priority: 'medium', status: 'investigating', occurred_at: '2026-11-08T07:05' }); assert.equal(res.status, 303); const { rows } = await pool.query('SELECT status, updated_at FROM issues WHERE id = 103'); assert.equal(rows[0].status, 'investigating'); assert.ok(rows[0].updated_at > before);}); test('POST /issues/:id/delete removes the issue', async () => { const created = await agent.post('/issues').type('form').send({ ...validIssue, title: 'Delete me please' }); const res = await agent.post(`${created.headers.location}/delete`); assert.equal(res.status, 303); assert.equal((await agent.get(created.headers.location)).status, 404);});test/organisations.test.js changed
test/organisations.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
let agent;
before(async () => {
await resetDatabase();
agent = await loginAs('carol');
});
after(() => pool.end());
test('GET /organisations lists organisations with building counts', async () => {
const res = await agent.get('/organisations');
assert.equal(res.status, 200);
assert.match(res.text, /Liffey Estates<\/a><\/td>\s*<td>2<\/td>/);
assert.match(res.text, /Harbour Lets/);
});
test('GET /organisations/1 shows its buildings, not other organisations\' buildings', async () => {
const res = await agent.get('/organisations/1');
assert.equal(res.status, 200);
assert.match(res.text, /Dublin Offices/);
assert.match(res.text, /Cork Apartments/);
assert.doesNotMatch(res.text, /Galway Studios/);
});
test('POST /organisations validates and creates', async () => {
const bad = await agent.post('/organisations').type('form').send({ name: ' ' });
assert.equal(bad.status, 400);
assert.match(bad.text, /Name must be between 2 and 100 characters/);
const good = await agent.post('/organisations').type('form').send({ name: 'Riverside Lettings' });
assert.equal(good.status, 303);
const page = await agent.get(good.headers.location);
assert.match(page.text, /<h1>Riverside Lettings<\/h1>/);
});
test('POST /organisations/:id/edit renames the organisation', async () => {
const res = await agent.post('/organisations/2/edit').type('form').send({ name: 'Harbour Lets Ltd' });
assert.equal(res.status, 303);
const page = await agent.get('/organisations/2');
assert.match(page.text, /<h1>Harbour Lets Ltd<\/h1>/);
});
test('unknown organisations are 404', async () => {
assert.equal((await agent.get('/organisations/999')).status, 404);
assert.equal((await agent.post('/organisations/999/edit').type('form').send({ name: 'Nope' })).status, 404);
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => { await resetDatabase(); agent = await loginAs('carol');});after(() => pool.end()); test('GET /organisations lists organisations with building counts', async () => { const res = await agent.get('/organisations'); assert.equal(res.status, 200); assert.match(res.text, /Liffey Estates<\/a><\/td>\s*<td>2<\/td>/); assert.match(res.text, /Harbour Lets/);}); test('GET /organisations/1 shows its buildings, not other organisations\' buildings', async () => { const res = await agent.get('/organisations/1'); assert.equal(res.status, 200); assert.match(res.text, /Dublin Offices/); assert.match(res.text, /Cork Apartments/); assert.doesNotMatch(res.text, /Galway Studios/);}); test('POST /organisations validates and creates', async () => { const bad = await agent.post('/organisations').type('form').send({ name: ' ' }); assert.equal(bad.status, 400); assert.match(bad.text, /Name must be between 2 and 100 characters/); const good = await agent.post('/organisations').type('form').send({ name: 'Riverside Lettings' }); assert.equal(good.status, 303); const page = await agent.get(good.headers.location); assert.match(page.text, /<h1>Riverside Lettings<\/h1>/);}); test('POST /organisations/:id/edit renames the organisation', async () => { const res = await agent.post('/organisations/2/edit').type('form').send({ name: 'Harbour Lets Ltd' }); assert.equal(res.status, 303); const page = await agent.get('/organisations/2'); assert.match(page.text, /<h1>Harbour Lets Ltd<\/h1>/);}); test('unknown organisations are 404', async () => { assert.equal((await agent.get('/organisations/999')).status, 404); assert.equal((await agent.post('/organisations/999/edit').type('form').send({ name: 'Nope' })).status, 404);});test/require-login.test.js added
test/require-login.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
before(resetDatabase);
after(() => pool.end());
function sessionId(res) {
const cookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('caretaker.sid='));
return cookie ? cookie.split(';')[0] : null;
}
test('anonymous requests are redirected to the login page', async () => {
for (const path of ['/', '/issues', '/issues/101', '/organisations', '/inspections/201', '/buildings/10']) {
const res = await request(app).get(path);
assert.equal(res.status, 303, path);
assert.equal(res.headers.location, '/login', path);
}
});
test('anonymous writes are refused and change nothing', async () => {
const res = await request(app).post('/issues/101/delete');
assert.equal(res.status, 303);
const { rowCount } = await pool.query('SELECT 1 FROM issues WHERE id = 101');
assert.equal(rowCount, 1);
});
test('login and register pages stay public', async () => {
assert.equal((await request(app).get('/login')).status, 200);
assert.equal((await request(app).get('/register')).status, 200);
assert.equal((await request(app).get('/css/style.css')).status, 200);
});
test('login issues a new session id (no session fixation)', async () => {
const agent = request.agent(app);
const first = await agent.get('/issues');
const before = sessionId(first);
assert.ok(before, 'a session exists before login');
const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' });
const afterLogin = sessionId(login);
assert.ok(afterLogin);
assert.notEqual(afterLogin, before);
assert.equal(login.headers.location, '/issues', 'returns to the page the user wanted');
});
test('returnTo only follows local paths', async () => {
const agent = request.agent(app);
await agent.get('//evil.test/phish');
const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' });
assert.equal(login.headers.location, '/');
});
test('new issues and transitions record the logged-in user', async () => {
const dave = await loginAs('dave');
const res = await dave.post('/issues').type('form').send({ title: 'Loose handrail on stairs', building_id: '20', priority: 'medium', occurred_at: '2026-11-21T08:00', reported_by: '1' });
const id = Number(res.headers.location.split('/').pop());
const { rows } = await pool.query('SELECT reported_by FROM issues WHERE id = $1', [id]);
assert.equal(rows[0].reported_by, 4, 'reported_by comes from the session, not the form');
await dave.post('/inspections/203/submit');
const history = await pool.query("SELECT changed_by FROM inspection_status_changes WHERE inspection_id = 203 AND to_status = 'submitted'");
assert.equal(history.rows[0].changed_by, 4);
});
test('the session cookie has the attributes we chose', async () => {
const res = await request(app).post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' });
const cookie = res.headers['set-cookie'].find((c) => c.startsWith('caretaker.sid='));
assert.match(cookie, /HttpOnly/);
assert.match(cookie, /SameSite=Lax/);
assert.match(cookie, /Expires=/);
assert.doesNotMatch(cookie, /Secure/, 'not Secure in tests: they use plain HTTP');
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; before(resetDatabase);after(() => pool.end()); function sessionId(res) { const cookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('caretaker.sid=')); return cookie ? cookie.split(';')[0] : null;} test('anonymous requests are redirected to the login page', async () => { for (const path of ['/', '/issues', '/issues/101', '/organisations', '/inspections/201', '/buildings/10']) { const res = await request(app).get(path); assert.equal(res.status, 303, path); assert.equal(res.headers.location, '/login', path); }}); test('anonymous writes are refused and change nothing', async () => { const res = await request(app).post('/issues/101/delete'); assert.equal(res.status, 303); const { rowCount } = await pool.query('SELECT 1 FROM issues WHERE id = 101'); assert.equal(rowCount, 1);}); test('login and register pages stay public', async () => { assert.equal((await request(app).get('/login')).status, 200); assert.equal((await request(app).get('/register')).status, 200); assert.equal((await request(app).get('/css/style.css')).status, 200);}); test('login issues a new session id (no session fixation)', async () => { const agent = request.agent(app); const first = await agent.get('/issues'); const before = sessionId(first); assert.ok(before, 'a session exists before login'); const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' }); const afterLogin = sessionId(login); assert.ok(afterLogin); assert.notEqual(afterLogin, before); assert.equal(login.headers.location, '/issues', 'returns to the page the user wanted');}); test('returnTo only follows local paths', async () => { const agent = request.agent(app); await agent.get('//evil.test/phish'); const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' }); assert.equal(login.headers.location, '/');}); test('new issues and transitions record the logged-in user', async () => { const dave = await loginAs('dave'); const res = await dave.post('/issues').type('form').send({ title: 'Loose handrail on stairs', building_id: '20', priority: 'medium', occurred_at: '2026-11-21T08:00', reported_by: '1' }); const id = Number(res.headers.location.split('/').pop()); const { rows } = await pool.query('SELECT reported_by FROM issues WHERE id = $1', [id]); assert.equal(rows[0].reported_by, 4, 'reported_by comes from the session, not the form'); await dave.post('/inspections/203/submit'); const history = await pool.query("SELECT changed_by FROM inspection_status_changes WHERE inspection_id = 203 AND to_status = 'submitted'"); assert.equal(history.rows[0].changed_by, 4);}); test('the session cookie has the attributes we chose', async () => { const res = await request(app).post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' }); const cookie = res.headers['set-cookie'].find((c) => c.startsWith('caretaker.sid=')); assert.match(cookie, /HttpOnly/); assert.match(cookie, /SameSite=Lax/); assert.match(cookie, /Expires=/); assert.doesNotMatch(cookie, /Secure/, 'not Secure in tests: they use plain HTTP');});views/inspections/show.ejs changed
views/inspections/show.ejs<%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/inspections">Inspections</a> / #<%= inspection.id %></p>
<div class="page-header">
<h1><%= inspection.title %></h1>
<div class="actions">
<% if (inspection.status === 'draft') { %>
<a class="btn" href="/inspections/<%= inspection.id %>/edit">Edit</a>
<form method="post" action="/inspections/<%= inspection.id %>/submit"><button type="submit" class="btn btn-primary">Submit for approval</button></form>
<% } %>
<% if (inspection.status === 'submitted') { %>
<form method="post" action="/inspections/<%= inspection.id %>/return"><button type="submit" class="btn">Return to draft</button></form>
<form method="post" action="/inspections/<%= inspection.id %>/approve" data-confirm="Approve this inspection? Approved inspections cannot be changed."><button type="submit" class="btn btn-primary">Approve</button></form>
<% } %>
</div>
</div>
<% if (error) { %>
<div class="flash flash-error" role="alert"><%= error %></div>
<% } %>
<dl class="details">
<dt>Building</dt><dd><a href="/buildings/<%= inspection.building_id %>"><%= inspection.building_name %></a></dd>
<dt>Status</dt><dd><span class="badge status-<%= inspection.status %>"><%= inspection.status %></span></dd>
<dt>Created by</dt><dd><%= inspection.created_by_name ?? 'unknown' %></dd>
<% if (inspection.submitted_at) { %><dt>Submitted</dt><dd><%= formatDate(inspection.submitted_at) %> UTC</dd><% } %>
<% if (inspection.approved_at) { %><dt>Approved</dt><dd><%= formatDate(inspection.approved_at) %> UTC</dd><% } %>
</dl>
<h2>Findings</h2>
<% if (inspection.findings) { %><p class="prose"><%= inspection.findings %></p><% } else { %><p class="empty">No findings recorded yet.</p><% } %>
<h2>History</h2>
<% if (history.length === 0) { %>
<p class="muted">No status changes yet.</p>
<% } else { %>
<table class="data">
<thead><tr><th>When (UTC)</th><th>Change</th><th>By</th></tr></thead>
<tbody>
<% for (const h of history) { %>
<tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td><td><%= h.changed_by_name ?? 'unknown' %></td></tr>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/inspections">Inspections</a> / #<%= inspection.id %></p><div class="page-header"> <h1><%= inspection.title %></h1> <div class="actions"> <% if (inspection.status === 'draft') { %> <a class="btn" href="/inspections/<%= inspection.id %>/edit">Edit</a> <form method="post" action="/inspections/<%= inspection.id %>/submit"><button type="submit" class="btn btn-primary">Submit for approval</button></form> <% } %> <% if (inspection.status === 'submitted') { %> <form method="post" action="/inspections/<%= inspection.id %>/return"><button type="submit" class="btn">Return to draft</button></form> <form method="post" action="/inspections/<%= inspection.id %>/approve" data-confirm="Approve this inspection? Approved inspections cannot be changed."><button type="submit" class="btn btn-primary">Approve</button></form> <% } %> </div></div><% if (error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %><dl class="details"> <dt>Building</dt><dd><a href="/buildings/<%= inspection.building_id %>"><%= inspection.building_name %></a></dd> <dt>Status</dt><dd><span class="badge status-<%= inspection.status %>"><%= inspection.status %></span></dd> <dt>Created by</dt><dd><%= inspection.created_by_name ?? 'unknown' %></dd> <% if (inspection.submitted_at) { %><dt>Submitted</dt><dd><%= formatDate(inspection.submitted_at) %> UTC</dd><% } %> <% if (inspection.approved_at) { %><dt>Approved</dt><dd><%= formatDate(inspection.approved_at) %> UTC</dd><% } %></dl><h2>Findings</h2><% if (inspection.findings) { %><p class="prose"><%= inspection.findings %></p><% } else { %><p class="empty">No findings recorded yet.</p><% } %><h2>History</h2><% if (history.length === 0) { %> <p class="muted">No status changes yet.</p><% } else { %> <table class="data"> <thead><tr><th>When (UTC)</th><th>Change</th><th>By</th></tr></thead> <tbody> <% for (const h of history) { %> <tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td><td><%= h.changed_by_name ?? 'unknown' %></td></tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %>views/issues/show.ejs changed
views/issues/show.ejs<%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p>
<div class="page-header">
<h1><%= issue.title %></h1>
<div class="actions">
<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.">
<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"> <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."> <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') %>views/partials/head.ejs changed
views/partials/head.ejs<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><%= title %> · Caretaker</title>
<link rel="stylesheet" href="/css/style.css">
<script src="/js/app.js" defer></script>
</head>
<body>
<%- include('nav') %>
<main class="container">
<% if (flash) { %>
<div class="flash flash-<%= flash.type %>" role="status"><%= flash.message %></div>
<% } %>
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><%= title %> · Caretaker</title> <link rel="stylesheet" href="/css/style.css"> <script src="/js/app.js" defer></script></head><body><%- include('nav') %><main class="container"><% if (flash) { %> <div class="flash flash-<%= flash.type %>" role="status"><%= flash.message %></div><% } %>Project tree at this checkpoint
.env.example
.env.test
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
migrations/002_create_inspections.sql
migrations/003_create_users.sql
migrations/004_create_session_table.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/migrate.js
scripts/seed.js
src/app.js
src/config.js
src/db.js
src/lib/ids.js
src/lib/validation.js
src/middleware/auth.js
src/middleware/flash.js
src/migrate.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/organisations.js
src/models/users.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/auth.test.js
test/buildings.test.js
test/dashboard.test.js
test/helpers.js
test/inspections.test.js
test/issue-list.test.js
test/issues.test.js
test/organisations.test.js
test/require-login.test.js
views/auth/login.ejs
views/auth/register.ejs
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.ejs
views/issues/form.ejs
views/issues/index.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs