Module 4 · Authentication and user management
4.3 Require login, and keep sessions safe
Deny anonymous access by default, add one-time flash messages, fix session fixation by regenerating the session at login, set cookie attributes deliberately, and record who did what from the trusted identity.
Starting point
Users can register, log in and log out, and req.user is loaded from the session. But every page still works without logging in.
Outcome
- Every page except
/login,/registerand static files requires a login. Anonymous visitors are redirected to the login page, and back to where they were going afterwards. - One-time "flash" messages appear on the next page.
- Logging in issues a new session ID.
- The session cookie is
HttpOnly,SameSite=Lax, expires after 8 hours, and can be markedSecurewith one setting. - New issues record
reported_by, new inspectionscreated_by, and each transitionchanged_by, fromreq.user. - All existing tests log in first, through a
loginAshelper.
The problem
Three separate problems, each with a demonstration.
1. Everything is public. Without a cookie, anyone can delete an issue:
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000
curl -si -X POST http://localhost:3000/issues/130/delete | head -1
HTTP/1.1 303 See Other
That issue is gone. (Re-seeding restores it; we do that below.)
2. Who reported this? Issues now have a reported_by column, but nothing fills it. The creating route does not know who the user is.
3. Session fixation. This one is subtle; we demonstrate it after adding login-required redirects, because it needs a session that exists before login.
Build it
1. Flash messages
A flash message is stored in the session by one request and shown, then deleted, by the next. Create 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();}Show it at the top of every page:
<main class="container"><% if (flash) { %> <div class="flash flash-<%= flash.type %>" role="status"><%= flash.message %></div><% } %>
Show the whole views/partials/head.ejs after this change
<!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>
<% } %>
2. Require a login, by default
Add requireLogin to src/middleware/auth.js:
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');}
Show the whole src/middleware/auth.js after this change
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');}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');
}
Now the important part: where it goes in src/app.js. Public routes come before it; everything after it is protected without having to remember a check on each route:
import { loadUser } from './middleware/auth.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';
app.locals.currentUser = null;app.locals.flash = null;
app.use(loadUser);app.use(flash); app.use(authRouter);app.use(requireLogin);
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { 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,}));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,
}));
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 });
});
This is deny by default. When a later lesson adds a new router below this line, it is protected automatically. The opposite design (each route opts in to a check) fails open: one forgotten check and a page is public.
3. Regenerate the session at login, and go back where the user was going
Replace the two places that set req.session.userId in src/routes/auth.js, and add the helper they use:
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 : '/';}
req.session.userId = user.id; await startSession(req, user.id); req.flash('success', `Welcome to Caretaker, ${user.name}.`); res.redirect(303, '/');}); authRouter.get('/login', (req, res) => {
req.session.userId = user.id; res.redirect(303, '/'); const returnTo = safeReturnTo(req.session.returnTo); await startSession(req, user.id); res.redirect(303, returnTo);});
Show the whole src/routes/auth.js after this change
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'); });});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');
});
});
req.session.regeneratedeletes the old session row and creates a new one with a new random ID, thensavewrites it before we redirect.- We read
returnTobefore regenerating, because regeneration throws the old session's data away. safeReturnToprevents an open redirect: without it, a link to our login page could send users to another site after they log in.
4. Deliberate cookie settings
Add a setting for HTTPS-only cookies to src/config.js:
sessionSecret: required('SESSION_SECRET'), // Set COOKIE_SECURE=1 when the app is served over HTTPS (always, in production). cookieSecure: process.env.COOKIE_SECURE === '1',
Show the whole src/config.js after this change
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',};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',
};
And spell out the cookie options in src/app.js:
resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax', secure: config.cookieSecure, maxAge: 8 * 60 * 60 * 1000, },}));
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { 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 });
});
| Attribute | What it does | Why we want it |
|---|---|---|
HttpOnly |
JavaScript in the page cannot read the cookie | An XSS bug cannot steal the session ID |
SameSite=Lax |
The browser does not send the cookie on cross-site POSTs or embedded requests, only on top-level navigation |
Blocks most cross-site request forgery (lesson 4.4 adds a token anyway) |
Secure |
The cookie is only sent over HTTPS | Nobody on the network can read it. Off locally, because localhost uses plain HTTP |
Max-Age |
The browser drops the cookie after 8 hours; the store expires the row too | A forgotten session on a shared computer does not live forever |
5. Record who did what, from the session
The identity in req.user came from the server-side session, so we can trust it. A reported_by field in a form could say anything. Update the models to accept the user:
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.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`;
export async function createIssue({ building_id, title, description, priority, occurred_at }) {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) VALUES ($1, $2, $3, $4, $5) `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], [building_id, title, description, priority, occurred_at, reportedBy], );
Show the whole src/models/issues.js after this change
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;}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;
}
a.id, a.building_id, s.name AS building_name, s.organisation_id, a.title, a.findings, a.status, 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,
'SELECT from_status, to_status, changed_at FROM inspection_status_changes WHERE inspection_id = $1 ORDER BY changed_at, id', `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`,
export async function createInspection({ building_id, title, findings }) {export async function createInspection({ building_id, title, findings }, createdBy) { const { rows } = await query( 'INSERT INTO inspections (building_id, title, findings) VALUES ($1, $2, $3) RETURNING id', [building_id, title, findings], 'INSERT INTO inspections (building_id, title, findings, created_by) VALUES ($1, $2, $3, $4) RETURNING id', [building_id, title, findings, createdBy], );
export async function transitionInspection(id, action) {export async function transitionInspection(id, action, changedBy) {
'INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, $2, $3)', [id, transition.from, transition.to], 'INSERT INTO inspection_status_changes (inspection_id, from_status, to_status, changed_by) VALUES ($1, $2, $3, $4)', [id, transition.from, transition.to, changedBy],
Show the whole src/models/inspections.js after this change
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; });}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;
});
}
The user is a separate argument, not a property of the validated form values. That makes it impossible for a form field to supply it by accident. Pass req.user.id from the routes:
created = await createIssue(record); created = await createIssue(record, req.user.id);
Show the whole src/routes/issues.js after this change
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.js';import { listBuildings } 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');
});
const created = await createInspection(values); const created = await createInspection(values, req.user.id);
const changed = await transitionInspection(inspection.id, req.params.action); const changed = await transitionInspection(inspection.id, req.params.action, req.user.id);
Show the whole src/routes/inspections.js after this change
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}`);});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}`);
});
Show the names on the pages:
<dt>Reported by</dt><dd><%= issue.reported_by_name ?? 'unknown' %></dd> <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd>
Show the whole views/issues/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header"> <h1><%= issue.title %></h1> <div class="actions"> <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') %>
<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>
<thead><tr><th>When (UTC)</th><th>Change</th></tr></thead> <thead><tr><th>When (UTC)</th><th>Change</th><th>By</th></tr></thead>
<tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td></tr> <tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td><td><%= h.changed_by_name ?? 'unknown' %></td></tr>
Show the whole views/inspections/show.ejs after this change
<%- 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') %>
6. Tests log in first
Every existing test now gets 303 See Other to /login. Add a login helper to test/helpers.js:
import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';
import { seed } from '../src/seed.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;}
Show the whole test/helpers.js after this change
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(); }}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();
}
}
The same mechanical change applies to six test files: create a logged-in agent before the tests, and send every request through it instead of request(app). Rather than make 80 identical edits by hand, run this small Node script once. It edits the six files in place:
node -e "
const fs = require('node:fs');
for (const file of ['issues', 'issue-list', 'organisations', 'buildings', 'inspections', 'dashboard']) {
const path = 'test/' + file + '.test.js';
let text = fs.readFileSync(path, 'utf8');
text = text.replace(\"import { resetDatabase } from './helpers.js';\", \"import { resetDatabase, loginAs } from './helpers.js';\");
text = text.replace('before(resetDatabase);', 'let agent;\nbefore(async () => {\n await resetDatabase();\n agent = await loginAs(\'carol\');\n});');
text = text.replaceAll('request(app)', 'agent');
fs.writeFileSync(path, text);
}
"
Open test/issues.test.js and read the top: agent is created once per file, logged in as Carol, and every request uses it. We pick Carol for now because, so far, any logged-in user can do anything. Module 5 changes that, and these tests will start asking which user does what.
Add tests for the new behaviour:
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');});Run and inspect
Run the whole suite before going further:
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✖ a correct login creates a session and shows the user (209.534ms)
✔ a wrong password or unknown email gets the same 401 and no session (48.784208ms)
✔ registration validates, creates a user, and logs them in (60.697083ms)
✔ registering an existing email is a field error (25.266833ms)
✖ logout destroys the session (41.54425ms)
✔ a building can be created inside an organisation (238.125667ms)
✔ a duplicate building name in the same organisation is a field error (10.582166ms)
✔ the same building name is allowed in another organisation (4.770417ms)
✔ a building with issues cannot be deleted (26.436917ms)
✔ an empty building can be deleted (11.790292ms)
✔ an organisation with buildings cannot be deleted, an empty one can (17.635209ms)
✔ the dashboard counts match the database (244.132792ms)
✔ every building appears with its organisation (6.48325ms)
✔ create a draft, edit it, submit it, approve it (251.1685ms)
✔ invalid transitions are refused with 409 and change nothing (9.356834ms)
✔ only drafts can be edited (5.29425ms)
✔ returning a submitted inspection makes it editable again (6.520334ms)
✔ concurrent approvals: exactly one wins (20.907875ms)
✔ unknown actions are 404 (2.649542ms)
✔ the list pages 10 at a time and reports the total (245.736875ms)
✔ pages do not overlap (15.336917ms)
✔ filters combine with AND (5.83425ms)
✔ sorting by priority puts critical first when descending (5.294667ms)
✔ unknown sort keys and SQL in the query string are ignored (23.871584ms)
✔ GET /issues lists issues from the database (235.748875ms)
✔ GET /issues/101 shows one issue with its building (3.947458ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (9.839792ms)
✔ POST /issues re-renders the form with errors (3.353583ms)
✔ POST /issues stores the issue and redirects to it (9.549084ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (10.773958ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.012584ms)
✔ an issue time in the future is rejected (2.8965ms)
✔ GET /issues/101/edit shows the current values (3.263334ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.494208ms)
✔ POST /issues/:id/delete removes the issue (7.901708ms)
✔ GET /organisations lists organisations with building counts (227.815959ms)
Show 57 more lines
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.998583ms)
✔ POST /organisations validates and creates (9.277625ms)
✔ POST /organisations/:id/edit renames the organisation (6.357458ms)
✔ unknown organisations are 404 (6.028041ms)
✔ anonymous requests are redirected to the login page (199.507625ms)
✔ anonymous writes are refused and change nothing (2.259833ms)
✔ login and register pages stay public (7.814ms)
✔ login issues a new session id (no session fixation) (61.190125ms)
✔ returnTo only follows local paths (26.992667ms)
✔ new issues and transitions record the logged-in user (32.043791ms)
✔ the session cookie has the attributes we chose (27.575125ms)
ℹ tests 47
ℹ suites 0
ℹ pass 45
ℹ fail 2
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3482.433958
✖ failing tests:
test at test/auth.test.js:11:1
✖ a correct login creates a session and shows the user (209.534ms)
AssertionError [ERR_ASSERTION]: The input did not match the regular expression /^caretaker\.sid=s%3A.+; Path=\/; HttpOnly/. Input:
'caretaker.sid=s%3ACBacw2fMf2-nZTa1BDxp0Id_M_oQedZu.EinaR7BJ17MYudYTfkHDouhJnnhlgrxh72Tp7y4dPWM; Path=/; Expires=Sat, 28 Nov 2026 22:41:01 GMT; HttpOnly; SameSite=Lax'
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/auth.test.js:15:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async startSubtestAfterBootstrap (node:internal/test_runner/harness:296:3) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 'caretaker.sid=s%3ACBacw2fMf2-nZTa1BDxp0Id_M_oQedZu.EinaR7BJ17MYudYTfkHDouhJnnhlgrxh72Tp7y4dPWM; Path=/; Expires=Sat, 28 Nov 2026 22:41:01 GMT; HttpOnly; SameSite=Lax',
expected: /^caretaker\.sid=s%3A.+; Path=\/; HttpOnly/,
operator: 'match',
diff: 'simple'
}
test at test/auth.test.js:49:1
✖ logout destroys the session (41.54425ms)
AssertionError [ERR_ASSERTION]: The input did not match the regular expression /Log in<\/a>/. Input:
'See Other. Redirecting to /login'
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/auth.test.js:53:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 'See Other. Redirecting to /login',
expected: /Log in<\/a>/,
operator: 'match',
diff: 'simple'
}
Two tests in test/auth.test.js fail, and both failures are correct: they describe the old behaviour. The cookie now carries Expires and SameSite, and after logout the home page redirects to /login instead of rendering a "Log in" link. When a test fails after an intended change, update the test to state the new intent; do not weaken it until it passes.
assert.match(res.headers['set-cookie'][0], /^caretaker\.sid=s%3A.+; Path=\/; HttpOnly/); assert.match(res.headers['set-cookie'][0], /^caretaker\.sid=s%3A.+; Path=\/; Expires=.+; HttpOnly; SameSite=Lax$/);
await agent.post('/logout'); assert.match((await agent.get('/')).text, /Log in<\/a>/); const home = await agent.get('/'); assert.equal(home.status, 303); assert.equal(home.headers.location, '/login');
Show the whole test/auth.test.js after this change
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');});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');
});
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ a correct login creates a session and shows the user (228.819125ms)
✔ a wrong password or unknown email gets the same 401 and no session (45.627416ms)
✔ registration validates, creates a user, and logs them in (38.634792ms)
✔ registering an existing email is a field error (24.597708ms)
✔ logout destroys the session (35.587ms)
✔ a building can be created inside an organisation (236.343833ms)
✔ a duplicate building name in the same organisation is a field error (9.678625ms)
✔ the same building name is allowed in another organisation (4.109833ms)
✔ a building with issues cannot be deleted (24.160208ms)
✔ an empty building can be deleted (10.368792ms)
✔ an organisation with buildings cannot be deleted, an empty one can (17.744958ms)
✔ the dashboard counts match the database (246.661625ms)
✔ every building appears with its organisation (7.26075ms)
✔ create a draft, edit it, submit it, approve it (252.001041ms)
✔ invalid transitions are refused with 409 and change nothing (11.097625ms)
✔ only drafts can be edited (5.588167ms)
✔ returning a submitted inspection makes it editable again (7.316458ms)
✔ concurrent approvals: exactly one wins (21.420125ms)
✔ unknown actions are 404 (2.57575ms)
✔ the list pages 10 at a time and reports the total (245.589208ms)
✔ pages do not overlap (11.077958ms)
✔ filters combine with AND (4.143791ms)
✔ sorting by priority puts critical first when descending (5.0685ms)
✔ unknown sort keys and SQL in the query string are ignored (33.576125ms)
✔ GET /issues lists issues from the database (245.185583ms)
✔ GET /issues/101 shows one issue with its building (4.956459ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (10.575666ms)
✔ POST /issues re-renders the form with errors (3.802375ms)
✔ POST /issues stores the issue and redirects to it (7.455709ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (11.003958ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.96175ms)
✔ an issue time in the future is rejected (2.733542ms)
✔ GET /issues/101/edit shows the current values (3.423584ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.292209ms)
✔ POST /issues/:id/delete removes the issue (7.671291ms)
✔ GET /organisations lists organisations with building counts (228.049041ms)
Show 19 more lines
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.963833ms)
✔ POST /organisations validates and creates (8.992458ms)
✔ POST /organisations/:id/edit renames the organisation (6.095ms)
✔ unknown organisations are 404 (5.666ms)
✔ anonymous requests are redirected to the login page (204.070125ms)
✔ anonymous writes are refused and change nothing (2.567875ms)
✔ login and register pages stay public (8.350875ms)
✔ login issues a new session id (no session fixation) (30.725667ms)
✔ returnTo only follows local paths (27.395541ms)
✔ new issues and transitions record the logged-in user (39.0335ms)
✔ the session cookie has the attributes we chose (25.411875ms)
ℹ tests 47
ℹ suites 0
ℹ pass 47
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3496.718625
Re-seed your development database, which lost issue 130 at the start of the lesson:
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000
An anonymous request is now redirected, and gets a session cookie that carries the flash message:
curl -si http://localhost:3000/issues | grep -E "HTTP/|Location|Set-Cookie"
HTTP/1.1 303 See Other
Location: /login
Set-Cookie: caretaker.sid=s%3AC8bZmcFR1yFrK4cPkP0iTBD3QECgb5wy.nMJv95Ki5byRWvJVDsXgGaafCHA1vqE%2FGDSAtTD6Adk; Path=/; Expires=Sat, 28 Nov 2026 22:41:09 GMT; HttpOnly; SameSite=Lax

Session fixation, demonstrated and fixed
Here is the attack our regenerate call prevents. An attacker visits the site and receives a session cookie. They then get that cookie into the victim's browser (for example through a vulnerable subdomain that can set cookies for the parent domain). The victim logs in with the attacker's session ID. If the server keeps the same ID after login, the attacker's copy of the cookie is now logged in as the victim.
Simulate it with two cookie jars. The "attacker" gets a session first:
rm -f /tmp/attacker.txt && curl -si -c /tmp/attacker.txt http://localhost:3000/issues | grep -E "HTTP/|Location"
HTTP/1.1 303 See Other
Location: /login
The "victim" logs in using a copy of that same cookie:
cp /tmp/attacker.txt /tmp/victim.txt && curl -si -b /tmp/victim.txt -c /tmp/victim.txt http://localhost:3000/login -d email=alice@example.test -d password=password123 | head -1
HTTP/1.1 303 See Other
Compare the session IDs in the two jars, then use the attacker's jar:
awk '$6 == "caretaker.sid" { print FILENAME ": " substr($7, 1, 20) "…" }' /tmp/attacker.txt /tmp/victim.txt
/tmp/attacker.txt: s%3AJP6JxpAidjIaN9n4…
/tmp/victim.txt: s%3AOfL6SOozZXaa7eFU…
curl -si -b /tmp/attacker.txt http://localhost:3000/ | grep -E "HTTP/|Location"
HTTP/1.1 303 See Other
Location: /login
The attacker's cookie is sent to the login page like any anonymous visitor's. The victim's browser received a new session ID at login, and the attacker's ID now points to a session that was deleted by regenerate. Comment out the startSession line and set req.session.userId = user.id; instead, repeat the three commands, and you will see the attacker's jar get 200 OK for /: logged in as Alice. Then restore the code.
Experiment
Our routes now record req.user.id as the reporter. Try to claim someone else's identity through the form.
reported_by=1 (Alice). Who is recorded as the reporter?Reveal Answer
Dave. The test "new issues and transitions record the logged-in user" does exactly this and checks the database. The form value never reaches createIssue: validation ignores unknown fields, and the reporter is a separate argument filled from the session. This is the first appearance of a rule we will repeat in every module from now on: identity and authorization data come from the server, never from the request.
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ a correct login creates a session and shows the user (248.241125ms)
✔ a wrong password or unknown email gets the same 401 and no session (45.164959ms)
✔ registration validates, creates a user, and logs them in (41.264708ms)
✔ registering an existing email is a field error (24.418834ms)
✔ logout destroys the session (37.568542ms)
✔ a building can be created inside an organisation (235.608333ms)
✔ a duplicate building name in the same organisation is a field error (9.675584ms)
✔ the same building name is allowed in another organisation (4.240375ms)
✔ a building with issues cannot be deleted (26.871833ms)
✔ an empty building can be deleted (10.454333ms)
✔ an organisation with buildings cannot be deleted, an empty one can (18.70625ms)
✔ the dashboard counts match the database (256.359125ms)
✔ every building appears with its organisation (6.900958ms)
✔ create a draft, edit it, submit it, approve it (256.442625ms)
✔ invalid transitions are refused with 409 and change nothing (8.830709ms)
✔ only drafts can be edited (4.880334ms)
✔ returning a submitted inspection makes it editable again (6.065292ms)
✔ concurrent approvals: exactly one wins (21.281792ms)
✔ unknown actions are 404 (2.316ms)
✔ the list pages 10 at a time and reports the total (249.861042ms)
✔ pages do not overlap (13.243917ms)
✔ filters combine with AND (4.753042ms)
✔ sorting by priority puts critical first when descending (5.705042ms)
✔ unknown sort keys and SQL in the query string are ignored (23.634916ms)
✔ GET /issues lists issues from the database (249.032417ms)
✔ GET /issues/101 shows one issue with its building (4.139167ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (10.81725ms)
✔ POST /issues re-renders the form with errors (3.374708ms)
✔ POST /issues stores the issue and redirects to it (8.3375ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (10.873708ms)
✔ the stored row has the cleaned values and ignores a client-sent status (6.280458ms)
✔ an issue time in the future is rejected (3.999167ms)
✔ GET /issues/101/edit shows the current values (4.634875ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.18375ms)
✔ POST /issues/:id/delete removes the issue (7.959792ms)
✔ GET /organisations lists organisations with building counts (232.083ms)
Show 19 more lines
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.331416ms)
✔ POST /organisations validates and creates (10.761875ms)
✔ POST /organisations/:id/edit renames the organisation (6.59675ms)
✔ unknown organisations are 404 (6.285208ms)
✔ anonymous requests are redirected to the login page (205.130459ms)
✔ anonymous writes are refused and change nothing (2.126916ms)
✔ login and register pages stay public (8.1755ms)
✔ login issues a new session id (no session fixation) (30.605042ms)
✔ returnTo only follows local paths (27.383625ms)
✔ new issues and transitions record the logged-in user (40.830167ms)
✔ the session cookie has the attributes we chose (28.911708ms)
ℹ tests 47
ℹ suites 0
ℹ pass 47
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3542.956375
git add -A
git commit -m "Require login, flash messages, session fixation fix, cookie settings"
[main bfd3b10] Require login, flash messages, session fixation fix, cookie settings
21 files changed, 267 insertions(+), 94 deletions(-)
create mode 100644 src/middleware/flash.js
create mode 100644 test/require-login.test.js
Symptom Login works but you land on / instead of the page you wanted
returnTo was read after regenerate, which discarded it. Read it first, as shown.
Symptom TypeError: req.flash is not a function
The flash middleware is registered after a route that uses it. It must come right after loadUser, before authRouter.
Symptom Tests fail with Login as carol failed with status 401
The test database was not re-seeded with users. resetDatabase must run before loginAs, as in the before hook the script created.
Recap and next step
Protection is now the default: one requireLogin line protects every router mounted after it. Login regenerates the session to defeat fixation. Cookie attributes are explicit. The application records who did what, using only the identity from the session, and the tests prove that a form field cannot override it.
Two gaps remain in authentication itself: other websites can still make a logged-in browser submit our forms, and nothing limits password guessing. The next lesson closes both, and then shows that "logged in" is very different from "allowed".
Open the checkpoint files for lesson 4.3 (separate page; only files from this lesson and earlier)