feat: add password-protected calculation admin

This commit is contained in:
nyan404 committed 2026-08-16 15:31:33 +03:00
1 parent 0cb5889ce2
commit 3d58b4fc9b
10 files changed
+169 -4

No files matched your search

+30 -4
View File
@@ -5,13 +5,22 @@ import mimetypes
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import unquote, urlparse
from urllib.parse import parse_qs, unquote, urlparse
from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload
from .belki.history import CalculationStore
ROOT = Path(__file__).resolve().parents[1]
WEB_ROOT = ROOT / "web"
_HISTORY_STORE: CalculationStore | None = None
def history_store() -> CalculationStore:
global _HISTORY_STORE
if _HISTORY_STORE is None:
_HISTORY_STORE = CalculationStore.from_environment()
return _HISTORY_STORE
class Handler(BaseHTTPRequestHandler):
@@ -26,13 +35,30 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(encoded)
def do_GET(self) -> None: # noqa: N802
if self.path in ("/health", "/api/health"):
path = urlparse(self.path).path
if path in ("/health", "/api/health"):
self._json(200, {"status": "ok"})
return
if self.path in ("/", "/calculator.html"):
if path in ("/", "/calculator.html"):
self._file(WEB_ROOT / "calculator.html")
return
requested = unquote(urlparse(self.path).path).lstrip("/")
if path == "/admin":
self._file(WEB_ROOT / "admin.html")
return
if path == "/api/admin/calculations":
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
if not expected:
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
return
if self.headers.get("X-Admin-Password", "") != expected:
self._json(401, {"error": "Неверный пароль"})
return
query = parse_qs(urlparse(self.path).query)
sort_by = query.get("sort", ["kitten_id"])[0]
descending = query.get("direction", ["desc"])[0] != "asc"
self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending)})
return
requested = unquote(path).lstrip("/")
candidate = (WEB_ROOT / requested).resolve()
if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents:
self._file(candidate)