d0841c8601
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
113 lines
4.4 KiB
TypeScript
113 lines
4.4 KiB
TypeScript
import type { FastifyInstance } from "fastify";
|
|
import { eq, siteConfig, type Db } from "@parking/db";
|
|
import { requirePermission } from "../auth.js";
|
|
import { getOccupancy } from "../occupancy.js";
|
|
|
|
// Site config (capacity) + live occupancy. Occupancy is a fold over the signed
|
|
// ledger; capacity is an admin-set knob. The FULL gate (refuse transient entry at
|
|
// capacity) lives in the entry flow. See wiki/concepts/capacity-occupancy.md.
|
|
|
|
// Optional park-metadata text fields (all nullable). Trimmed; "" → null.
|
|
const TEXT_FIELDS = [
|
|
"parkName",
|
|
"operatorName",
|
|
"nius",
|
|
"address",
|
|
"phone",
|
|
"email",
|
|
// IANA timezone for tariff wall-clock windows (copied into each published version).
|
|
"timezone",
|
|
// Default vehicle/customer category frozen onto each transient entry.
|
|
"defaultVehicleCategory",
|
|
] as const;
|
|
type TextField = (typeof TEXT_FIELDS)[number];
|
|
|
|
interface SiteConfigBody extends Partial<Record<TextField, string | null>> {
|
|
/** Nominal capacity; null = no limit. */
|
|
capacity?: number | null;
|
|
/** Default for the booth "print exit ticket" checkbox (booth-geography knob). */
|
|
exitVoucherDefault?: boolean;
|
|
/** Site default monthly subscription price in minor units (pre-fills the form). */
|
|
subscriptionMonthlyPriceMinor?: number | null;
|
|
}
|
|
|
|
/** Shape returned by GET/PUT: capacity + the booth flag + the subscription default
|
|
* + every metadata field. */
|
|
type SiteConfig = {
|
|
capacity: number | null;
|
|
exitVoucherDefault: boolean;
|
|
subscriptionMonthlyPriceMinor: number | null;
|
|
} & Record<TextField, string | null>;
|
|
|
|
function toSiteConfig(row: typeof siteConfig.$inferSelect | undefined): SiteConfig {
|
|
const out = {
|
|
capacity: row?.capacity ?? null,
|
|
exitVoucherDefault: row?.exitVoucherDefault ?? false,
|
|
subscriptionMonthlyPriceMinor: row?.subscriptionMonthlyPriceMinor ?? null,
|
|
} as SiteConfig;
|
|
for (const f of TEXT_FIELDS) out[f] = row?.[f] ?? null;
|
|
return out;
|
|
}
|
|
|
|
/** Trim a text field; empty string becomes null so blank input clears it. */
|
|
function normText(v: unknown): string | null {
|
|
if (v == null) return null;
|
|
const s = String(v).trim();
|
|
return s === "" ? null : s;
|
|
}
|
|
|
|
export async function siteRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|
const readGuard = requirePermission("site:read");
|
|
const writeGuard = requirePermission("site:update");
|
|
|
|
// Live occupancy: cars inside, capacity, free, full. Any signed-in role.
|
|
app.get("/api/occupancy", { preHandler: readGuard }, async () => getOccupancy(db));
|
|
|
|
// Read site config (capacity + park metadata).
|
|
app.get("/api/site-config", { preHandler: readGuard }, async () => {
|
|
const row = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
|
return toSiteConfig(row);
|
|
});
|
|
|
|
// Set site config (admin). Capacity: null or 0+ integer. Metadata: optional text
|
|
// (only the fields PRESENT in the body are updated; absent fields are untouched).
|
|
app.put<{ Body: SiteConfigBody }>("/api/site-config", { preHandler: writeGuard }, async (req, reply) => {
|
|
const body = req.body ?? ({} as SiteConfigBody);
|
|
|
|
const patch: Partial<typeof siteConfig.$inferInsert> = {};
|
|
if ("capacity" in body) {
|
|
const c = body.capacity;
|
|
if (c != null && (!Number.isInteger(c) || c < 0)) {
|
|
return reply.code(400).send({ error: "capacity must be a non-negative integer or null" });
|
|
}
|
|
patch.capacity = c ?? null;
|
|
}
|
|
if ("exitVoucherDefault" in body) {
|
|
if (typeof body.exitVoucherDefault !== "boolean") {
|
|
return reply.code(400).send({ error: "exitVoucherDefault must be a boolean" });
|
|
}
|
|
patch.exitVoucherDefault = body.exitVoucherDefault;
|
|
}
|
|
if ("subscriptionMonthlyPriceMinor" in body) {
|
|
const p = body.subscriptionMonthlyPriceMinor;
|
|
if (p != null && (!Number.isInteger(p) || p < 0)) {
|
|
return reply.code(400).send({ error: "subscriptionMonthlyPriceMinor must be a non-negative integer or null" });
|
|
}
|
|
patch.subscriptionMonthlyPriceMinor = p ?? null;
|
|
}
|
|
for (const f of TEXT_FIELDS) {
|
|
if (f in body) patch[f] = normText(body[f]);
|
|
}
|
|
|
|
const existing = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
|
const updatedAt = new Date().toISOString();
|
|
if (existing) {
|
|
db.update(siteConfig).set({ ...patch, updatedAt }).where(eq(siteConfig.id, 1)).run();
|
|
} else {
|
|
db.insert(siteConfig).values({ id: 1, ...patch, updatedAt }).run();
|
|
}
|
|
const row = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
|
return toSiteConfig(row);
|
|
});
|
|
}
|