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
77 lines
2.4 KiB
JavaScript
77 lines
2.4 KiB
JavaScript
// Seed the first admin user (run once at install).
|
|
//
|
|
// pnpm --filter @parking/server seed-admin
|
|
// -> prompts for a username (default "admin") and password
|
|
//
|
|
// Non-interactive (install scripts):
|
|
// ADMIN_USER=admin ADMIN_PASS='strong-pass' pnpm --filter @parking/server seed-admin
|
|
//
|
|
// A username may also be passed as an argument. Refuses to overwrite an existing
|
|
// user unless FORCE=1 (which resets that user's password).
|
|
|
|
import { randomUUID } from "node:crypto";
|
|
import { createInterface } from "node:readline/promises";
|
|
import { stdin, stdout } from "node:process";
|
|
import { createRequire } from "node:module";
|
|
|
|
const require = createRequire(import.meta.url);
|
|
const bcrypt = require("bcrypt");
|
|
const { createDb, users, eq } = require("@parking/db");
|
|
|
|
const DEFAULT_USERNAME = "admin";
|
|
|
|
// Lazily create one readline interface and read answers sequentially through a
|
|
// single async line iterator — robust whether stdin is a TTY or a pipe (chaining
|
|
// readline/promises question() over a pipe can drop buffered lines).
|
|
let rl = null;
|
|
let lines = null;
|
|
async function prompt(label) {
|
|
if (!rl) {
|
|
rl = createInterface({ input: stdin, output: stdout });
|
|
lines = rl[Symbol.asyncIterator]();
|
|
}
|
|
stdout.write(label);
|
|
const { value } = await lines.next();
|
|
return (value ?? "").trim();
|
|
}
|
|
|
|
// Username: env var > CLI arg > prompt (blank -> default "admin").
|
|
let username = process.env.ADMIN_USER ?? process.argv[2];
|
|
if (!username) {
|
|
username = (await prompt(`Admin username [${DEFAULT_USERNAME}]: `)) || DEFAULT_USERNAME;
|
|
}
|
|
|
|
let password = process.env.ADMIN_PASS;
|
|
if (!password) {
|
|
password = await prompt(`Password for "${username}": `);
|
|
}
|
|
rl?.close();
|
|
|
|
if (!password || password.length < 8) {
|
|
console.error("password must be at least 8 characters");
|
|
process.exit(1);
|
|
}
|
|
|
|
const db = createDb();
|
|
const existing = await db.select().from(users).where(eq(users.username, username)).get();
|
|
if (existing && process.env.FORCE !== "1") {
|
|
console.error(`user "${username}" already exists (set FORCE=1 to reset the password)`);
|
|
process.exit(1);
|
|
}
|
|
|
|
const passwordHash = await bcrypt.hash(password, 12);
|
|
|
|
if (existing) {
|
|
await db.update(users).set({ passwordHash, roleId: "admin" }).where(eq(users.id, existing.id));
|
|
console.log(`reset password for admin "${username}"`);
|
|
} else {
|
|
await db.insert(users).values({
|
|
id: randomUUID(),
|
|
username,
|
|
passwordHash,
|
|
roleId: "admin",
|
|
});
|
|
console.log(`created admin "${username}"`);
|
|
}
|
|
process.exit(0);
|