Checkpoint · Lesson 7.3
Members and controlled onboarding: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m07-l03 -- src.
Files changed in this lesson
migrations/006_create_permission_changes.sql added
migrations/006_create_permission_changes.sql-- Every change to who may do what. Written in the same transaction as the change.
CREATE TABLE permission_changes (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
actor_id integer REFERENCES users (id) ON DELETE SET NULL,
target_user_id integer REFERENCES users (id) ON DELETE SET NULL,
organisation_id integer NOT NULL REFERENCES organisations (id) ON DELETE CASCADE,
building_id integer REFERENCES buildings (id) ON DELETE CASCADE,
change text NOT NULL CHECK (change IN ('add_member', 'change_member_role', 'grant_role', 'revoke_role')),
role text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX permission_changes_organisation_id_idx ON permission_changes (organisation_id);
-- Every change to who may do what. Written in the same transaction as the change.CREATE TABLE permission_changes ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, actor_id integer REFERENCES users (id) ON DELETE SET NULL, target_user_id integer REFERENCES users (id) ON DELETE SET NULL, organisation_id integer NOT NULL REFERENCES organisations (id) ON DELETE CASCADE, building_id integer REFERENCES buildings (id) ON DELETE CASCADE, change text NOT NULL CHECK (change IN ('add_member', 'change_member_role', 'grant_role', 'revoke_role')), role text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()); CREATE INDEX permission_changes_organisation_id_idx ON permission_changes (organisation_id);src/authz/authorize.js changed
src/authz/authorize.jsimport { config } from '../config.js';
import { buildAuthorizationCall } from './request.js';
import { evaluate } from './cedar.js';
// Builds the Cedar call for this user, action and database row, evaluates it, and logs.
export function authorize(user, action, row, context = {}) {
const call = buildAuthorizationCall(user, action, row, context);
const result = evaluate(call);
const resource = `${call.resource.type.replace('Caretaker::', '')}::${call.resource.id}`;
if (result.decision === 'failure' || result.errors.length > 0) {
console.error('authz problem', { user: user.id, action, resource, decision: result.decision, errors: result.errors });
}
if (config.authzLog) {
console.log(`authz user=${user.id} action=${action} resource=${resource} decision=${result.decision} reasons=${result.reasons.join(',') || '-'}`);
}
return result;
}
import { config } from '../config.js';import { buildAuthorizationCall } from './request.js';import { evaluate } from './cedar.js'; // Builds the Cedar call for this user, action and database row, evaluates it, and logs.export function authorize(user, action, row, context = {}) { const call = buildAuthorizationCall(user, action, row, context); const result = evaluate(call); const resource = `${call.resource.type.replace('Caretaker::', '')}::${call.resource.id}`; if (result.decision === 'failure' || result.errors.length > 0) { console.error('authz problem', { user: user.id, action, resource, decision: result.decision, errors: result.errors }); } if (config.authzLog) { console.log(`authz user=${user.id} action=${action} resource=${resource} decision=${result.decision} reasons=${result.reasons.join(',') || '-'}`); } return result;}src/authz/policies/forbid-self-membership-change.cedar added
src/authz/policies/forbid-self-membership-change.cedar// Nobody changes their own membership: no self-promotion, and no admin
// removing their own rights by accident.
forbid (principal, action == Caretaker::Action::"ManageMembers", resource)
when { context.targetUser == principal };
// Nobody changes their own membership: no self-promotion, and no admin// removing their own rights by accident.forbid (principal, action == Caretaker::Action::"ManageMembers", resource)when { context.targetUser == principal };src/authz/request.js changed
src/authz/request.jsimport { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity } from './entities.js';
// Which entity type each action's resource is. Must match the schema's appliesTo.
export const RESOURCE_TYPES = {
ViewOrganisation: 'Organisation',
UpdateOrganisation: 'Organisation',
DeleteOrganisation: 'Organisation',
CreateBuilding: 'Organisation',
ViewMembers: 'Organisation',
ManageMembers: 'Organisation',
ViewBuilding: 'Building',
UpdateBuilding: 'Building',
DeleteBuilding: 'Building',
CreateIssue: 'Building',
CreateInspection: 'Building',
ViewIssue: 'Issue',
UpdateIssue: 'Issue',
DeleteIssue: 'Issue',
ViewInspection: 'Inspection',
UpdateInspection: 'Inspection',
SubmitInspection: 'Inspection',
ApproveInspection: 'Inspection',
ReturnInspection: 'Inspection',
};
// The resource entity for a database row, followed by the building and organisation it belongs to.
function resourceEntities(type, row) {
switch (type) {
case 'Organisation':
return [organisationEntity(row.id)];
case 'Building':
return [buildingEntity(row), organisationEntity(row.organisation_id)];
case 'Issue':
return [issueEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)];
case 'Inspection':
return [inspectionEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)];
default:
throw new Error(`Unknown resource type ${type}`);
}
}
// Builds the request part of an isAuthorized call for one user, action and database row.
export function buildAuthorizationCall(user, action, row, context = {}) {
const type = RESOURCE_TYPES[action];
if (!type) {
throw new Error(`No Cedar resource type for action ${action}`);
}
const [resource, ...related] = resourceEntities(type, row);
return {
principal: ref('User', user.id),
action: { type: 'Caretaker::Action', id: action },
resource: resource.uid,
context,
entities: [userEntity(user), resource, ...related],
};
}
import { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity } from './entities.js'; // Which entity type each action's resource is. Must match the schema's appliesTo.export const RESOURCE_TYPES = { ViewOrganisation: 'Organisation', UpdateOrganisation: 'Organisation', DeleteOrganisation: 'Organisation', CreateBuilding: 'Organisation', ViewMembers: 'Organisation', ManageMembers: 'Organisation', ViewBuilding: 'Building', UpdateBuilding: 'Building', DeleteBuilding: 'Building', CreateIssue: 'Building', CreateInspection: 'Building', ViewIssue: 'Issue', UpdateIssue: 'Issue', DeleteIssue: 'Issue', ViewInspection: 'Inspection', UpdateInspection: 'Inspection', SubmitInspection: 'Inspection', ApproveInspection: 'Inspection', ReturnInspection: 'Inspection',}; // The resource entity for a database row, followed by the building and organisation it belongs to.function resourceEntities(type, row) { switch (type) { case 'Organisation': return [organisationEntity(row.id)]; case 'Building': return [buildingEntity(row), organisationEntity(row.organisation_id)]; case 'Issue': return [issueEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)]; case 'Inspection': return [inspectionEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)]; default: throw new Error(`Unknown resource type ${type}`); }} // Builds the request part of an isAuthorized call for one user, action and database row.export function buildAuthorizationCall(user, action, row, context = {}) { const type = RESOURCE_TYPES[action]; if (!type) { throw new Error(`No Cedar resource type for action ${action}`); } const [resource, ...related] = resourceEntities(type, row); return { principal: ref('User', user.id), action: { type: 'Caretaker::Action', id: action }, resource: resource.uid, context, entities: [userEntity(user), resource, ...related], };}src/authz/rules.js changed
src/authz/rules.js// Authorization: every route and template asks can(user, action, resource).
// Since Module 6 every answer comes from the Cedar policies in src/authz/policies.
import { authorize } from './authorize.js';
export function can(user, action, resource, context = {}) {
return authorize(user, action, resource, context).allowed;
}
// Authorization: every route and template asks can(user, action, resource).// Since Module 6 every answer comes from the Cedar policies in src/authz/policies.import { authorize } from './authorize.js'; export function can(user, action, resource, context = {}) { return authorize(user, action, resource, context).allowed;}src/authz/schema.cedarschema changed
src/authz/schema.cedarschema// What Cedar may see in Caretaker, and in what shape. Version 2.
namespace Caretaker {
entity Organisation;
entity Building in [Organisation] = {
organisation: Organisation,
};
// Version 2: facts only. Each set holds exactly the rows the database has.
entity User = {
viewerBuildings: Set<Building>,
reporterBuildings: Set<Building>,
inspectorBuildings: Set<Building>,
adminBuildings: Set<Building>,
memberOrganisations: Set<Organisation>,
adminOrganisations: Set<Organisation>,
};
entity Issue in [Building] = {
building: Building,
status: String,
priority: String,
reportedBy?: User,
};
entity Inspection in [Building] = {
building: Building,
status: String,
createdBy?: User,
};
// Action groups. A policy about a group applies to every action in it.
action ReadBuildingData;
action AdministerBuilding;
action AdministerOrganisation;
action ViewOrganisation appliesTo { principal: [User], resource: [Organisation] };
action UpdateOrganisation, DeleteOrganisation, CreateBuilding in [AdministerOrganisation] appliesTo {
principal: [User],
resource: [Organisation],
};
action DeleteBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Building] };
action ViewMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation] };
action ManageMembers in [AdministerOrganisation] appliesTo {
principal: [User],
resource: [Organisation],
context: { targetUser: User, role: String },
};
action ViewBuilding in [ReadBuildingData] appliesTo { principal: [User], resource: [Building] };
action ViewIssue in [ReadBuildingData] appliesTo { principal: [User], resource: [Issue] };
action ViewInspection in [ReadBuildingData] appliesTo { principal: [User], resource: [Inspection] };
action CreateIssue, CreateInspection, UpdateBuilding in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] };
action UpdateIssue, DeleteIssue in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue] };
action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo {
principal: [User],
resource: [Inspection],
};
}
// What Cedar may see in Caretaker, and in what shape. Version 2.namespace Caretaker { entity Organisation; entity Building in [Organisation] = { organisation: Organisation, }; // Version 2: facts only. Each set holds exactly the rows the database has. entity User = { viewerBuildings: Set<Building>, reporterBuildings: Set<Building>, inspectorBuildings: Set<Building>, adminBuildings: Set<Building>, memberOrganisations: Set<Organisation>, adminOrganisations: Set<Organisation>, }; entity Issue in [Building] = { building: Building, status: String, priority: String, reportedBy?: User, }; entity Inspection in [Building] = { building: Building, status: String, createdBy?: User, }; // Action groups. A policy about a group applies to every action in it. action ReadBuildingData; action AdministerBuilding; action AdministerOrganisation; action ViewOrganisation appliesTo { principal: [User], resource: [Organisation] }; action UpdateOrganisation, DeleteOrganisation, CreateBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation], }; action DeleteBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Building] }; action ViewMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation] }; action ManageMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation], context: { targetUser: User, role: String }, }; action ViewBuilding in [ReadBuildingData] appliesTo { principal: [User], resource: [Building] }; action ViewIssue in [ReadBuildingData] appliesTo { principal: [User], resource: [Issue] }; action ViewInspection in [ReadBuildingData] appliesTo { principal: [User], resource: [Inspection] }; action CreateIssue, CreateInspection, UpdateBuilding in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] }; action UpdateIssue, DeleteIssue in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue] }; action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo { principal: [User], resource: [Inspection], };}src/models/members.js added
src/models/members.jsimport { query, withTransaction } from '../db.js';
export const MEMBER_ROLES = ['member', 'org_admin'];
export async function listMembers(organisationId) {
const { rows } = await query(
`SELECT u.id, u.name, u.email, m.role
FROM memberships m
JOIN users u ON u.id = m.user_id
WHERE m.organisation_id = $1
ORDER BY u.name`,
[organisationId],
);
return rows;
}
// Adds a membership or changes its role, and records the change, in one transaction.
// Returns 'add_member' or 'change_member_role'.
export async function setMembership({ organisationId, userId, role, actorId }) {
return withTransaction(async (client) => {
const existing = await client.query(
'SELECT role FROM memberships WHERE user_id = $1 AND organisation_id = $2 FOR UPDATE',
[userId, organisationId],
);
let change;
if (existing.rowCount === 0) {
await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]);
change = 'add_member';
} else {
await client.query('UPDATE memberships SET role = $3 WHERE user_id = $1 AND organisation_id = $2', [userId, organisationId, role]);
change = 'change_member_role';
}
await client.query(
'INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, change, role) VALUES ($1, $2, $3, $4, $5)',
[actorId, userId, organisationId, change, role],
);
return change;
});
}
export async function listPermissionChanges(organisationId, limit = 20) {
const { rows } = await query(
`SELECT pc.change, pc.role, pc.created_at, actor.name AS actor_name, target.name AS target_name, s.name AS building_name
FROM permission_changes pc
LEFT JOIN users actor ON actor.id = pc.actor_id
LEFT JOIN users target ON target.id = pc.target_user_id
LEFT JOIN buildings s ON s.id = pc.building_id
WHERE pc.organisation_id = $1
ORDER BY pc.created_at DESC, pc.id DESC
LIMIT $2`,
[organisationId, limit],
);
return rows;
}
import { query, withTransaction } from '../db.js'; export const MEMBER_ROLES = ['member', 'org_admin']; export async function listMembers(organisationId) { const { rows } = await query( `SELECT u.id, u.name, u.email, m.role FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.organisation_id = $1 ORDER BY u.name`, [organisationId], ); return rows;} // Adds a membership or changes its role, and records the change, in one transaction.// Returns 'add_member' or 'change_member_role'.export async function setMembership({ organisationId, userId, role, actorId }) { return withTransaction(async (client) => { const existing = await client.query( 'SELECT role FROM memberships WHERE user_id = $1 AND organisation_id = $2 FOR UPDATE', [userId, organisationId], ); let change; if (existing.rowCount === 0) { await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]); change = 'add_member'; } else { await client.query('UPDATE memberships SET role = $3 WHERE user_id = $1 AND organisation_id = $2', [userId, organisationId, role]); change = 'change_member_role'; } await client.query( 'INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, change, role) VALUES ($1, $2, $3, $4, $5)', [actorId, userId, organisationId, change, role], ); return change; });} export async function listPermissionChanges(organisationId, limit = 20) { const { rows } = await query( `SELECT pc.change, pc.role, pc.created_at, actor.name AS actor_name, target.name AS target_name, s.name AS building_name FROM permission_changes pc LEFT JOIN users actor ON actor.id = pc.actor_id LEFT JOIN users target ON target.id = pc.target_user_id LEFT JOIN buildings s ON s.id = pc.building_id WHERE pc.organisation_id = $1 ORDER BY pc.created_at DESC, pc.id DESC LIMIT $2`, [organisationId, limit], ); return rows;}src/models/users.js changed
src/models/users.jsimport argon2 from 'argon2';
import { query } from '../db.js';
const PUBLIC_COLUMNS = 'id, email, name, created_at';
export function normaliseEmail(email) {
return typeof email === 'string' ? email.trim().toLowerCase() : '';
}
export async function hashPassword(password) {
return argon2.hash(password, { type: argon2.argon2id });
}
export async function createUser({ email, name, password }) {
const passwordHash = await hashPassword(password);
const { rows } = await query(
`INSERT INTO users (email, name, password_hash) VALUES ($1, $2, $3) RETURNING ${PUBLIC_COLUMNS}`,
[normaliseEmail(email), name, passwordHash],
);
return rows[0];
}
export async function findUserByEmail(email) {
const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE email = $1`, [normaliseEmail(email)]);
return rows[0] ?? null;
}
export async function findUserById(id) {
const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE id = $1`, [id]);
return rows[0] ?? null;
}
// A real hash of a random string. Used so that "unknown email" takes as long as "wrong password".
const DUMMY_HASH = await hashPassword(`dummy-${Math.random()}`);
// Returns the user (without the hash) if the email and password match, otherwise null.
export async function verifyCredentials(email, password) {
const { rows } = await query('SELECT id, password_hash FROM users WHERE email = $1', [normaliseEmail(email)]);
const row = rows[0];
const ok = await argon2.verify(row ? row.password_hash : DUMMY_HASH, typeof password === 'string' ? password : '');
return row && ok ? findUserById(row.id) : null;
}
import argon2 from 'argon2';import { query } from '../db.js'; const PUBLIC_COLUMNS = 'id, email, name, created_at'; export function normaliseEmail(email) { return typeof email === 'string' ? email.trim().toLowerCase() : '';} export async function hashPassword(password) { return argon2.hash(password, { type: argon2.argon2id });} export async function createUser({ email, name, password }) { const passwordHash = await hashPassword(password); const { rows } = await query( `INSERT INTO users (email, name, password_hash) VALUES ($1, $2, $3) RETURNING ${PUBLIC_COLUMNS}`, [normaliseEmail(email), name, passwordHash], ); return rows[0];} export async function findUserByEmail(email) { const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE email = $1`, [normaliseEmail(email)]); return rows[0] ?? null;} export async function findUserById(id) { const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE id = $1`, [id]); return rows[0] ?? null;} // A real hash of a random string. Used so that "unknown email" takes as long as "wrong password".const DUMMY_HASH = await hashPassword(`dummy-${Math.random()}`); // Returns the user (without the hash) if the email and password match, otherwise null.export async function verifyCredentials(email, password) { const { rows } = await query('SELECT id, password_hash FROM users WHERE email = $1', [normaliseEmail(email)]); const row = rows[0]; const ok = await argon2.verify(row ? row.password_hash : DUMMY_HASH, typeof password === 'string' ? password : ''); return row && ok ? findUserById(row.id) : null;}src/routes/organisations.js changed
src/routes/organisations.jsimport express from 'express';
import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';
import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { validateName } from '../lib/validation.js';
import { can } from '../authz/rules.js';
import { notFound, forbidden } from '../lib/http.js';
import { listMembers, setMembership, listPermissionChanges, MEMBER_ROLES } from '../models/members.js';
import { findUserByEmail, normaliseEmail } from '../models/users.js';
import { ref } from '../authz/entities.js';
export const organisationsRouter = express.Router();
const validateOrganisation = validateName;
function renderForm(res, status, { organisation = null, values = {}, errors = {} }) {
res.status(status).render('organisations/form', {
title: organisation ? `Edit ${organisation.name}` : 'New organisation',
action: organisation ? `/organisations/${organisation.id}/edit` : '/organisations',
organisation,
values,
errors,
});
}
// Loads the organisation named by :id, or answers 404. Returns null when it answered.
async function loadOrganisation(req, res) {
const id = parseId(req.params.id);
const organisation = id === null ? null : await findOrganisation(id);
if (!organisation || !can(req.user, 'ViewOrganisation', organisation)) {
notFound(req, res);
return null;
}
return organisation;
}
organisationsRouter.get('/', async (req, res) => {
res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations(req.user.id) });
});
organisationsRouter.get('/new', (req, res) => {
renderForm(res, 200, {});
});
organisationsRouter.post('/', async (req, res) => {
const { errors, values } = validateOrganisation(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderForm(res, 400, { values, errors });
}
const created = await createOrganisation(values, req.user.id);
res.redirect(303, `/organisations/${created.id}`);
});
organisationsRouter.get('/:id', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
const buildings = await listBuildingsForOrganisation(organisation.id);
res.render('organisations/show', { title: organisation.name, organisation, buildings });
});
organisationsRouter.get('/:id/edit', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);
renderForm(res, 200, { organisation, values: organisation });
});
organisationsRouter.post('/:id/edit', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);
const { errors, values } = validateOrganisation(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderForm(res, 400, { organisation, values, errors });
}
await updateOrganisation(organisation.id, values);
res.redirect(303, `/organisations/${organisation.id}`);
});
organisationsRouter.post('/:id/delete', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'DeleteOrganisation', organisation)) return forbidden(res);
try {
await deleteOrganisation(organisation.id);
} catch (err) {
if (err.code === PG_ERRORS.RESTRICT_VIOLATION) {
const buildings = await listBuildingsForOrganisation(organisation.id);
return res.status(409).render('organisations/show', {
title: organisation.name,
organisation,
buildings,
error: 'This organisation still has buildings. Delete its buildings first.',
});
}
throw err;
}
res.redirect(303, '/organisations');
});
async function renderMembers(res, status, organisation, { values = {}, error = null } = {}) {
res.status(status).render('organisations/members', {
title: `Members of ${organisation.name}`,
organisation,
members: await listMembers(organisation.id),
changes: await listPermissionChanges(organisation.id),
roles: MEMBER_ROLES,
values,
error,
});
}
organisationsRouter.get('/:id/members', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res);
await renderMembers(res, 200, organisation);
});
organisationsRouter.post('/:id/members', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res);
// The context comes from the form, so validate it and load the real user first.
const email = normaliseEmail(req.body?.email);
const role = MEMBER_ROLES.includes(req.body?.role) ? req.body.role : null;
const target = email ? await findUserByEmail(email) : null;
if (!target || !role) {
const error = !target ? 'No account uses that email. Ask the person to register first.' : 'Choose a role.';
return renderMembers(res, 400, organisation, { values: { email, role }, error });
}
if (!can(req.user, 'ManageMembers', organisation, { targetUser: ref('User', target.id), role })) {
return forbidden(res, 'You cannot make this membership change.');
}
try {
const change = await setMembership({ organisationId: organisation.id, userId: target.id, role, actorId: req.user.id });
req.flash('success', change === 'add_member' ? `${target.name} is now a ${role} of ${organisation.name}.` : `${target.name} is now ${role}.`);
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return renderMembers(res, 409, organisation, { values: { email, role }, error: 'Someone else changed this membership at the same time. Try again.' });
}
throw err;
}
res.redirect(303, `/organisations/${organisation.id}/members`);
});
function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) {
res.status(status).render('buildings/form', {
title: `New building in ${organisation.name}`,
action: `/organisations/${organisation.id}/buildings`,
cancelUrl: `/organisations/${organisation.id}`,
building: null,
values,
errors,
});
}
organisationsRouter.get('/:id/buildings/new', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);
renderBuildingForm(res, 200, { organisation });
});
organisationsRouter.post('/:id/buildings', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);
const { errors, values } = validateName(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderBuildingForm(res, 400, { organisation, values, errors });
}
try {
const building = await createBuilding({ organisation_id: organisation.id, name: values.name });
res.redirect(303, `/buildings/${building.id}`);
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } });
}
throw err;
}
});
import express from 'express';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';import { listMembers, setMembership, listPermissionChanges, MEMBER_ROLES } from '../models/members.js';import { findUserByEmail, normaliseEmail } from '../models/users.js';import { ref } from '../authz/entities.js'; export const organisationsRouter = express.Router(); const validateOrganisation = validateName; function renderForm(res, status, { organisation = null, values = {}, errors = {} }) { res.status(status).render('organisations/form', { title: organisation ? `Edit ${organisation.name}` : 'New organisation', action: organisation ? `/organisations/${organisation.id}/edit` : '/organisations', organisation, values, errors, });} // Loads the organisation named by :id, or answers 404. Returns null when it answered.async function loadOrganisation(req, res) { const id = parseId(req.params.id); const organisation = id === null ? null : await findOrganisation(id); if (!organisation || !can(req.user, 'ViewOrganisation', organisation)) { notFound(req, res); return null; } return organisation;} organisationsRouter.get('/', async (req, res) => { res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations(req.user.id) });}); organisationsRouter.get('/new', (req, res) => { renderForm(res, 200, {});}); organisationsRouter.post('/', async (req, res) => { const { errors, values } = validateOrganisation(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderForm(res, 400, { values, errors }); } const created = await createOrganisation(values, req.user.id); res.redirect(303, `/organisations/${created.id}`);}); organisationsRouter.get('/:id', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; const buildings = await listBuildingsForOrganisation(organisation.id); res.render('organisations/show', { title: organisation.name, organisation, buildings });}); organisationsRouter.get('/:id/edit', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res); renderForm(res, 200, { organisation, values: organisation });}); organisationsRouter.post('/:id/edit', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res); const { errors, values } = validateOrganisation(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderForm(res, 400, { organisation, values, errors }); } await updateOrganisation(organisation.id, values); res.redirect(303, `/organisations/${organisation.id}`);}); organisationsRouter.post('/:id/delete', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'DeleteOrganisation', organisation)) return forbidden(res); try { await deleteOrganisation(organisation.id); } catch (err) { if (err.code === PG_ERRORS.RESTRICT_VIOLATION) { const buildings = await listBuildingsForOrganisation(organisation.id); return res.status(409).render('organisations/show', { title: organisation.name, organisation, buildings, error: 'This organisation still has buildings. Delete its buildings first.', }); } throw err; } res.redirect(303, '/organisations');}); async function renderMembers(res, status, organisation, { values = {}, error = null } = {}) { res.status(status).render('organisations/members', { title: `Members of ${organisation.name}`, organisation, members: await listMembers(organisation.id), changes: await listPermissionChanges(organisation.id), roles: MEMBER_ROLES, values, error, });} organisationsRouter.get('/:id/members', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res); await renderMembers(res, 200, organisation);}); organisationsRouter.post('/:id/members', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res); // The context comes from the form, so validate it and load the real user first. const email = normaliseEmail(req.body?.email); const role = MEMBER_ROLES.includes(req.body?.role) ? req.body.role : null; const target = email ? await findUserByEmail(email) : null; if (!target || !role) { const error = !target ? 'No account uses that email. Ask the person to register first.' : 'Choose a role.'; return renderMembers(res, 400, organisation, { values: { email, role }, error }); } if (!can(req.user, 'ManageMembers', organisation, { targetUser: ref('User', target.id), role })) { return forbidden(res, 'You cannot make this membership change.'); } try { const change = await setMembership({ organisationId: organisation.id, userId: target.id, role, actorId: req.user.id }); req.flash('success', change === 'add_member' ? `${target.name} is now a ${role} of ${organisation.name}.` : `${target.name} is now ${role}.`); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderMembers(res, 409, organisation, { values: { email, role }, error: 'Someone else changed this membership at the same time. Try again.' }); } throw err; } res.redirect(303, `/organisations/${organisation.id}/members`);}); function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) { res.status(status).render('buildings/form', { title: `New building in ${organisation.name}`, action: `/organisations/${organisation.id}/buildings`, cancelUrl: `/organisations/${organisation.id}`, building: null, values, errors, });} organisationsRouter.get('/:id/buildings/new', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res); renderBuildingForm(res, 200, { organisation });}); organisationsRouter.post('/:id/buildings', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res); const { errors, values } = validateName(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderBuildingForm(res, 400, { organisation, values, errors }); } try { const building = await createBuilding({ organisation_id: organisation.id, name: values.name }); res.redirect(303, `/buildings/${building.id}`); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } }); } throw err; }});test/members.test.js added
test/members.test.jsimport { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
const agents = {};
before(async () => {
await resetDatabase();
for (const name of ['alice', 'bob', 'carol', 'dave', 'nora']) agents[name] = await loginAs(name);
});
after(() => pool.end());
test('only organisation admins can open the members page', async () => {
const statuses = {};
for (const name of ['alice', 'bob', 'carol', 'nora']) statuses[name] = (await agents[name].get('/organisations/1/members')).status;
assert.deepEqual(statuses, { alice: 403, bob: 404, carol: 200, nora: 404 });
});
test('controlled onboarding: carol adds nora; nora sees the organisation but no building', async () => {
const res = await agents.carol.post('/organisations/1/members').type('form').send({ email: 'NORA@example.test', role: 'member' });
assert.equal(res.status, 303);
assert.equal((await agents.nora.get('/organisations/1')).status, 200);
assert.equal((await agents.nora.get('/buildings/10')).status, 404);
const { rows } = await pool.query("SELECT actor_id, target_user_id, change, role FROM permission_changes WHERE target_user_id = 5");
assert.deepEqual(rows, [{ actor_id: 3, target_user_id: 5, change: 'add_member', role: 'member' }]);
});
test('promoting dave to org_admin gives him the organisation\'s admin rights on his next request', async () => {
assert.equal((await agents.dave.get('/organisations/1/edit')).status, 403);
await agents.carol.post('/organisations/1/members').type('form').send({ email: 'dave@example.test', role: 'org_admin' });
assert.equal((await agents.dave.get('/organisations/1/edit')).status, 200);
});
test('nobody changes their own membership', async () => {
const res = await agents.carol.post('/organisations/1/members').type('form').send({ email: 'carol@example.test', role: 'member' });
assert.equal(res.status, 403);
const { rows } = await pool.query('SELECT role FROM memberships WHERE user_id = 3 AND organisation_id = 1');
assert.equal(rows[0].role, 'org_admin');
});
test('unknown emails and roles are form errors', async () => {
assert.equal((await agents.carol.post('/organisations/1/members').type('form').send({ email: 'ghost@example.test', role: 'member' })).status, 400);
assert.equal((await agents.carol.post('/organisations/1/members').type('form').send({ email: 'nora@example.test', role: 'owner' })).status, 400);
});
test('a member cannot add members, even with a well-formed request', async () => {
const res = await agents.alice.post('/organisations/1/members').type('form').send({ email: 'nora@example.test', role: 'org_admin' });
assert.equal(res.status, 403);
});
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; const agents = {};before(async () => { await resetDatabase(); for (const name of ['alice', 'bob', 'carol', 'dave', 'nora']) agents[name] = await loginAs(name);});after(() => pool.end()); test('only organisation admins can open the members page', async () => { const statuses = {}; for (const name of ['alice', 'bob', 'carol', 'nora']) statuses[name] = (await agents[name].get('/organisations/1/members')).status; assert.deepEqual(statuses, { alice: 403, bob: 404, carol: 200, nora: 404 });}); test('controlled onboarding: carol adds nora; nora sees the organisation but no building', async () => { const res = await agents.carol.post('/organisations/1/members').type('form').send({ email: 'NORA@example.test', role: 'member' }); assert.equal(res.status, 303); assert.equal((await agents.nora.get('/organisations/1')).status, 200); assert.equal((await agents.nora.get('/buildings/10')).status, 404); const { rows } = await pool.query("SELECT actor_id, target_user_id, change, role FROM permission_changes WHERE target_user_id = 5"); assert.deepEqual(rows, [{ actor_id: 3, target_user_id: 5, change: 'add_member', role: 'member' }]);}); test('promoting dave to org_admin gives him the organisation\'s admin rights on his next request', async () => { assert.equal((await agents.dave.get('/organisations/1/edit')).status, 403); await agents.carol.post('/organisations/1/members').type('form').send({ email: 'dave@example.test', role: 'org_admin' }); assert.equal((await agents.dave.get('/organisations/1/edit')).status, 200);}); test('nobody changes their own membership', async () => { const res = await agents.carol.post('/organisations/1/members').type('form').send({ email: 'carol@example.test', role: 'member' }); assert.equal(res.status, 403); const { rows } = await pool.query('SELECT role FROM memberships WHERE user_id = 3 AND organisation_id = 1'); assert.equal(rows[0].role, 'org_admin');}); test('unknown emails and roles are form errors', async () => { assert.equal((await agents.carol.post('/organisations/1/members').type('form').send({ email: 'ghost@example.test', role: 'member' })).status, 400); assert.equal((await agents.carol.post('/organisations/1/members').type('form').send({ email: 'nora@example.test', role: 'owner' })).status, 400);}); test('a member cannot add members, even with a well-formed request', async () => { const res = await agents.alice.post('/organisations/1/members').type('form').send({ email: 'nora@example.test', role: 'org_admin' }); assert.equal(res.status, 403);});views/organisations/members.ejs added
views/organisations/members.ejs<%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/organisations/<%= organisation.id %>"><%= organisation.name %></a> / Members</p>
<h1>Members of <%= organisation.name %></h1>
<% if (error) { %><div class="flash flash-error" role="alert"><%= error %></div><% } %>
<table class="data">
<thead><tr><th>Name</th><th>Email</th><th>Role</th></tr></thead>
<tbody>
<% for (const m of members) { %>
<tr><td><%= m.name %></td><td><%= m.email %></td><td><span class="badge role-badge"><%= m.role %></span></td></tr>
<% } %>
</tbody>
</table>
<h2>Add a member or change a role</h2>
<form method="post" action="/organisations/<%= organisation.id %>/members" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<div class="field">
<label for="email">Email of a registered user</label>
<input id="email" name="email" type="email" value="<%= values.email ?? '' %>">
</div>
<div class="field">
<label for="role">Role</label>
<select id="role" name="role">
<% for (const r of roles) { %><option value="<%= r %>"<%= values.role === r ? ' selected' : '' %>><%= r %></option><% } %>
</select>
</div>
<div class="form-actions"><button type="submit" class="btn btn-primary">Save membership</button></div>
</form>
<h2>Recent permission changes</h2>
<% if (changes.length === 0) { %>
<p class="muted">No changes recorded yet.</p>
<% } else { %>
<table class="data">
<thead><tr><th>When (UTC)</th><th>By</th><th>Change</th><th>For</th><th>Role</th><th>Building</th></tr></thead>
<tbody>
<% for (const c of changes) { %>
<tr><td><%= formatDate(c.created_at) %></td><td><%= c.actor_name ?? 'unknown' %></td><td><%= c.change %></td><td><%= c.target_name ?? 'unknown' %></td><td><%= c.role %></td><td><%= c.building_name ?? '' %></td></tr>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations/<%= organisation.id %>"><%= organisation.name %></a> / Members</p><h1>Members of <%= organisation.name %></h1><% if (error) { %><div class="flash flash-error" role="alert"><%= error %></div><% } %> <table class="data"> <thead><tr><th>Name</th><th>Email</th><th>Role</th></tr></thead> <tbody> <% for (const m of members) { %> <tr><td><%= m.name %></td><td><%= m.email %></td><td><span class="badge role-badge"><%= m.role %></span></td></tr> <% } %> </tbody></table> <h2>Add a member or change a role</h2><form method="post" action="/organisations/<%= organisation.id %>/members" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <div class="field"> <label for="email">Email of a registered user</label> <input id="email" name="email" type="email" value="<%= values.email ?? '' %>"> </div> <div class="field"> <label for="role">Role</label> <select id="role" name="role"> <% for (const r of roles) { %><option value="<%= r %>"<%= values.role === r ? ' selected' : '' %>><%= r %></option><% } %> </select> </div> <div class="form-actions"><button type="submit" class="btn btn-primary">Save membership</button></div></form> <h2>Recent permission changes</h2><% if (changes.length === 0) { %> <p class="muted">No changes recorded yet.</p><% } else { %> <table class="data"> <thead><tr><th>When (UTC)</th><th>By</th><th>Change</th><th>For</th><th>Role</th><th>Building</th></tr></thead> <tbody> <% for (const c of changes) { %> <tr><td><%= formatDate(c.created_at) %></td><td><%= c.actor_name ?? 'unknown' %></td><td><%= c.change %></td><td><%= c.target_name ?? 'unknown' %></td><td><%= c.role %></td><td><%= c.building_name ?? '' %></td></tr> <% } %> </tbody> </table><% } %><%- 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">
<% if (can('UpdateOrganisation', organisation)) { %>
<a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a>
<% } %>
<% if (can('ViewMembers', organisation)) { %>
<a class="btn" href="/organisations/<%= organisation.id %>/members">Members</a>
<% } %>
<% if (can('CreateBuilding', organisation)) { %>
<a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a>
<% } %>
<% if (can('DeleteOrganisation', organisation)) { %>
<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) { %>
<% const buildingRef = { id: building.id, organisation_id: organisation.id }; %>
<% if (can('ViewBuilding', buildingRef)) { %>
<tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>
<% } else { %>
<tr><td><%= building.name %></td><td class="muted">no access</td></tr>
<% } %>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
<%- 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"> <% if (can('UpdateOrganisation', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a> <% } %> <% if (can('ViewMembers', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/members">Members</a> <% } %> <% if (can('CreateBuilding', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a> <% } %> <% if (can('DeleteOrganisation', organisation)) { %> <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) { %> <% const buildingRef = { id: building.id, organisation_id: organisation.id }; %> <% if (can('ViewBuilding', buildingRef)) { %> <tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr> <% } else { %> <tr><td><%= building.name %></td><td class="muted">no access</td></tr> <% } %> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %>Project tree at this checkpoint
.env.example
.env.test
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
migrations/002_create_inspections.sql
migrations/003_create_users.sql
migrations/004_create_session_table.sql
migrations/005_create_memberships_and_building_roles.sql
migrations/006_create_permission_changes.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/authz-explain.js
scripts/cedar-errors-demo.js
scripts/cedar-hello.js
scripts/migrate.js
scripts/seed.js
scripts/template-demo.js
scripts/validate-policies.js
src/app.js
src/authz/authorize.js
src/authz/cedar.js
src/authz/entities.js
src/authz/policies/building-admin.cedar
src/authz/policies/building-read.cedar
src/authz/policies/forbid-self-approval.cedar
src/authz/policies/forbid-self-membership-change.cedar
src/authz/policies/inspector-create-inspection.cedar
src/authz/policies/inspector-own-inspections.cedar
src/authz/policies/org-admin.cedar
src/authz/policies/org-member.cedar
src/authz/policies/reporter-create-issue.cedar
src/authz/policies/reporter-own-issues.cedar
src/authz/policy-store.js
src/authz/request.js
src/authz/rules.js
src/authz/schema.cedarschema
src/config.js
src/db.js
src/lib/http.js
src/lib/ids.js
src/lib/validation.js
src/middleware/auth.js
src/middleware/csrf.js
src/middleware/flash.js
src/middleware/rate-limit.js
src/migrate.js
src/models/access.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/members.js
src/models/organisations.js
src/models/scope.js
src/models/users.js
src/routes/account.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/access-matrix.test.js
test/access.test.js
test/auth.test.js
test/authz-decisions.test.js
test/buildings.test.js
test/csrf.test.js
test/dashboard.test.js
test/helpers.js
test/inspections.test.js
test/isolation.test.js
test/issue-authz.test.js
test/issue-list.test.js
test/issues.test.js
test/members.test.js
test/organisations.test.js
test/policies.test.js
test/rate-limit.test.js
test/require-login.test.js
test/resource-authz.test.js
views/account.ejs
views/auth/login.ejs
views/auth/register.ejs
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/forbidden.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.ejs
views/issues/form.ejs
views/issues/index.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/members.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs