Files
charging_station/frontend/src/pages/Users.tsx
T
julian 75869364b0 feat: React control panel; pending-card review workflow; auth-method audit
Frontend rewrite (frontend/, replacing backend/static/):
- Vite + TypeScript + React 19, React Router 7, zustand, TanStack Query 5
- dev: vite proxy /api -> :9000; prod: npm run build -> dist/, served by
  the backend with SPA fallback
- pages: Control (gun bays w/ scope+readiness-gated start/stop, relays),
  History (who/via/gun/when/duration/kWh audit), Cards (pending review,
  enrolled, rejected), Users (permission checkbox matrix)
- self-contained: fonts bundled, no CDN; light/dark; reduced-motion safe

Backend:
- learn mode removed: unknown cards are always refused and queued in
  pending_cards; admin approves (name + owner + gun restrictions in one
  step) or rejects (denied_cards, silent, un-rejectable); pending count
  rides /api/status as the notification signal
- sessions record the auth method (card tap vs in-app button) for audit
- GET /api/permissions: grantable-permission catalog driving the UI matrix
- SPA static serving with path-traversal guard; 503 hint when not built

Smoke test: 54 checks incl. approve/reject round-trips over a fake charge
point and method audit assertions.
2026-07-11 20:52:20 +02:00

276 lines
8.8 KiB
TypeScript

