Spaces:
Running
Running
Download py/auth.py from eatbackhackathon2026/eatback: direct link, hf CLI and curl.
- Browser
- Download file 5.75 kB
-
https://huggingface.co/spaces/eatbackhackathon2026/eatback/resolve/main/py/auth.py
- Command line
-
hf download hf://spaces/eatbackhackathon2026/eatback/py/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/eatbackhackathon2026/eatback/resolve/main/py/auth.py
5.75 kB
| """PIN sign-in for the school laptop server. | |
| Four roles, each with its own PIN: | |
| admin — ผู้ดูแล / ครูโภชนาการ: every screen; menus, plans, fixes, settings, demo data, backups, PINs | |
| kitchen — แม่ครัว: the kitchen screen and recipes, rounds, weighing, the morning scale check | |
| teacher — ครูประจำชั้น: the teacher screen for the kids' opinions | |
| viewer — ผู้บริหาร: the overview, trends and fixes, read only | |
| With real school data every screen and every read needs a signed-in role (app.SCREENS says which screens | |
| each role opens), and each change needs a role that covers it. The ESP32 boards post readings without one. | |
| PINs are stored as PBKDF2 hashes (never sent to the browser). The first start generates them and the | |
| console prints them once; `python server/pins.py` makes new ones. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import hmac | |
| import json | |
| import secrets | |
| import threading | |
| import time | |
| from db import LOCK, one, run | |
| ROLES = ("admin", "kitchen", "teacher", "viewer") | |
| ROLE_TH = {"admin": "ผู้ดูแล", "kitchen": "แม่ครัว", "teacher": "ครูประจำชั้น", "viewer": "ผู้บริหาร"} | |
| # Who may do what: the coordinator covers every role, the kitchen also taps the kids' answers, the principal only reads. | |
| COVERS = {"admin": {"admin", "kitchen", "teacher", "viewer"}, "kitchen": {"kitchen", "teacher"}, "teacher": {"teacher"}, | |
| "viewer": {"viewer"}} | |
| SESSION_S = 12 * 3600 | |
| COOKIE = "eatback_session" | |
| PIN_KEY = "auth_pins" # settings row, outside DEFAULT_SETTINGS so it is never returned to pages | |
| MAX_TRIES, LOCKOUT_S = 5, 60 # wrong PINs from one client before a short pause | |
| _ROUNDS = 120_000 | |
| _lock = threading.Lock() | |
| _sessions: dict[str, tuple[str, float]] = {} | |
| _failures: dict[str, tuple[int, float]] = {} | |
| def _hash(pin: str, salt: str) -> str: | |
| return hashlib.pbkdf2_hmac("sha256", pin.encode(), bytes.fromhex(salt), _ROUNDS).hex() | |
| def _valid_pin(pin) -> bool: | |
| return isinstance(pin, str) and pin.isdigit() and 4 <= len(pin) <= 8 | |
| def _stored() -> dict: | |
| with LOCK: # the sign-in check runs on request threads outside the handlers' lock | |
| row = one("SELECT value FROM settings WHERE key = ?", PIN_KEY) | |
| return json.loads(row["value"]) if row else {} | |
| def set_pins(pins: dict[str, str]) -> None: | |
| """Replace the PINs for the given roles. PINs are 4–8 digits and must differ between roles.""" | |
| current = _stored() | |
| for role, pin in pins.items(): | |
| if role not in ROLES: | |
| raise ValueError(f"unknown role {role}") | |
| if not _valid_pin(pin): | |
| raise ValueError("PIN ต้องเป็นตัวเลข 4–8 หลัก") | |
| salt = secrets.token_hex(16) | |
| current[role] = {"salt": salt, "hash": _hash(pin, salt)} | |
| for role, pin in pins.items(): | |
| for other in ROLES: | |
| if other != role and other in current and hmac.compare_digest(_hash(pin, current[other]["salt"]), current[other]["hash"]): | |
| raise ValueError("PIN ของแต่ละบทบาทต้องไม่ซ้ำกัน") | |
| run("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", | |
| PIN_KEY, json.dumps(current)) | |
| with _lock: # a changed PIN signs that role out everywhere | |
| for token, (role, _) in list(_sessions.items()): | |
| if role in pins: | |
| _sessions.pop(token, None) | |
| def new_pins(roles=ROLES) -> dict[str, str]: | |
| """Save a random 6-digit PIN for each of these roles. Returns them to print once.""" | |
| while True: | |
| fresh: dict[str, str] = {} | |
| for role in roles: | |
| while True: | |
| pin = f"{secrets.randbelow(10**6):06d}" | |
| if pin not in fresh.values(): | |
| break | |
| fresh[role] = pin | |
| try: | |
| set_pins(fresh) | |
| return fresh | |
| except ValueError: # matched a role this call keeps: draw again | |
| continue | |
| def ensure_pins() -> dict[str, str] | None: | |
| """First start: create a PIN for every role that has none. Returns the new PINs to print once.""" | |
| have = _stored() | |
| missing = [r for r in ROLES if r not in have] | |
| return new_pins(missing) if missing else None | |
| def check_pin(pin, client: str) -> str | None: | |
| """The role whose PIN this is, or None. Repeated wrong PINs from one client are paused.""" | |
| now = time.time() | |
| with _lock: | |
| count, until = _failures.get(client, (0, 0.0)) | |
| if until > now: | |
| raise PermissionError(int(until - now) + 1) | |
| role = None | |
| if _valid_pin(pin): | |
| for r, rec in _stored().items(): | |
| if hmac.compare_digest(_hash(pin, rec["salt"]), rec["hash"]): | |
| role = r | |
| with _lock: | |
| if role: | |
| _failures.pop(client, None) | |
| else: | |
| count += 1 | |
| _failures[client] = (0, now + LOCKOUT_S) if count >= MAX_TRIES else (count, 0.0) | |
| return role | |
| def new_session(role: str) -> str: | |
| token = secrets.token_urlsafe(32) | |
| with _lock: | |
| _sessions[token] = (role, time.time() + SESSION_S) | |
| return token | |
| def session_role(token: str | None) -> str | None: | |
| if not token: | |
| return None | |
| with _lock: | |
| entry = _sessions.get(token) | |
| if entry and entry[1] > time.time(): | |
| return entry[0] | |
| _sessions.pop(token, None) | |
| return None | |
| def end_session(token: str | None) -> None: | |
| with _lock: | |
| _sessions.pop(token or "", None) | |
| def allowed(role: str | None, need: str) -> bool: | |
| return bool(role) and need in COVERS[role] | |