Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 4.4

CSRF tokens, login throttling, and "logged in" is not "allowed": checkpoint files

Git tag in the reference repository
lesson/m04-l04 (commit 2510736)
Replay result
All steps replayed from an empty folder
Tests at this point
pass (tests 52, pass 52, fail 0)

Compare your folder with the reference using Git, if you cloned it: git diff lesson/m04-l04 -- src.

Files changed in this lesson

.env.test changed

.env.test
# Settings for automated tests. Local learning values only; safe to commit.NODE_ENV=testDATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_testPORT=3001LOG_SQL=0SESSION_SECRET=test-only-secret-never-use-this-anywhere-realLOGIN_RATE_LIMIT=5

package-lock.json changed

Generated by npm from package.json. Do not edit it by hand; run the npm commands from the lesson.

package.json changed

package.json
{  "name": "caretaker",  "version": "1.0.0",  "description": "",  "scripts": {    "test": "node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec \"test/**/*.test.js\"",    "start": "node --env-file=.env src/server.js",    "dev": "node --env-file=.env --watch src/server.js",    "db:migrate": "node --env-file=.env scripts/migrate.js",    "db:seed": "node --env-file=.env scripts/seed.js"  },  "keywords": [],  "author": "",  "license": "ISC",  "type": "module",  "dependencies": {    "argon2": "0.45.2",    "connect-pg-simple": "10.0.0",    "ejs": "7.0.2",    "express": "5.3.0",    "express-rate-limit": "8.7.4",    "express-session": "1.19.0",    "pg": "8.23.1"  },  "devDependencies": {    "supertest": "7.3.2"  }}

src/app.js changed

src/app.js
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 { csrf } from './middleware/csrf.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;app.locals.csrfToken = ''; const PgSession = connectPgSimple(session); app.use((req, res, next) => {  if (process.env.NODE_ENV === 'test') {    return next();  }  const started = Date.now();  res.on('finish', () => {    console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false }));app.use(session({  store: new PgSession({ pool, tableName: 'session', pruneSessionInterval: config.env === 'test' ? false : 900 }),  name: 'caretaker.sid',  secret: config.sessionSecret,  resave: false,  saveUninitialized: false,  cookie: {    httpOnly: true,    sameSite: 'lax',    secure: config.cookieSecure,    maxAge: 8 * 60 * 60 * 1000,  },}));app.use(loadUser);app.use(flash);app.use(csrf); app.use(authRouter);app.use(requireLogin); app.get('/', async (req, res) => {  res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });}); app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); app.use((req, res) => {  res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);  }  const message = err.expose ? err.message : 'Something went wrong';  res.status(status).render('error', { title: 'Error', status, message });});

src/config.js changed

src/config.js
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',  loginRateLimit: Number(process.env.LOGIN_RATE_LIMIT ?? 10),};

src/middleware/csrf.js added

src/middleware/csrf.js
import crypto from 'node:crypto'; const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']); function tokensMatch(sent, expected) {  if (typeof sent !== 'string' || sent.length !== expected.length) {    return false;  }  return crypto.timingSafeEqual(Buffer.from(sent), Buffer.from(expected));} // Synchronizer token: one random token per session, required on every unsafe request.export function csrf(req, res, next) {  if (!req.session.csrfToken) {    req.session.csrfToken = crypto.randomBytes(32).toString('base64url');  }  res.locals.csrfToken = req.session.csrfToken;  if (SAFE_METHODS.has(req.method)) {    return next();  }  const sent = req.body?._csrf ?? req.get('x-csrf-token');  if (!tokensMatch(sent, req.session.csrfToken)) {    const err = new Error('This form has expired or did not come from Caretaker. Go back, reload the page and try again.');    err.status = 403;    err.expose = true;    return next(err);  }  next();}

src/middleware/rate-limit.js added

src/middleware/rate-limit.js
import { rateLimit } from 'express-rate-limit';import { config } from '../config.js'; // At most config.loginRateLimit failed attempts per client IP in 15 minutes.export const loginLimiter = rateLimit({  windowMs: 15 * 60 * 1000,  limit: config.loginRateLimit,  skipSuccessfulRequests: true,  standardHeaders: 'draft-8',  legacyHeaders: false,  handler: (req, res) => {    res.status(429).render('auth/login', {      title: 'Log in',      email: '',      error: 'Too many failed attempts. Wait 15 minutes, then try again.',    });  },});

