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
This commit is contained in:
2026-06-19 01:19:28 +02:00
parent d71ba82999
commit d0841c8601
29 changed files with 1301 additions and 104 deletions
+60 -2
View File
@@ -44,16 +44,26 @@ export class ApiError extends Error {
// --- Auth -----------------------------------------------------------------
export type Role = "admin" | "operator" | "cashier" | "readonly";
export type Lang = "sq" | "en";
/** A `resource:action` permission string (the server is the source of truth for
* the full grid; the role composer fetches it via /api/roles). */
export type Permission = string;
export interface SessionUser {
id: string;
username: string;
role: Role;
roleId: string;
roleName: string;
/** The permissions this user's role grants — the UI gates nav/routes on these. */
permissions: Permission[];
/** Preferred UI language (loaded from the server on login). */
language: Lang;
}
/** Does this session grant the permission? Central authz check for the SPA. */
export function can(user: SessionUser | null, perm: Permission): boolean {
return !!user && user.permissions.includes(perm);
}
export function login(username: string, password: string): Promise<SessionUser> {
return apiFetch<SessionUser>("/api/auth/login", {
method: "POST",
@@ -80,6 +90,54 @@ export async function fetchMe(): Promise<SessionUser | null> {
}
}
// --- User & role management (RBAC) ----------------------------------------
export interface ManagedUser {
id: string;
username: string;
roleId: string;
roleName: string;
language: Lang;
createdAt: string;
}
export interface ManagedRole {
id: string;
name: string;
builtin: boolean;
permissions: Permission[];
userCount: number;
}
export function fetchUsers(): Promise<{ users: ManagedUser[] }> {
return apiFetch("/api/users");
}
export function createUser(body: { username: string; password: string; roleId: string }): Promise<ManagedUser> {
return apiFetch("/api/users", { method: "POST", body: JSON.stringify(body) });
}
export function updateUser(id: string, body: { username?: string; roleId?: string }): Promise<ManagedUser> {
return apiFetch(`/api/users/${id}`, { method: "PUT", body: JSON.stringify(body) });
}
export function resetUserPassword(id: string, password: string): Promise<{ ok: boolean }> {
return apiFetch(`/api/users/${id}/password`, { method: "PUT", body: JSON.stringify({ password }) });
}
export function deleteUser(id: string): Promise<{ ok: boolean }> {
return apiFetch(`/api/users/${id}`, { method: "DELETE" });
}
/** Roles + the full permission catalog (for the composer checkbox grid). */
export function fetchRoles(): Promise<{ catalog: Permission[]; roles: ManagedRole[] }> {
return apiFetch("/api/roles");
}
export function createRole(body: { name: string; permissions: Permission[] }): Promise<ManagedRole> {
return apiFetch("/api/roles", { method: "POST", body: JSON.stringify(body) });
}
export function updateRole(id: string, body: { name?: string; permissions?: Permission[] }): Promise<ManagedRole> {
return apiFetch(`/api/roles/${id}`, { method: "PUT", body: JSON.stringify(body) });
}
export function deleteRole(id: string): Promise<{ ok: boolean }> {
return apiFetch(`/api/roles/${id}`, { method: "DELETE" });
}
// --- Device setup ---------------------------------------------------------
export interface ConfigField {