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.
This commit is contained in:
+85
-14
@@ -17,7 +17,7 @@ from pydantic import BaseModel
|
||||
|
||||
from . import csms, relays, store, users
|
||||
from .config import CONFIG, save
|
||||
from .journal import read_events, read_seen
|
||||
from .journal import now, read_events
|
||||
from ocpp.v16 import call
|
||||
|
||||
log = logging.getLogger("api")
|
||||
@@ -110,16 +110,18 @@ async def me(user: dict = Depends(current_user)):
|
||||
# ---- status & journals ----
|
||||
@router.get("/status")
|
||||
async def api_status(user: dict = Depends(current_user)):
|
||||
is_admin = users.allowed(user["scopes"], "admin")
|
||||
return {
|
||||
"mode": "learn" if CONFIG.get("learn_mode") else "enforce",
|
||||
"connected": {
|
||||
cp_id: getattr(cp, "boot_info", None) for cp_id, cp in csms.CONNECTED.items()
|
||||
},
|
||||
"connectors": {f"{cp_id}/{conn}": s for (cp_id, conn), s in csms.CONNECTORS.items()},
|
||||
"active_transactions": csms.ACTIVE_TX,
|
||||
"recent_auth_events": list(csms.AUTH_EVENTS),
|
||||
"recent_auth_events": list(csms.AUTH_EVENTS) if is_admin else [],
|
||||
"relays": _visible_relays(user),
|
||||
"chargers": CONFIG["chargers"], # display labels for the panel
|
||||
# the admin's notification bell: unknown cards awaiting a decision
|
||||
"pending_cards": len(CONFIG["pending_cards"]) if is_admin else 0,
|
||||
}
|
||||
|
||||
|
||||
@@ -238,11 +240,7 @@ class AllowlistEntry(BaseModel):
|
||||
@router.get("/allowlist")
|
||||
async def allowlist_get(user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
return {
|
||||
"learn_mode": CONFIG["learn_mode"],
|
||||
"authorized": CONFIG["authorized"],
|
||||
"seen": read_seen(),
|
||||
}
|
||||
return {"authorized": CONFIG["authorized"]}
|
||||
|
||||
|
||||
@router.put("/allowlist/{id_tag}")
|
||||
@@ -267,14 +265,87 @@ async def allowlist_delete(id_tag: str, user: dict = Depends(current_user)):
|
||||
return {"authorized": CONFIG["authorized"]}
|
||||
|
||||
|
||||
@router.post("/mode")
|
||||
async def set_mode(learn: bool, user: dict = Depends(current_user)):
|
||||
"""Flip learn mode at runtime — no restart needed; decide() reads CONFIG live."""
|
||||
# ---- pending cards: unknown taps awaiting the admin's decision ----
|
||||
class ApproveBody(BaseModel):
|
||||
name: str
|
||||
user: Optional[str] = None # link the card to its owner right here
|
||||
guns: Optional[list[str]] = None
|
||||
kind: str = "card"
|
||||
|
||||
|
||||
@router.get("/cards/pending")
|
||||
async def pending_list(user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
CONFIG["learn_mode"] = learn
|
||||
return CONFIG["pending_cards"]
|
||||
|
||||
|
||||
@router.post("/cards/pending/{id_tag}/approve")
|
||||
async def pending_approve(id_tag: str, body: ApproveBody,
|
||||
user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
if id_tag not in CONFIG["pending_cards"]:
|
||||
raise HTTPException(404, f"{id_tag!r} is not pending")
|
||||
if body.user is not None and body.user not in CONFIG["users"]:
|
||||
raise HTTPException(400, f"cannot link card to unknown user {body.user!r}")
|
||||
CONFIG["pending_cards"].pop(id_tag)
|
||||
CONFIG["authorized"][id_tag] = body.model_dump(exclude_none=True)
|
||||
save()
|
||||
log.warning("mode changed: %s", "LEARN" if learn else "ENFORCE")
|
||||
return {"mode": "learn" if learn else "enforce"}
|
||||
log.info("pending card %r APPROVED by %r as %r (user=%s)",
|
||||
id_tag, user["name"], body.name, body.user)
|
||||
return {"approved": id_tag, "authorized": CONFIG["authorized"]}
|
||||
|
||||
|
||||
@router.post("/cards/pending/{id_tag}/reject")
|
||||
async def pending_reject(id_tag: str, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
meta = CONFIG["pending_cards"].pop(id_tag, None)
|
||||
if meta is None:
|
||||
raise HTTPException(404, f"{id_tag!r} is not pending")
|
||||
CONFIG["denied_cards"][id_tag] = {
|
||||
"rejected_at": now(), "by": user["name"],
|
||||
**{k: meta[k] for k in ("first_seen", "count") if k in meta},
|
||||
}
|
||||
save()
|
||||
log.warning("pending card %r REJECTED by %r", id_tag, user["name"])
|
||||
return {"rejected": id_tag}
|
||||
|
||||
|
||||
@router.get("/cards/denied")
|
||||
async def denied_list(user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
return CONFIG["denied_cards"]
|
||||
|
||||
|
||||
@router.delete("/cards/denied/{id_tag}")
|
||||
async def denied_delete(id_tag: str, user: dict = Depends(current_user)):
|
||||
"""Un-reject: the card pends again on its next tap."""
|
||||
need(user, "admin")
|
||||
if CONFIG["denied_cards"].pop(id_tag, None) is None:
|
||||
raise HTTPException(404, f"{id_tag!r} is not denied")
|
||||
save()
|
||||
return {"undenied": id_tag}
|
||||
|
||||
|
||||
# ---- permission catalog: what CAN be granted (drives the UI matrix) ----
|
||||
@router.get("/permissions")
|
||||
async def permissions_catalog(user: dict = Depends(current_user)):
|
||||
"""Everything a scope could refer to, so the panel renders checkboxes
|
||||
instead of asking admins to type raw scope strings."""
|
||||
need(user, "admin")
|
||||
chargers = {}
|
||||
for cp_id, meta in CONFIG["chargers"].items():
|
||||
chargers[cp_id] = {"label": meta.get("label", cp_id),
|
||||
"guns": dict(meta.get("guns", {}))}
|
||||
# chargers that connected but were never given display labels
|
||||
for (cp_id, conn) in csms.CONNECTORS:
|
||||
if conn > 0:
|
||||
entry = chargers.setdefault(cp_id, {"label": cp_id, "guns": {}})
|
||||
entry["guns"].setdefault(str(conn), f"Gun {conn}")
|
||||
return {
|
||||
"chargers": chargers, # scope per gun: charger:<cp>:<conn>
|
||||
"relays": relays.configured(), # scope per relay: relay:<name>
|
||||
"admin_scope": "admin",
|
||||
}
|
||||
|
||||
|
||||
# ---- user management (admin) ----
|
||||
|
||||
Reference in New Issue
Block a user