src/routes/auth.js changed

src/routes/auth.js
import express from 'express';import { createUser, verifyCredentials, normaliseEmail } from '../models/users.js';import { PG_ERRORS } from '../db.js';import { cleanText } from '../lib/validation.js';import { loginLimiter } from '../middleware/rate-limit.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', loginLimiter, 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', loginLimiter, 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');  });});

test/auth.test.js changed

test/auth.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, anonymousAgent } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('a correct login creates a session and shows the user', async () => {  const agent = await anonymousAgent();  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', async () => {  for (const email of ['alice@example.test', 'mallory@example.test']) {    const agent = await anonymousAgent();    const res = await agent.post('/login').type('form').send({ email, password: 'wrong-password' });    assert.equal(res.status, 401);    assert.match(res.text, /Email or password is incorrect/);  }}); test('registration validates, creates a user, and logs them in', async () => {  const agent = await anonymousAgent();  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 agent = await anonymousAgent();  const res = await agent.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 = await anonymousAgent();  await agent.post('/login').type('form').send({ email: 'bob@example.test', password: 'password123' });  const home = await agent.get('/');  agent.set('X-CSRF-Token', home.text.match(/<meta name="csrf-token" content="([^"]+)">/)[1]);  await agent.post('/logout');  const after = await agent.get('/');  assert.equal(after.status, 303);  assert.equal(after.headers.location, '/login');});

test/csrf.test.js added

test/csrf.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let alice;before(async () => {  await resetDatabase();  alice = await loginAs('alice');});after(() => pool.end()); test('a logged-in POST without a token is refused with 403', async () => {  const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', '');  assert.equal(res.status, 403);  assert.match(res.text, /did not come from Caretaker/);  assert.equal((await pool.query('SELECT 1 FROM issues WHERE id = 130')).rowCount, 1);}); test('a token from another session is refused', async () => {  const bob = await loginAs('bob');  const bobToken = bob._defaults.find((d) => d.fn === 'set' && d.args[0] === 'X-CSRF-Token').args[1];  const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', bobToken);  assert.equal(res.status, 403);}); test('the right token in the form field works', async () => {  const page = await alice.get('/issues/130');  const token = page.text.match(/name="_csrf" value="([^"]+)"/)[1];  const res = await alice.post('/issues/130/delete').set('X-CSRF-Token', '').type('form').send({ _csrf: token });  assert.equal(res.status, 303);}); test('every POST form on every page carries the token', async () => {  const pages = ['/', '/issues/new', '/issues/101', '/issues/101/edit', '/organisations/1', '/organisations/new', '/buildings/10', '/buildings/10/edit', '/inspections/new', '/inspections/201', '/inspections/203'];  for (const path of pages) {    const html = (await alice.get(path)).text;    const forms = (html.match(/<form method="post"/g) ?? []).length;    const tokens = (html.match(/<form method="post"[^>]*><input type="hidden" name="_csrf" value="[^"]+">/g) ?? []).length;    assert.ok(forms > 0, `${path} has a POST form`);    assert.equal(tokens, forms, `${path}: every POST form has a token`);  }});

test/helpers.js changed

test/helpers.js
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'; export function csrfTokenFrom(html) {  const match = html.match(/<meta name="csrf-token" content="([^"]+)">/);  if (!match) {    throw new Error('No CSRF token on the page');  }  return match[1];} // An agent that has visited the login page and sends its CSRF token on every request.export async function anonymousAgent() {  const agent = request.agent(app);  const page = await agent.get('/login');  agent.set('X-CSRF-Token', csrfTokenFrom(page.text));  return agent;} // 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 = await anonymousAgent();  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}`);  }  // Login regenerated the session, so the token changed. Read the new one.  const home = await agent.get('/');  agent.set('X-CSRF-Token', csrfTokenFrom(home.text));  return agent;} export async function resetDatabase() {  if (!config.databaseUrl.endsWith('/caretaker_test')) {    throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`);  }  await migrate(config.databaseUrl, { log: () => {} });  const client = await pool.connect();  try {    await seed(client);  } finally {    client.release();  }}

test/rate-limit.test.js added

