Spaces:
Running
Running
File size: 5,748 Bytes
052adbf 9aaa92e 052adbf 9aaa92e 052adbf 9aaa92e 052adbf 9aaa92e 052adbf 811afbe 052adbf 811afbe 052adbf 811afbe 052adbf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | """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]
|