Files
charging_station/backend/routes.py
T
julian d7b17d9cb2 feat(backend): production backend — CSMS, multi-user auth, relays, session store, web panel
One FastAPI process on port 9000 (the charger's hardcoded URL), replacing
discovering/station.py for production:

- csms.py: OCPP 1.6J handlers ported from the proven discovery code; the
  decide() gate now supports per-gun RFID restriction ("connectors": [2])
  enforced at StartTransaction
- users.py: username/password auth (PBKDF2), stateless HMAC sessions
  (cookie + bearer, 30 days), fnmatch permission scopes
  (charger:<cp>:<gun>, relay:<name>, admin) and a user CLI
- relays.py: local tinytuya control of the SmartLife/Tuya WiFi relays
  (no cloud; needs one-time id/local-key extraction via tinytuya wizard)
- store.py: SQLite consumption tracking — who charged, when, how many kWh,
  per-minute energy/power/SoC samples; tx ids survive restarts
- routes.py: /api/* with per-scope checks, allowlist/user CRUD, runtime
  learn-mode flip, session history with visibility rules
- static/: self-contained vanilla-JS PWA — login, per-gun start/stop gated
  by scope + gun readiness, relay toggles, history, admin tab

config.json (password hashes, session secret, Tuya keys) and sessions.db
are gitignored; config.example.json documents the shape. Covered by a
37-check smoke test incl. a fake charge point over the real WS route.
2026-07-11 18:58:09 +02:00

340 lines
12 KiB
Python

"""REST API — everything under /api/*, for the web panel (and curl).
Authorization model (see backend/users.py):
* POST /api/login {username, password} -> HMAC session token, set as an
HttpOnly cookie AND returned in the body (usable as a Bearer token).
* Every endpoint resolves the caller to a user and checks a permission
scope: charger:<cp>:<gun>, relay:<name>, or admin (implies everything).
* With ZERO users configured the API is open (anonymous admin) so nothing
breaks before the first `python -m backend.users add` — main.py warns.
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel
from . import csms, relays, store, users
from .config import CONFIG, save
from .journal import read_events, read_seen
from ocpp.v16 import call
log = logging.getLogger("api")
SESSION_COOKIE = "session"
def current_user(request: Request) -> dict:
"""Resolve the session cookie or Bearer token to a user dict."""
if not CONFIG["users"]:
return {"name": "anonymous", "scopes": ["admin"], "id_tag": "app-remote"}
token = request.cookies.get(SESSION_COOKIE) or (
request.headers.get("authorization") or ""
).removeprefix("Bearer ").strip()
username = users.verify_session(token) if token else None
if username is None:
raise HTTPException(401, "not logged in (or session expired)")
return {"name": username, **CONFIG["users"][username]}
def need(user: dict, scope: str) -> None:
if not users.allowed(user["scopes"], scope):
raise HTTPException(403, f"user {user['name']!r} lacks permission {scope!r}")
router = APIRouter(prefix="/api")
def _cp(cp_id: Optional[str]) -> csms.ChargePoint:
try:
return csms.pick_cp(cp_id)
except KeyError as exc:
raise HTTPException(409, str(exc.args[0]))
async def _ocpp(coro):
"""Run an OCPP call for an HTTP handler, mapping failures to HTTP errors."""
try:
return await coro
except HTTPException:
raise
except Exception as exc:
raise HTTPException(502, f"OCPP call failed: {exc!r}")
def _visible_relays(user: dict) -> dict:
return {
name: info
for name, info in relays.configured().items()
if users.allowed(user["scopes"], f"relay:{name}")
}
# ---- login / identity ----
class LoginBody(BaseModel):
username: str
password: str
@router.post("/login")
async def login(body: LoginBody, response: Response):
entry = CONFIG["users"].get(body.username)
if not CONFIG["users"]:
raise HTTPException(409, "no users configured — the API is open; log in is pointless "
"until `python -m backend.users add` creates one")
if entry is None or not users.verify_password(body.password, entry.get("password", "")):
log.warning("failed login for %r", body.username)
raise HTTPException(401, "wrong username or password")
token = users.mint_session(body.username)
response.set_cookie(
SESSION_COOKIE, token, max_age=users.SESSION_TTL,
httponly=True, samesite="lax", # no `secure`: plain http inside NetBird
)
log.info("login: %r", body.username)
return {"token": token, "user": users.public_view(body.username, entry)}
@router.post("/logout")
async def logout(response: Response):
# sessions are stateless — logout just clears the cookie on this client
response.delete_cookie(SESSION_COOKIE)
return {"logged_out": True}
@router.get("/me")
async def me(user: dict = Depends(current_user)):
return users.public_view(user["name"], user)
# ---- status & journals ----
@router.get("/status")
async def api_status(user: dict = Depends(current_user)):
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),
"relays": _visible_relays(user),
}
@router.get("/events")
async def api_events(limit: int = 100, event: Optional[str] = None,
user: dict = Depends(current_user)):
need(user, "admin")
return read_events(limit=limit, event=event)
# ---- charger control (scope: charger:<cp>:<gun>) ----
@router.post("/charger/start")
async def charger_start(connector: int = 1, cp: Optional[str] = None,
user: dict = Depends(current_user)):
target = _cp(cp)
need(user, f"charger:{target.id}:{connector}")
# remote starts run under the caller's own idTag so sessions are attributable
id_tag = user.get("id_tag") or f"app-{user['name']}"
if id_tag not in CONFIG["authorized"]:
CONFIG["authorized"][id_tag] = {"name": f"app token of {user['name']}", "kind": "app"}
save()
status = await _ocpp(csms.remote_start(target.id, id_tag, connector))
return {"remote_start": status, "id_tag": id_tag}
@router.post("/charger/stop")
@router.post("/charger/stop/{tx}")
async def charger_stop(tx: Optional[int] = None, user: dict = Depends(current_user)):
if tx is None:
if len(csms.ACTIVE_TX) != 1:
raise HTTPException(409, f"specify /stop/<tx>; active: {list(csms.ACTIVE_TX)}")
tx = next(iter(csms.ACTIVE_TX))
info = csms.ACTIVE_TX.get(tx) or store.open_session(tx)
if info is None:
raise HTTPException(409, f"no active transaction {tx}")
need(user, f"charger:{info['cp']}:{info['connector']}")
status = await _ocpp(csms.remote_stop(tx))
return {"remote_stop": status, "transaction": tx}
@router.post("/charger/unlock/{connector}")
async def charger_unlock(connector: int, cp: Optional[str] = None,
user: dict = Depends(current_user)):
target = _cp(cp)
need(user, f"charger:{target.id}:{connector}")
resp = await _ocpp(target.call(call.UnlockConnector(connector_id=connector)))
return {"unlock": connector, "status": resp.status}
@router.post("/charger/trigger/{what}")
async def charger_trigger(what: str, connector: Optional[int] = None,
cp: Optional[str] = None, user: dict = Depends(current_user)):
need(user, "admin")
if what not in csms.TRIGGERABLE:
raise HTTPException(400, f"unknown trigger {what!r}; options: {list(csms.TRIGGERABLE)}")
payload = call.TriggerMessage(
requested_message=csms.TRIGGERABLE[what], connector_id=connector
)
resp = await _ocpp(_cp(cp).call(payload))
return {"trigger": what, "status": resp.status}
@router.post("/charger/setconfig")
async def charger_setconfig(key: str, value: str, cp: Optional[str] = None,
user: dict = Depends(current_user)):
need(user, "admin")
resp = await _ocpp(_cp(cp).call(call.ChangeConfiguration(key=key, value=value)))
return {"key": key, "value": value, "status": resp.status}
@router.post("/charger/probe")
async def charger_probe(cp: Optional[str] = None, user: dict = Depends(current_user)):
need(user, "admin")
return await _ocpp(csms.interrogate(_cp(cp)))
# ---- 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']}")
)
@router.get("/sessions")
async def sessions_list(limit: int = 50, cp: Optional[str] = None,
connector: Optional[int] = None,
user: dict = Depends(current_user)):
rows = store.query_sessions(limit=limit, cp=cp, connector=connector)
return [s for s in rows if _may_see_session(user, s)]
@router.get("/sessions/{tx}/samples")
async def session_samples(tx: int, user: dict = Depends(current_user)):
session = store.get_session(tx)
if session is None:
raise HTTPException(404, f"no session {tx}")
if not _may_see_session(user, session):
raise HTTPException(403, f"user {user['name']!r} may not view session {tx}")
return {"session": session, "samples": store.samples_for(tx)}
# ---- 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
@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(),
}
@router.put("/allowlist/{id_tag}")
async def allowlist_put(id_tag: str, entry: AllowlistEntry,
user: dict = Depends(current_user)):
need(user, "admin")
CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True)
save()
log.info("allowlist: added/updated %r (%s)", id_tag, entry.name)
return {"authorized": CONFIG["authorized"]}
@router.delete("/allowlist/{id_tag}")
async def allowlist_delete(id_tag: str, user: dict = Depends(current_user)):
need(user, "admin")
if CONFIG["authorized"].pop(id_tag, None) is None:
raise HTTPException(404, f"idTag {id_tag!r} is not in the allowlist")
save()
log.info("allowlist: removed %r", id_tag)
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."""
need(user, "admin")
CONFIG["learn_mode"] = learn
save()
log.warning("mode changed: %s", "LEARN" if learn else "ENFORCE")
return {"mode": "learn" if learn else "enforce"}
# ---- user management (admin) ----
class UserBody(BaseModel):
password: Optional[str] = None
scopes: Optional[list[str]] = None
@router.get("/users")
async def users_list(user: dict = Depends(current_user)):
need(user, "admin")
return [users.public_view(name, u) for name, u in CONFIG["users"].items()]
@router.put("/users/{name}")
async def users_put(name: str, body: UserBody, user: dict = Depends(current_user)):
need(user, "admin")
try:
updated = users.set_user(name, password=body.password, scopes=body.scopes)
except ValueError as exc:
raise HTTPException(400, str(exc))
log.info("users: %r set by %r (scopes=%s)", name, user["name"], updated["scopes"])
return users.public_view(name, updated)
@router.delete("/users/{name}")
async def users_delete(name: str, user: dict = Depends(current_user)):
need(user, "admin")
if name == user["name"]:
raise HTTPException(400, "refusing to delete the account you are logged in as")
try:
users.remove_user(name)
except KeyError:
raise HTTPException(404, f"no user {name!r}")
log.info("users: %r removed by %r", name, user["name"])
return {"removed": name}
# ---- relays (scope: relay:<name>) ----
@router.get("/relays")
async def relays_list(live: bool = False, user: dict = Depends(current_user)):
"""Relays the caller may control; ?live=true polls each for its actual state."""
visible = _visible_relays(user)
if not live:
return visible
polled = await relays.status_all()
return {name: polled[name] for name in visible if name in polled}
@router.get("/relays/{name}")
async def relay_status(name: str, user: dict = Depends(current_user)):
need(user, f"relay:{name}")
try:
return await relays.status(name)
except relays.RelayError as exc:
raise HTTPException(502, str(exc))
@router.post("/relays/{name}/{verb}")
async def relay_switch(name: str, verb: str, user: dict = Depends(current_user)):
need(user, f"relay:{name}")
actions = {"on": True, "off": False}
try:
if verb == "toggle":
return await relays.toggle(name)
if verb in actions:
return await relays.switch(name, actions[verb])
except relays.RelayError as exc:
raise HTTPException(502, str(exc))
raise HTTPException(400, f"unknown verb {verb!r}; use on, off or toggle")