test/rate-limit.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, anonymousAgent } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('failed logins are limited per client; the limit then blocks even correct passwords', async () => {  const agent = await anonymousAgent();  for (let i = 1; i <= 5; i++) {    const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: `guess-${i}` });    assert.equal(res.status, 401, `attempt ${i}`);  }  const blocked = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'guess-6' });  assert.equal(blocked.status, 429);  assert.match(blocked.headers.ratelimit, /r=0/, 'no requests remaining');  const correct = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' });  assert.equal(correct.status, 429);});

test/require-login.test.js changed

test/require-login.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs, anonymousAgent, csrfTokenFrom } from './helpers.js'; before(resetDatabase);after(() => pool.end()); function sessionId(res) {  const cookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('caretaker.sid='));  return cookie ? cookie.split(';')[0] : null;} test('anonymous requests are redirected to the login page', async () => {  for (const path of ['/', '/issues', '/issues/101', '/organisations', '/inspections/201', '/buildings/10']) {    const res = await request(app).get(path);    assert.equal(res.status, 303, path);    assert.equal(res.headers.location, '/login', path);  }}); test('anonymous writes are refused and change nothing', async () => {  const withoutToken = await request(app).post('/issues/101/delete');  assert.equal(withoutToken.status, 403);  const agent = await anonymousAgent();  const withToken = await agent.post('/issues/101/delete');  assert.equal(withToken.status, 303);  assert.equal(withToken.headers.location, '/login');  const { rowCount } = await pool.query('SELECT 1 FROM issues WHERE id = 101');  assert.equal(rowCount, 1);}); test('login and register pages stay public', async () => {  assert.equal((await request(app).get('/login')).status, 200);  assert.equal((await request(app).get('/register')).status, 200);  assert.equal((await request(app).get('/css/style.css')).status, 200);}); test('login issues a new session id (no session fixation)', async () => {  const agent = request.agent(app);  await agent.get('/issues');  const page = await agent.get('/login');  const before = sessionId(page) ?? 'cookie set by the first request';  const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) });  const afterLogin = sessionId(login);  assert.ok(afterLogin);  assert.notEqual(afterLogin, before);  assert.equal(login.headers.location, '/issues', 'returns to the page the user wanted');}); test('returnTo only follows local paths', async () => {  const agent = request.agent(app);  await agent.get('//evil.test/phish');  const page = await agent.get('/login');  const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) });  assert.equal(login.headers.location, '/');}); test('new issues and transitions record the logged-in user', async () => {  const dave = await loginAs('dave');  const res = await dave.post('/issues').type('form').send({ title: 'Loose handrail on stairs', building_id: '20', priority: 'medium', occurred_at: '2026-11-21T08:00', reported_by: '1' });  const id = Number(res.headers.location.split('/').pop());  const { rows } = await pool.query('SELECT reported_by FROM issues WHERE id = $1', [id]);  assert.equal(rows[0].reported_by, 4, 'reported_by comes from the session, not the form');   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 agent = await anonymousAgent();  const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' });  const cookie = res.headers['set-cookie'].find((c) => c.startsWith('caretaker.sid='));  assert.match(cookie, /HttpOnly/);  assert.match(cookie, /SameSite=Lax/);  assert.match(cookie, /Expires=/);  assert.doesNotMatch(cookie, /Secure/, 'not Secure in tests: they use plain HTTP');});

views/auth/login.ejs changed

views/auth/login.ejs
<%- include('../partials/head') %><h1>Log in</h1><form method="post" action="/login" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">  <% if (error) { %><div class="error-summary" role="alert"><p><%= error %></p></div><% } %>  <div class="field">    <label for="email">Email</label>    <input id="email" name="email" type="email" value="<%= email %>" autocomplete="username" required>  </div>  <div class="field">    <label for="password">Password</label>    <input id="password" name="password" type="password" autocomplete="current-password" required>  </div>  <div class="form-actions">    <button type="submit" class="btn btn-primary">Log in</button>    <a class="btn" href="/register">Create an account</a>  </div></form><%- include('../partials/foot') %>

views/auth/register.ejs changed

views/auth/register.ejs
<%- include('../partials/head') %><h1>Create an account</h1><form method="post" action="/register" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">  <div class="field<%= errors.name ? ' has-error' : '' %>">    <label for="name">Name</label>    <input id="name" name="name" value="<%= values.name ?? '' %>" autocomplete="name">    <% if (errors.name) { %><p class="field-error"><%= errors.name %></p><% } %>  </div>  <div class="field<%= errors.email ? ' has-error' : '' %>">    <label for="email">Email</label>    <input id="email" name="email" type="email" value="<%= values.email ?? '' %>" autocomplete="username">    <% if (errors.email) { %><p class="field-error"><%= errors.email %></p><% } %>  </div>  <div class="field<%= errors.password ? ' has-error' : '' %>">    <label for="password">Password</label>    <input id="password" name="password" type="password" autocomplete="new-password">    <p class="hint">At least 10 characters. A passphrase of several words works well.</p>    <% if (errors.password) { %><p class="field-error"><%= errors.password %></p><% } %>  </div>  <div class="form-actions">    <button type="submit" class="btn btn-primary">Create account</button>    <a class="btn" href="/login">I already have an account</a>  </div></form><%- include('../partials/foot') %>

views/buildings/form.ejs changed

views/buildings/form.ejs
<%- include('../partials/head') %><h1><%= title %></h1><form method="post" action="<%= action %>" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">  <div class="field<%= errors.name ? ' has-error' : '' %>">    <label for="name">Building name</label>    <input id="name" name="name" value="<%= values.name ?? '' %>" maxlength="100" required>    <% if (errors.name) { %><p class="field-error"><%= errors.name %></p><% } %>  </div>  <div class="form-actions">    <button type="submit" class="btn btn-primary"><%= building ? 'Save changes' : 'Create building' %></button>    <a class="btn" href="<%= cancelUrl %>">Cancel</a>  </div></form><%- include('../partials/foot') %>

views/buildings/show.ejs changed

views/buildings/show.ejs
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations/<%= building.organisation_id %>"><%= building.organisation_name %></a> / Building #<%= building.id %></p><div class="page-header">  <h1><%= building.name %></h1>  <div class="actions">    <a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a>    <form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">      <button type="submit" class="btn btn-danger">Delete</button>    </form>  </div></div><% if (error) { %>  <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Latest issues</h2><% if (issues.length === 0) { %>  <p class="empty">No issues at this building.</p><% } else { %>  <table class="data">    <thead><tr><th>Title</th><th>Priority</th><th>Status</th><th>Occurred</th></tr></thead>    <tbody>      <% for (const issue of issues) { %>        <tr>          <td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td>          <td><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></td>          <td><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td>          <td><%= formatDate(issue.occurred_at) %></td>        </tr>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>

views/inspections/form.ejs changed

views/inspections/form.ejs
<%- include('../partials/head') %><h1><%= title %></h1><form method="post" action="<%= action %>" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">  <% if (!inspection) { %>    <div class="field<%= errors.building_id ? ' has-error' : '' %>">      <label for="building_id">Building</label>      <select id="building_id" name="building_id">        <option value="">Choose…</option>        <% for (const building of buildings) { %>          <option value="<%= building.id %>"<%= values.building_id === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option>        <% } %>      </select>      <% if (errors.building_id) { %><p class="field-error"><%= errors.building_id %></p><% } %>    </div>  <% } %>  <div class="field<%= errors.title ? ' has-error' : '' %>">    <label for="title">Title</label>    <input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200">    <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %>  </div>  <div class="field<%= errors.findings ? ' has-error' : '' %>">    <label for="findings">Findings</label>    <textarea id="findings" name="findings" maxlength="5000"><%= values.findings ?? '' %></textarea>    <% if (errors.findings) { %><p class="field-error"><%= errors.findings %></p><% } %>  </div>  <div class="form-actions">    <button type="submit" class="btn btn-primary"><%= inspection ? 'Save draft' : 'Create draft' %></button>    <a class="btn" href="<%= inspection ? `/inspections/${inspection.id}` : '/inspections' %>">Cancel</a>  </div></form><%- include('../partials/foot') %>

views/inspections/show.ejs changed

views/inspections/show.ejs
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/inspections">Inspections</a> / #<%= inspection.id %></p><div class="page-header">  <h1><%= inspection.title %></h1>  <div class="actions">    <% if (inspection.status === 'draft') { %>      <a class="btn" href="/inspections/<%= inspection.id %>/edit">Edit</a>      <form method="post" action="/inspections/<%= inspection.id %>/submit"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Submit for approval</button></form>    <% } %>    <% if (inspection.status === 'submitted') { %>      <form method="post" action="/inspections/<%= inspection.id %>/return"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn">Return to draft</button></form>      <form method="post" action="/inspections/<%= inspection.id %>/approve" data-confirm="Approve this inspection? Approved inspections cannot be changed."><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Approve</button></form>    <% } %>  </div></div><% if (error) { %>  <div class="flash flash-error" role="alert"><%= error %></div><% } %><dl class="details">  <dt>Building</dt><dd><a href="/buildings/<%= inspection.building_id %>"><%= inspection.building_name %></a></dd>  <dt>Status</dt><dd><span class="badge status-<%= inspection.status %>"><%= inspection.status %></span></dd>  <dt>Created by</dt><dd><%= inspection.created_by_name ?? 'unknown' %></dd>  <% if (inspection.submitted_at) { %><dt>Submitted</dt><dd><%= formatDate(inspection.submitted_at) %> UTC</dd><% } %>  <% if (inspection.approved_at) { %><dt>Approved</dt><dd><%= formatDate(inspection.approved_at) %> UTC</dd><% } %></dl><h2>Findings</h2><% if (inspection.findings) { %><p class="prose"><%= inspection.findings %></p><% } else { %><p class="empty">No findings recorded yet.</p><% } %><h2>History</h2><% if (history.length === 0) { %>  <p class="muted">No status changes yet.</p><% } else { %>  <table class="data">    <thead><tr><th>When (UTC)</th><th>Change</th><th>By</th></tr></thead>    <tbody>      <% for (const h of history) { %>        <tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td><td><%= h.changed_by_name ?? 'unknown' %></td></tr>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>

views/issues/form.ejs changed

views/issues/form.ejs
<%- include('../partials/head') %><h1><%= title %></h1> <% if (Object.keys(errors).length > 0) { %>  <div class="error-summary" role="alert">    <p>Please fix the highlighted fields.</p>  </div><% } %> <form method="post" action="<%= action %>" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">  <div class="field<%= errors.title ? ' has-error' : '' %>">    <label for="title">Title</label>    <input id="title" name="title" value="<%= values.title ?? '' %>" maxlength="200" required>    <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %>  </div>   <div class="field<%= errors.building_id ? ' has-error' : '' %>">    <label for="building_id">Building</label>    <select id="building_id" name="building_id">      <option value="">Choose…</option>      <% for (const building of buildings) { %>        <option value="<%= building.id %>"<%= values.building_id === building.id ? ' selected' : '' %>><%= building.organisation_name %> · <%= building.name %></option>      <% } %>    </select>    <% if (errors.building_id) { %><p class="field-error"><%= errors.building_id %></p><% } %>  </div>   <div class="field<%= errors.occurred_at ? ' has-error' : '' %>">    <label for="occurred_at">Occurred at (UTC)</label>    <input id="occurred_at" name="occurred_at" type="datetime-local" value="<%= values.occurred_at ?? '' %>">    <% if (errors.occurred_at) { %><p class="field-error"><%= errors.occurred_at %></p><% } %>  </div>   <div class="field<%= errors.description ? ' has-error' : '' %>">    <label for="description">Description <span class="muted">(optional)</span></label>    <textarea id="description" name="description" maxlength="2000"><%= values.description ?? '' %></textarea>    <% if (errors.description) { %><p class="field-error"><%= errors.description %></p><% } %>  </div>   <div class="field<%= errors.priority ? ' has-error' : '' %>">    <label for="priority">Priority</label>    <select id="priority" name="priority">      <option value="">Choose…</option>      <% for (const s of priorities) { %>        <option value="<%= s %>"<%= values.priority === s ? ' selected' : '' %>><%= s %></option>      <% } %>    </select>    <% if (errors.priority) { %><p class="field-error"><%= errors.priority %></p><% } %>  </div>   <% if (issue) { %>    <div class="field<%= errors.status ? ' has-error' : '' %>">      <label for="status">Status</label>      <select id="status" name="status">        <% for (const s of statuses) { %>          <option value="<%= s %>"<%= values.status === s ? ' selected' : '' %>><%= s %></option>        <% } %>      </select>      <% if (errors.status) { %><p class="field-error"><%= errors.status %></p><% } %>    </div>  <% } %>   <div class="form-actions">    <button type="submit" class="btn btn-primary"><%= issue ? 'Save changes' : 'Save issue' %></button>    <a class="btn" href="<%= issue ? `/issues/${issue.id}` : '/issues' %>">Cancel</a>  </div></form><%- include('../partials/foot') %>

views/issues/show.ejs changed

views/issues/show.ejs
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header">  <h1><%= issue.title %></h1>  <div class="actions">    <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a>    <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">      <button type="submit" class="btn btn-danger">Delete</button>    </form>  </div></div><dl class="details">  <dt>Building</dt><dd><%= issue.building_name %></dd>  <dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd>  <dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd>  <dt>Reported by</dt><dd><%= issue.reported_by_name ?? 'unknown' %></dd>  <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd>  <dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd></dl><% if (issue.description) { %>  <h2>Description</h2>  <p class="prose"><%= issue.description %></p><% } %><%- include('../partials/foot') %>

views/organisations/form.ejs changed

views/organisations/form.ejs
<%- include('../partials/head') %><h1><%= title %></h1><form method="post" action="<%= action %>" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">  <div class="field<%= errors.name ? ' has-error' : '' %>">    <label for="name">Name</label>    <input id="name" name="name" value="<%= values.name ?? '' %>" maxlength="100" required>    <% if (errors.name) { %><p class="field-error"><%= errors.name %></p><% } %>  </div>  <div class="form-actions">    <button type="submit" class="btn btn-primary"><%= organisation ? 'Save changes' : 'Create organisation' %></button>    <a class="btn" href="<%= organisation ? `/organisations/${organisation.id}` : '/organisations' %>">Cancel</a>  </div></form><%- include('../partials/foot') %>

views/organisations/show.ejs changed

views/organisations/show.ejs
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations">Organisations</a> / #<%= organisation.id %></p><div class="page-header">  <h1><%= organisation.name %></h1>  <div class="actions">    <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a>    <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a>    <form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">      <button type="submit" class="btn btn-danger">Delete</button>    </form>  </div></div><% if (typeof error !== 'undefined' && error) { %>  <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Buildings</h2><% if (buildings.length === 0) { %>  <p class="empty">This organisation has no buildings yet.</p><% } else { %>  <table class="data">    <thead><tr><th>Building</th><th>Issues</th></tr></thead>    <tbody>      <% for (const building of buildings) { %>        <tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>

views/partials/head.ejs changed

views/partials/head.ejs
<!doctype html><html lang="en"><head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width, initial-scale=1">  <meta name="csrf-token" content="<%= csrfToken %>">  <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><% } %>

views/partials/nav.ejs changed

views/partials/nav.ejs
<header class="site-header">  <div class="container header-inner">    <a class="brand" href="/">Caretaker</a>    <nav class="main-nav" aria-label="Main">      <a href="/issues">Issues</a>      <a href="/inspections">Inspections</a>      <a href="/organisations">Organisations</a>    </nav>    <div class="user-nav">      <% if (currentUser) { %>        <span>Signed in as <strong><%= currentUser.name %></strong></span>        <form method="post" action="/logout"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="link-button">Log out</button></form>      <% } else { %>        <a class="link-button" href="/login">Log in</a>      <% } %>    </div>  </div></header>

Project tree at this checkpoint

.env.example
.env.test
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
migrations/002_create_inspections.sql
migrations/003_create_users.sql
migrations/004_create_session_table.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/migrate.js
scripts/seed.js
src/app.js
src/config.js
src/db.js
src/lib/ids.js
src/lib/validation.js
src/middleware/auth.js
src/middleware/csrf.js
src/middleware/flash.js
src/middleware/rate-limit.js
src/migrate.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/organisations.js
src/models/users.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/auth.test.js
test/buildings.test.js
test/csrf.test.js
test/dashboard.test.js
test/helpers.js
test/inspections.test.js
test/issue-list.test.js
test/issues.test.js
test/organisations.test.js
test/rate-limit.test.js
test/require-login.test.js
views/auth/login.ejs
views/auth/register.ejs
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.ejs
views/issues/form.ejs
views/issues/index.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs

Back to lesson 4.4