import { useMemo, useState } from "react";
import { api, isAdmin, scopeAllowed } from "../api";
import { useAction, usePermissions, useUsers } from "../queries";
import { useApp } from "../store";
import type { Me, PermissionCatalog } from "../types";
/** The permission matrix: scopes rendered as checkboxes instead of raw strings. */
interface Matrix {
admin: boolean;
guns: string[]; // "cp:conn"
allRelays: boolean;
relays: string[];
}
function toMatrix(scopes: string[], catalog: PermissionCatalog): Matrix {
const nonAdmin = scopes.filter((s) => s !== "admin" && s !== "*");
const guns: string[] = [];
for (const [cp, meta] of Object.entries(catalog.chargers))
for (const conn of Object.keys(meta.guns))
if (scopeAllowed(nonAdmin, `charger:${cp}:${conn}`)) guns.push(`${cp}:${conn}`);
const allRelays = nonAdmin.includes("relay:*");
const relays = allRelays
? []
: Object.keys(catalog.relays).filter((r) => scopeAllowed(nonAdmin, `relay:${r}`));
return { admin: isAdmin(scopes), guns, allRelays, relays };
}
function toScopes(m: Matrix): string[] {
if (m.admin) return ["admin"];
return [
...m.guns.map((g) => `charger:${g}`),
...(m.allRelays ? ["relay:*"] : m.relays.map((r) => `relay:${r}`)),
];
}
function MatrixEditor({
catalog,
value,
onChange,
}: {
catalog: PermissionCatalog;
value: Matrix;
onChange: (m: Matrix) => void;
}) {
const toggleList = (list: string[], item: string) =>
list.includes(item) ? list.filter((x) => x !== item) : [...list, item];
return (
<div className="matrix">
<label className="check check--strong">
<input
type="checkbox"
checked={value.admin}
onChange={() => onChange({ ...value, admin: !value.admin })}
/>
<span>Administrator — everything, including cards, users and settings</span>
</label>
{!value.admin && (
<>
<div className="matrix__group">
<span className="field__label">Charging guns</span>
{Object.entries(catalog.chargers).map(([cp, meta]) =>
Object.entries(meta.guns).map(([conn, label]) => {
const gun = `${cp}:${conn}`;
return (
<label key={gun} className="check">
<input
type="checkbox"
checked={value.guns.includes(gun)}
onChange={() => onChange({ ...value, guns: toggleList(value.guns, gun) })}
/>
<span>
{meta.label} — {label}
</span>
</label>
);
}),
)}
{!Object.keys(catalog.chargers).length && (
<span className="dim">no chargers known yet</span>
)}
</div>
<div className="matrix__group">
<span className="field__label">Relays</span>
<label className="check">
<input
type="checkbox"
checked={value.allRelays}
onChange={() => onChange({ ...value, allRelays: !value.allRelays })}
/>
<span>All relays (including future ones)</span>
</label>
{!value.allRelays &&
Object.entries(catalog.relays).map(([name, meta]) => (
<label key={name} className="check">
<input
type="checkbox"
checked={value.relays.includes(name)}
onChange={() =>
onChange({ ...value, relays: toggleList(value.relays, name) })
}
/>
<span>{meta.label}</span>
</label>
))}
{!value.allRelays && !Object.keys(catalog.relays).length && (
<span className="dim">no relays registered yet</span>
)}
</div>
</>
)}
</div>
);
}
function UserEditor({
user,
catalog,
onClose,
}: {
user: Me | null; // null = create new
catalog: PermissionCatalog;
onClose: () => void;
}) {
const toast = useApp((s) => s.toast);
const [name, setName] = useState(user?.name ?? "");
const [password, setPassword] = useState("");
const [matrix, setMatrix] = useState<Matrix>(() =>
user ? toMatrix(user.scopes, catalog) : { admin: false, guns: [], allRelays: false, relays: [] },
);
const save = useAction(
() =>
api.put(`/users/${encodeURIComponent(name.trim())}`, {
...(password ? { password } : {}),
scopes: toScopes(matrix),
}),
[["users"]],
() => {
toast(user ? "User updated" : "User created");
onClose();
},
);
return (
<form
className="panel__inset"
onSubmit={(e) => {
e.preventDefault();
save.mutate();
}}
>
<h3>{user ? `Edit ${user.name}` : "New user"}</h3>
<div className="formrow">
<label className="field">
<span>Username</span>
<input
value={name}
onChange={(e) => setName(e.target.value)}
disabled={!!user}
required
placeholder="e.g. maria"
/>
</label>
<label className="field">
<span>{user ? "New password (empty = keep)" : "Password"}</span>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required={!user}
autoComplete="new-password"
/>
</label>
</div>
<MatrixEditor catalog={catalog} value={matrix} onChange={setMatrix} />
<div className="cardform__actions">
<button className="btn btn--primary btn--sm" disabled={save.isPending}>
{user ? "Save changes" : "Create user"}
</button>
<button type="button" className="btn btn--ghost btn--sm" onClick={onClose}>
Cancel
</button>
</div>
</form>
);
}
function describeScopes(scopes: string[], catalog: PermissionCatalog): string {
if (isAdmin(scopes)) return "Administrator";
const m = toMatrix(scopes, catalog);
const parts: string[] = [];
for (const gun of m.guns) {
const [cp, conn] = gun.split(":");
const meta = catalog.chargers[cp];
parts.push(meta ? `${meta.label} ${meta.guns[conn] ?? `gun ${conn}`}` : gun);
}
if (m.allRelays) parts.push("all relays");
else parts.push(...m.relays.map((r) => catalog.relays[r]?.label ?? r));
return parts.length ? parts.join(" · ") : "No permissions";
}
export default function Users() {
const me = useApp((s) => s.me)!;
const toast = useApp((s) => s.toast);
const { data: users } = useUsers();
const { data: catalog } = usePermissions();
const [editing, setEditing] = useState<Me | null | "new">(null);
const remove = useAction(
(name: string) => api.delete(`/users/${encodeURIComponent(name)}`),
[["users"]],
() => toast("User deleted (their sessions are now invalid)"),
);
const sorted = useMemo(
() => [...(users ?? [])].sort((a, b) => a.name.localeCompare(b.name)),
[users],
);
if (!catalog) return <p className="empty">Loading permission catalog…</p>;
return (
<section className="panel">
<header className="panel__head">
<h2>Users</h2>
<button className="btn btn--primary btn--sm" onClick={() => setEditing("new")}>
Add user
</button>
</header>
{!sorted.length && (
<p className="empty">
No users yet — the API is open until the first account exists. Create the admin account
now.
</p>
)}
<div className="table-wrap">
<table className="table">
<tbody>
{sorted.map((u) => (
<tr key={u.name}>
<td className="strong">{u.name}</td>
<td className="dim">{describeScopes(u.scopes, catalog)}</td>
<td className="num">
<button className="btn btn--ghost btn--sm" onClick={() => setEditing(u)}>
Edit
</button>
<button
className="btn btn--ghost btn--sm btn--dangertext"
disabled={u.name === me.name}
title={u.name === me.name ? "You cannot delete your own account" : undefined}
onClick={() => {
if (confirm(`Delete user ${u.name}?`)) remove.mutate(u.name);
}}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{editing !== null && (
<UserEditor
user={editing === "new" ? null : editing}
catalog={catalog}
onClose={() => setEditing(null)}
/>
)}
</section>
);
}