feat(backend): link cards to users; charger-qualified gun restrictions; config-driven gun labels

- Allowlist entries take "user": <username> — sessions started with that
  card attribute to the person, and the owner sees their card's history
  even without gun-wide permissions (ownership looked up live)
- "guns": ["eu092025:2"] (fnmatch) replaces the charger-blind
  "connectors": [2] restriction — safe with multiple chargers
- New "chargers" config section provides per-charger/per-gun display
  names; the panel no longer hardcodes the Anfu gun labels
- Panel admin tab: owner dropdown + guns field on card entries
- Smoke test: 42 checks, incl. retroactive history visibility after
  linking a card and rejection of links to unknown users
This commit is contained in:
2026-07-11 20:03:36 +02:00
parent 3326c8d16c
commit 70c2fe1210
8 changed files with 85 additions and 39 deletions
+15 -4
View File
@@ -19,14 +19,25 @@
}
},
"authorized": {
"1000000000000000": { "name": "Example RFID card, works on both guns", "kind": "card" },
"1000000000000001": {
"name": "Example RFID card restricted to gun 2",
"1000000000000000": {
"name": "Card linked to a user, works everywhere",
"kind": "card",
"connectors": [2]
"user": "admin-user"
},
"1000000000000001": {
"name": "Card restricted to gun 2 of one charger",
"kind": "card",
"user": "gun1-only-user",
"guns": ["eu092025:2"]
},
"app-remote": { "name": "Web/app remote start token", "kind": "app" }
},
"chargers": {
"eu092025": {
"label": "Anfu 60kW",
"guns": { "1": "Gun 1 · EU (CCS)", "2": "Gun 2 · GB/T" }
}
},
"relays": {
"example-relay": {
"id": "<tuya device id from tinytuya wizard>",
+3 -1
View File
@@ -17,8 +17,10 @@ CONFIG_PATH = HERE / "config.json"
DEFAULTS = {
"learn_mode": True,
"users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...}
"authorized": {}, # idTag -> {"name", "kind": "card|app|car", optional "connectors": [1]}
"authorized": {}, # idTag -> {"name", "kind": "card|app|car",
# optional "user": owner, "guns": ["eu092025:2"]}
"relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"}
"chargers": {}, # cp_id -> {"label", "guns": {"1": "display name", ...}} (UI only)
}
+21 -13
View File
@@ -10,6 +10,7 @@ import asyncio
import json
import logging
from collections import deque
from fnmatch import fnmatch
from typing import Optional
from fastapi import WebSocket, WebSocketDisconnect
@@ -46,21 +47,24 @@ TRIGGERABLE = {
}
def decide(id_tag: str, context: str, connector: Optional[int] = None) -> AuthorizationStatus:
def decide(id_tag: str, context: str, connector: Optional[int] = None,
cp: Optional[str] = None) -> AuthorizationStatus:
"""The one gate every auth method flows through: is this idTag allowed?
An allowlist entry may carry "connectors": [1] to restrict a card to
specific guns. Only StartTransaction knows the connector, so the per-gun
check fires there; a plain Authorize (card tap) still accepts a known card
— which matches this charger, since AuthorizeRemoteTxRequests=false means
An allowlist entry may carry "guns": ["eu092025:2"] to restrict a card to
specific guns of specific chargers (fnmatch patterns, so "eu092025:*"
works). Only StartTransaction knows the connector, so the per-gun check
fires there; a plain Authorize (card tap) still accepts a known card —
which matches this charger, since AuthorizeRemoteTxRequests=false means
StartTransaction is the decisive call anyway.
"""
entry = CONFIG["authorized"].get(id_tag)
known = entry is not None
if known and connector is not None and entry.get("connectors") \
and connector not in entry["connectors"]:
log.warning("[NO] REJECTED idTag=%r (%s) not allowed on connector %s (allowed: %s)",
id_tag, entry.get("name", "?"), connector, entry["connectors"])
gun = f"{cp}:{connector}" if cp and connector is not None else None
if known and gun and entry.get("guns") \
and not any(fnmatch(gun, pat) for pat in entry["guns"]):
log.warning("[NO] REJECTED idTag=%r (%s) not allowed on %s (allowed: %s)",
id_tag, entry.get("name", "?"), gun, entry["guns"])
status = AuthorizationStatus.invalid
elif known:
name = entry.get("name", "?")
@@ -82,10 +86,14 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None) -> Author
def resolve_who(id_tag: str) -> str:
"""Human label for a session: allowlist entry name, username, or the raw tag."""
"""Human label for a session: the card's owning user, the allowlist entry
name, the username behind an app idTag, or the raw tag — in that order."""
entry = CONFIG["authorized"].get(id_tag)
if entry and entry.get("name"):
return entry["name"]
if entry:
if entry.get("user"):
return entry["user"]
if entry.get("name"):
return entry["name"]
for username, user in CONFIG["users"].items():
if user.get("id_tag") == id_tag:
return username
@@ -125,7 +133,7 @@ class ChargePoint(OcppChargePoint):
@on(Action.start_transaction)
async def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs):
status = decide(id_tag, f"StartTransaction (connector {connector_id})",
connector=connector_id)
connector=connector_id, cp=self.id)
if status == AuthorizationStatus.accepted:
_tx_counter["n"] += 1
tx = _tx_counter["n"]
+15 -7
View File
@@ -119,6 +119,7 @@ async def api_status(user: dict = Depends(current_user)):
"active_transactions": csms.ACTIVE_TX,
"recent_auth_events": list(csms.AUTH_EVENTS),
"relays": _visible_relays(user),
"chargers": CONFIG["chargers"], # display labels for the panel
}
@@ -197,11 +198,15 @@ async def charger_probe(cp: Optional[str] = None, user: dict = Depends(current_u
# ---- session history: who charged when and how many kWh ----
def _may_see_session(user: dict, s: dict) -> bool:
"""Own sessions, sessions on guns you control, or everything for admin."""
return (
s["id_tag"] == user.get("id_tag")
or users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}")
)
"""Own sessions (own app starts or own cards), sessions on guns you
control, or everything for admin. Card ownership is looked up live, so
linking a card to a user retroactively shows them its history."""
if users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}"):
return True
if s["id_tag"] == user.get("id_tag"):
return True
entry = CONFIG["authorized"].get(s["id_tag"])
return bool(entry and entry.get("user") == user["name"])
@router.get("/sessions")
@@ -225,8 +230,9 @@ async def session_samples(tx: int, user: dict = Depends(current_user)):
# ---- allowlist management (admin) ----
class AllowlistEntry(BaseModel):
name: str
kind: str = "card" # card | app | car
connectors: Optional[list[int]] = None # e.g. [2] = this card only works on gun 2
kind: str = "card" # card | app | car
user: Optional[str] = None # owning username -> sessions attribute to them
guns: Optional[list[str]] = None # e.g. ["eu092025:2"]; fnmatch, empty = all guns
@router.get("/allowlist")
@@ -243,6 +249,8 @@ async def allowlist_get(user: dict = Depends(current_user)):
async def allowlist_put(id_tag: str, entry: AllowlistEntry,
user: dict = Depends(current_user)):
need(user, "admin")
if entry.user is not None and entry.user not in CONFIG["users"]:
raise HTTPException(400, f"cannot link card to unknown user {entry.user!r}")
CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True)
save()
log.info("allowlist: added/updated %r (%s)", id_tag, entry.name)
+19 -12
View File
@@ -143,22 +143,23 @@
</div>
</div>
<div class="card">
<h2>Allowlist</h2>
<h2>Cards &amp; tags</h2>
<div class="scroll"><table>
<thead><tr><th>idTag</th><th>Name</th><th>Guns</th><th></th></tr></thead>
<thead><tr><th>idTag</th><th>Name</th><th>User</th><th>Guns</th><th></th></tr></thead>
<tbody id="allowlist"></tbody>
</table></div>
<div id="seen-tags"></div>
<form onsubmit="return addAllowlist(event)" style="margin-top:10px">
<div class="row"><input id="a-tag" placeholder="idTag" required></div>
<div class="row">
<input id="a-name" placeholder="Name (e.g. RFID card C)" required>
<input id="a-name" placeholder="Name (e.g. Card blue)" required>
<select id="a-kind" style="width:110px"><option>card</option><option>app</option><option>car</option></select>
</div>
<div class="row">
<input id="a-conn" placeholder="Guns, e.g. 1,2 — empty = all">
<button class="small">Add</button>
<select id="a-user"><option value="">No user linked</option></select>
<input id="a-guns" placeholder="Guns, e.g. eu092025:2 — empty = all">
</div>
<div class="row"><button class="small">Save card</button></div>
</form>
</div>
<div class="card">
@@ -308,8 +309,10 @@ function renderGuns() {
.sort((a, b) => a.conn - b.conn);
if (!conns.length)
html += `<div class="card"><div class="sub">${esc(cp)} connected — no gun status yet</div></div>`;
const cpCfg = (status.chargers || {})[cp] || {};
for (const { conn, st } of conns) {
const gunName = conn === 1 ? "Gun 1 · EU (CCS)" : conn === 2 ? "Gun 2 · GB/T" : `Gun ${conn}`;
let gunName = (cpCfg.guns || {})[conn] || `Gun ${conn}`;
if (cps.length > 1) gunName = `${cpCfg.label || cp} · ${gunName}`;
const active = txByGun[`${cp}/${conn}`];
const may = scopeOk(`charger:${cp}:${conn}`);
const canStart = may && !active && (st === "Preparing" || st === "Available");
@@ -408,22 +411,24 @@ async function loadSessions() {
// ---- admin tab ----
async function loadAdmin() {
try {
const al = await api("/allowlist");
const [al, users] = await Promise.all([api("/allowlist"), api("/users")]);
$("mode-label").textContent = al.learn_mode ? "Learn mode" : "Enforcing allowlist";
$("mode-btn").textContent = al.learn_mode ? "Enforce" : "Back to learn";
$("mode-btn").dataset.learn = al.learn_mode;
$("allowlist").innerHTML = Object.entries(al.authorized).map(([tag, e]) => `<tr>
<td class="sub">${esc(tag)}</td><td>${esc(e.name)}</td>
<td>${e.connectors ? e.connectors.join(",") : "all"}</td>
<td>${e.user ? esc(e.user) : '<span class="sub">—</span>'}</td>
<td class="sub">${e.guns ? esc(e.guns.join(", ")) : "all"}</td>
<td><button class="danger small" onclick="delAllowlist('${esc(tag)}')">&#10005;</button></td>
</tr>`).join("");
$("a-user").innerHTML = `<option value="">No user linked</option>` +
users.map(u => `<option value="${esc(u.name)}">${esc(u.name)}</option>`).join("");
const seen = Object.entries(al.seen || {}).filter(([tag]) => !(tag in al.authorized));
$("seen-tags").innerHTML = seen.length
? `<div class="sub" style="margin-top:8px">Seen but not enrolled:</div>` + seen.map(([tag, s]) =>
`<div class="row" style="padding:4px 0"><div class="grow sub">${esc(tag)} (&times;${s.count})</div>
<button class="small secondary" onclick="$('a-tag').value='${esc(tag)}';$('a-name').focus()">Enroll</button></div>`).join("")
: "";
const users = await api("/users");
$("users").innerHTML = users.map(u => `<tr>
<td>${esc(u.name)}</td><td class="sub">${esc(u.scopes.join(" "))}</td>
<td><button class="danger small" onclick="delUser('${esc(u.name)}')">&#10005;</button></td>
@@ -441,12 +446,14 @@ async function toggleMode() {
async function addAllowlist(ev) {
ev.preventDefault();
const body = { name: $("a-name").value.trim(), kind: $("a-kind").value };
const conns = $("a-conn").value.trim();
if (conns) body.connectors = conns.split(",").map(s => +s.trim()).filter(Boolean);
if ($("a-user").value) body.user = $("a-user").value;
const guns = $("a-guns").value.trim();
if (guns) body.guns = guns.split(",").map(s => s.trim()).filter(Boolean);
try {
await api(`/allowlist/${encodeURIComponent($("a-tag").value.trim())}`,
{ method: "PUT", body: JSON.stringify(body) });
$("a-tag").value = $("a-name").value = $("a-conn").value = "";
$("a-tag").value = $("a-name").value = $("a-guns").value = "";
$("a-user").value = "";
loadAdmin();
} catch (e) { toast(e.message); }
return false;