Files
charging_station/backend/routes.py
T
julian 069d544bb5 feat: private session history, own-permissions view, plug-gated start button
- non-admins now see ONLY their own sessions in /api/sessions (own app
  starts + own linked cards); gun scopes grant control, not visibility;
  admins see everything
- Account page shows the logged-in user's permissions in plain words
  (Administrator badge, or the guns/relays they control), built solely
  from data already visible to them
- Start button arms only when the gun reports Preparing (cable in the
  car); idle unplugged gun shows an explanatory hint instead
- keep owner's app rename to 'Art IoT'
- smoke test: 59 checks (gun-scoped user sees no foreign sessions)
2026-07-12 09:04:06 +02:00

485 lines
18 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 now, read_events
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)
class PasswordBody(BaseModel):
current_password: str
new_password: str
@router.post("/me/password")
async def change_own_password(body: PasswordBody, user: dict = Depends(current_user)):
"""Self-service password change — requires the current password.
(Admins can still reset anyone's via PUT /api/users/<name>.)"""
entry = CONFIG["users"].get(user["name"])
if entry is None:
raise HTTPException(409, "no user account — the API is in open mode")
if not users.verify_password(body.current_password, entry.get("password", "")):
raise HTTPException(403, "current password is wrong")
if len(body.new_password) < 4:
raise HTTPException(400, "new password must be at least 4 characters")
users.set_user(user["name"], password=body.new_password)
log.info("password changed by %r", user["name"])
return {"changed": True}
# ---- status & journals ----
@router.get("/status")
async def api_status(user: dict = Depends(current_user)):
is_admin = users.allowed(user["scopes"], "admin")
return {
"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) 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,
}
@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:
"""Transactions are private: admins see everything, everyone else sees
ONLY their own sessions (their app starts + their linked cards). Card
ownership is looked up live, so linking a card to a user retroactively
shows them its history. (Gun scopes grant CONTROL, not visibility —
owner decision 2026-07-12.)"""
if users.allowed(user["scopes"], "admin"):
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")
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
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")
async def allowlist_get(user: dict = Depends(current_user)):
need(user, "admin")
return {"authorized": CONFIG["authorized"]}
@router.put("/allowlist/{id_tag}")
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)
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"]}
# ---- 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")
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.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) ----
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}
# ---- relay & charger registry (admin; how tinytuya wizard results get in) ----
class RelayBody(BaseModel):
id: str # tuya device id (from tinytuya wizard)
key: str # tuya local key (from tinytuya wizard)
ip: str = "auto" # pin the LAN IP once known (faster than discovery)
version: float = 3.3
switch: int = 1
label: Optional[str] = None
@router.put("/relays/{name}")
async def relay_put(name: str, body: RelayBody, user: dict = Depends(current_user)):
need(user, "admin")
entry = body.model_dump()
entry["label"] = entry["label"] or name
CONFIG["relays"][name] = entry
save()
log.info("relays: %r set by %r", name, user["name"])
return {"relays": relays.configured()}
@router.delete("/relays/{name}")
async def relay_delete(name: str, user: dict = Depends(current_user)):
need(user, "admin")
if CONFIG["relays"].pop(name, None) is None:
raise HTTPException(404, f"no relay {name!r}")
save()
return {"relays": relays.configured()}
class ChargerBody(BaseModel):
label: Optional[str] = None
guns: Optional[dict[str, str]] = None # {"1": "Gun 1 · EU (CCS)"}
@router.put("/chargers/{cp_id}")
async def charger_put(cp_id: str, body: ChargerBody, user: dict = Depends(current_user)):
need(user, "admin")
CONFIG["chargers"][cp_id] = body.model_dump(exclude_none=True)
save()
return {"chargers": CONFIG["chargers"]}
# ---- 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")