Files
parking_solution/apps/server/src/routes/printers.ts
T
julian d0841c8601 feat(auth): dynamic RBAC — composable roles + resource×CRUD permissions
Replace the hardcoded role enum (admin/operator/cashier/readonly, checked
literally as requireRole("admin",...) across ~15 routes) with dynamic RBAC:
roles are DATA, route guards check a PERMISSION.

@parking/shared defines a code-defined grid: RESOURCES (user/role/tariff/
subscription/site/device/shift/payment/session/event/report) × Action
(create/read/update/delete + domain verbs void/cash) -> PERMISSIONS
(resource:action, e.g. tariff:update, payment:create, event:void).

DB: new roles + role_permissions tables; users.role enum -> role_id FK;
migration 0007_rbac (create tables, seed the builtin admin role + all 26
perms, seed operator/cashier/readonly composable roles matching old
behaviour, rebuild users to swap the column copying all rows).

auth.ts: JWT payload role -> roleId; permissionsFor(roleId) with an
in-memory cache + bumpPermsCache(); requirePermission(...perms) preHandler;
requireAuth for /me & /language; initAuth(db) wires the resolver once. Every
route guard mapped to a permission; device ingress (devices/qr-reader) stays
auth-free by design. New routes/users.ts (user:* CRUD, bcrypt 12, last-admin
guard) + routes/roles.ts (role:* CRUD, builtin-protected, perms validated
against the grid, cache bump on write). auth/me + /login return
{roleId, roleName, permissions, language}. seed-admin -> roleId:'admin'.

Frontend: SessionUser carries permissions + can() helper; router nav/route
guards gate by permission (requirePerm replaces adminOnly); SiteSettings
edit gated by site:update; new UsersManager + RolesManager (permission
checkbox grid; admin role locked); i18n nav.users/roles + blocks (sq+en).

Decisions: one role per user; protected built-in admin (no-lockout: the last
admin can't be deleted/downgraded); JWT carries roleId, perms resolved
per-request so role edits apply immediately (no re-login).

Verified: full build green; 20-assertion inject test passes (cashier 403s on
tariff publish + user list, admin passes, granting a perm applies on the next
request, last-admin + builtin-role protections return 409); migration 0007
applied to a copy of the live DB (incl WAL/shm) — existing admin maps to
role_id='admin', all rows preserved. Append-only event chain untouched
(event:void gates appending a void, not a delete).

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
2026-06-19 01:19:28 +02:00

51 lines
1.9 KiB
TypeScript

import type { FastifyInstance } from "fastify";
import { requirePermission } from "../auth.js";
import { deviceEvents } from "../device-events.js";
import type { PrinterMonitor } from "../printer-monitor.js";
// Live printer-status API. The PrinterMonitor polls printers in the background;
// these endpoints expose its cache (snapshot) and a live push stream (SSE) so the
// booth UI shows paper-out / cover-open / offline in real time. Any authenticated
// operator may read status (it's operational, not a setup action).
export async function printerRoutes(
app: FastifyInstance,
monitor: PrinterMonitor,
): Promise<void> {
const guard = requirePermission("device:read");
// Current status of every monitored printer (cached — no device round-trip).
app.get("/api/printers/status", { preHandler: guard }, async () => ({
printers: monitor.snapshot(),
}));
// Live stream: emits the full snapshot on connect, then one event per change.
// Server-Sent Events — one-way, survives proxies, trivially consumed by the SPA.
app.get("/api/printers/status/stream", { preHandler: guard }, (req, reply) => {
reply.raw.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
connection: "keep-alive",
});
const send = (event: string, data: unknown) => {
reply.raw.write(`event: ${event}\n`);
reply.raw.write(`data: ${JSON.stringify(data)}\n\n`);
};
// Initial state so a fresh client doesn't wait for the next change.
send("snapshot", { printers: monitor.snapshot() });
const unsubscribe = deviceEvents.onPrinterStatus((e) => send("status", e));
// Heartbeat keeps intermediaries from closing an idle connection.
const heartbeat = setInterval(() => reply.raw.write(": ping\n\n"), 25000);
heartbeat.unref?.();
req.raw.on("close", () => {
clearInterval(heartbeat);
unsubscribe();
});
});
}