Name exactly one gate on every declaration, and own a shift by identity id
This commit is contained in:
@@ -49,6 +49,7 @@ export const ADMIN_NAV: NavNode = {
|
||||
icon: "i-shield",
|
||||
id: "admin",
|
||||
label: "admin.nav.section", // a key in this plugin's catalog; the host translates nav labels
|
||||
public: true, // the header gates nothing; every child needs a permission, and an empty header is dropped
|
||||
};
|
||||
|
||||
// The screen gate: a signed-in user holding this request's `<resource>:<action>`. Each route already
|
||||
|
||||
@@ -18,6 +18,9 @@ What it demonstrates:
|
||||
- **All three route gates** — the Overview is `public` (anyone), "My shifts" is `session` (any
|
||||
signed-in visitor, showing only rows assigned to them), and "Shifts" is gated on `scheduling:read` /
|
||||
`scheduling:write`; a leaf whose gate a visitor fails is invisible in the menu.
|
||||
- **Ownership joined on the identity id** — "My shifts" asks the upstream for `assigneeId=ctx.user.id`,
|
||||
the opaque subject id, and renders the row's separate `assignee` display name. An email address is
|
||||
user-changeable and can be reassigned to someone else, who would then inherit those rows.
|
||||
- **Its own translations** — every string comes from `i18n/en-US.ts` (`sv-SE.ts` beside it), including
|
||||
the nav labels, which are catalog keys in the manifest. `shifts.count` shows a plural message, and
|
||||
the views carry the visitor's language onto their links with `localeHref()`.
|
||||
@@ -39,8 +42,8 @@ Your backend must expose two routes; the plugin treats any non-2xx as a recovera
|
||||
|
||||
| Route | Request | Success | Response body |
|
||||
| --- | --- | --- | --- |
|
||||
| `GET /shifts` | `Accept: application/json`, optional `?assignee=<who>` | `200` | JSON array of `{ id, title, assignee, start, end }` (all strings; missing fields coerce to `""`). With `assignee`, only that person's rows |
|
||||
| `POST /shifts` | JSON body `{ title, assignee, start, end }` | `2xx` | ignored (the plugin POST-redirect-GETs back to the list) |
|
||||
| `GET /shifts` | `Accept: application/json`, optional `?assigneeId=<id>` | `200` | JSON array of `{ id, title, assignee, assigneeId, start, end }` (all strings; missing fields coerce to `""`). With `assigneeId`, only that person's rows |
|
||||
| `POST /shifts` | JSON body `{ title, assignee, assigneeId?, start, end }` | `2xx` | ignored (the plugin POST-redirect-GETs back to the list) |
|
||||
|
||||
Domain rules (overlap, capacity, time ordering) live in your backend — reject with a 4xx and the
|
||||
form re-renders. The plugin only validates that `title` and `assignee` are non-empty.
|
||||
@@ -54,4 +57,5 @@ cosmetically) — normalise to your backend's format there if it matters.
|
||||
A user sees the shift list once they hold the `scheduling:read` permission in Keto (and
|
||||
`scheduling:write` to create). The one-command bootstrap grants both to the demo admin, so the seeded
|
||||
`admin@plainpages.local` can use it immediately. "My shifts" needs no grant at all — signing in is
|
||||
its whole gate.
|
||||
its whole gate; it lists the rows this demo upstream holds against the signed-in visitor's id, and
|
||||
the demo's seeded rows belong to three made-up people, so a freshly seeded admin sees it empty.
|
||||
|
||||
@@ -31,6 +31,7 @@ export default definePlugin({
|
||||
icon: "i-cal",
|
||||
id: "scheduling",
|
||||
label: "scheduling.nav.section",
|
||||
public: true, // the header gates nothing; each child names its own gate, and an empty header is dropped
|
||||
}],
|
||||
|
||||
// Roles this plugin introduces (docs + Keto seeding). Namespaced `<id>:<action>`.
|
||||
|
||||
@@ -25,8 +25,8 @@ function fakeCtx(opts: { body?: string; permissions?: string[]; url?: string; us
|
||||
}
|
||||
|
||||
const SHIFTS: Shift[] = [
|
||||
{ assignee: "Avery Kline", end: "12:00", id: "1", start: "08:00", title: "Morning desk" },
|
||||
{ assignee: "Blair Mora", end: "17:00", id: "2", start: "12:00", title: "Afternoon support" },
|
||||
{ assignee: "Avery Kline", assigneeId: "019bdc1a-3f27-7c41-9a6e-2b1d4f8e05a3", end: "12:00", id: "1", start: "08:00", title: "Morning desk" },
|
||||
{ assignee: "Blair Mora", assigneeId: "019bdc1a-4a83-7de2-8f05-6c93a71be4d8", end: "17:00", id: "2", start: "12:00", title: "Afternoon support" },
|
||||
];
|
||||
const fakeUpstream = (over: Partial<ShiftsUpstream> = {}): ShiftsUpstream => ({ create: async () => {}, list: async () => SHIFTS, ...over });
|
||||
|
||||
@@ -63,11 +63,11 @@ test("createUpstream.list fetches /shifts, asks for JSON, and maps the rows", as
|
||||
const http = (async (url, init) => {
|
||||
seen = String(url);
|
||||
assert.equal((init?.headers as Record<string, string>).accept, "application/json");
|
||||
return new Response(JSON.stringify([{ assignee: "A", end: "2", id: "x", start: "1", title: "T", extra: "ignored" }]), { status: 200 });
|
||||
return new Response(JSON.stringify([{ assignee: "A", assigneeId: "019bdc1a-5b6e-7a90-b3c7-84f01d2ea9b6", end: "2", id: "x", start: "1", title: "T", extra: "ignored" }]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const shifts = await createUpstream(() => "http://up:4000/", http).list(); // trailing slash trimmed
|
||||
assert.equal(seen, "http://up:4000/shifts");
|
||||
assert.deepEqual(shifts, [{ assignee: "A", end: "2", id: "x", start: "1", title: "T" }]);
|
||||
assert.deepEqual(shifts, [{ assignee: "A", assigneeId: "019bdc1a-5b6e-7a90-b3c7-84f01d2ea9b6", end: "2", id: "x", start: "1", title: "T" }]);
|
||||
});
|
||||
|
||||
test("createUpstream throws UpstreamError carrying the status on a non-2xx", async () => {
|
||||
@@ -174,19 +174,20 @@ test("buildFormModel marks title/assignee required and attaches field errors", (
|
||||
|
||||
// ---- the session-gated page: the visitor's own rows ----
|
||||
|
||||
test("my shifts asks the upstream for the visitor's own rows, and names them in the empty state", async () => {
|
||||
test("my shifts scopes the upstream read by the visitor's id, and names them in the empty state", async () => {
|
||||
const user: User = { email: "Blair.Mora@example.test", id: "01a06091-baa3-71f4-a068-4879972979ff", permissions: [] };
|
||||
const mine: Shift = { assignee: "blair.mora@example.test", end: "22:00", id: "3", start: "17:00", title: "Evening on-call" };
|
||||
let asked: { assignee?: string } | undefined;
|
||||
const mine: Shift = { assignee: "Blair Mora", assigneeId: user.id, end: "22:00", id: "3", start: "17:00", title: "Evening on-call" };
|
||||
let asked: { assigneeId?: string } | undefined;
|
||||
|
||||
const upstream = fakeUpstream({ list: async (opts) => { asked = opts; return [mine]; } });
|
||||
const r = asView(await myShifts(upstream)(fakeCtx({ url: "http://localhost/scheduling/mine", user })));
|
||||
assert.equal(r.view, "mine");
|
||||
assert.deepEqual(asked, { assignee: "Blair.Mora@example.test" });
|
||||
assert.deepEqual(asked, { assigneeId: "01a06091-baa3-71f4-a068-4879972979ff" }); // the id, never the address
|
||||
const table = r.data["table"] as { emptyText: string; rows: { name: string }[] };
|
||||
assert.deepEqual(table.rows.map((row) => row.name), ["Evening on-call"]);
|
||||
assert.match(table.emptyText, /Blair\.Mora@example\.test/); // an empty page still says whose it is
|
||||
|
||||
// The route carries `session: true`, but the handler asserts the session itself rather than trusting it.
|
||||
// `requireSession` narrows `ctx.user` from `User | null` to `User` — the one part of the route's
|
||||
// `session: true` guarantee the contract cannot state in the handler's type.
|
||||
await assert.rejects(async () => { await myShifts(fakeUpstream())(fakeCtx()); }, GuardError);
|
||||
});
|
||||
|
||||
@@ -22,7 +22,8 @@ export const WRITE = "scheduling:write"; // the permission gating create
|
||||
|
||||
export interface Shift {
|
||||
id: string;
|
||||
assignee: string;
|
||||
assignee: string; // display name, rendered in the table
|
||||
assigneeId: string; // who the shift belongs to — an opaque id, the same one `ctx.user.id` carries
|
||||
end: string;
|
||||
start: string;
|
||||
title: string;
|
||||
@@ -47,9 +48,9 @@ export class UpstreamError extends Error {
|
||||
|
||||
export interface ShiftsUpstream {
|
||||
create(input: ShiftInput): Promise<void>;
|
||||
// `assignee` scopes the read at the source, which is where an ownership rule belongs (README →
|
||||
// `assigneeId` scopes the read at the source, which is where an ownership rule belongs (README →
|
||||
// Three tiers of "may I?"); without it the caller would hold everyone's rows to render one page.
|
||||
list(opts?: { assignee?: string }): Promise<Shift[]>;
|
||||
list(opts?: { assigneeId?: string }): Promise<Shift[]>;
|
||||
}
|
||||
|
||||
// REST client over the upstream service (a stand-in for the customer's real backend). `fetch`
|
||||
@@ -69,7 +70,7 @@ export function createUpstream(baseUrl: () => string, fetchImpl: typeof fetch =
|
||||
if (!res.ok) throw new UpstreamError(`create shift failed (${res.status})`, res.status);
|
||||
},
|
||||
async list(opts = {}) {
|
||||
const query = opts.assignee == null ? "" : `?${new URLSearchParams({ assignee: opts.assignee })}`;
|
||||
const query = opts.assigneeId == null ? "" : `?${new URLSearchParams({ assigneeId: opts.assigneeId })}`;
|
||||
const res = await fetchImpl(`${base()}/shifts${query}`, { headers: { accept: "application/json" } });
|
||||
if (!res.ok) throw new UpstreamError(`list shifts failed (${res.status})`, res.status);
|
||||
const data: unknown = await res.json();
|
||||
@@ -82,7 +83,7 @@ const str = (v: unknown): string => (typeof v === "string" ? v : v == null ? ""
|
||||
|
||||
function toShift(raw: unknown): Shift {
|
||||
const r = (raw ?? {}) as Record<string, unknown>;
|
||||
return { assignee: str(r["assignee"]), end: str(r["end"]), id: str(r["id"]), start: str(r["start"]), title: str(r["title"]) };
|
||||
return { assignee: str(r["assignee"]), assigneeId: str(r["assigneeId"]), end: str(r["end"]), id: str(r["id"]), start: str(r["start"]), title: str(r["title"]) };
|
||||
}
|
||||
|
||||
// ---- view models (pure; the EJS views read these) -----------------------------------
|
||||
@@ -196,7 +197,9 @@ export function myShifts(upstream: ShiftsUpstream): RouteHandler {
|
||||
let shifts: Shift[] = [];
|
||||
let error: string | undefined;
|
||||
try {
|
||||
shifts = await upstream.list({ assignee: user.email });
|
||||
// Join on the id, never the email: an address is user-changeable and can be reassigned to
|
||||
// someone else, which would hand them the previous holder's rows.
|
||||
shifts = await upstream.list({ assigneeId: user.id });
|
||||
} catch (err) {
|
||||
ctx.log.warn("scheduling upstream unreachable", { error: String(err) });
|
||||
error = ctx.t("scheduling.upstream.list");
|
||||
|
||||
Reference in New Issue
Block a user