feat: add password-protected calculation admin
This commit is contained in:
1 parent
0cb5889ce2
commit
3d58b4fc9b
10 files changed
+169
-4
No files matched your search
@@ -15,6 +15,7 @@ class CalculationStore:
|
||||
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
|
||||
self.database_url = database_url or ""
|
||||
self.sqlite_path = Path(sqlite_path) if sqlite_path else None
|
||||
fetch_limit = 5000
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
import psycopg
|
||||
self._psycopg = psycopg
|
||||
@@ -85,3 +86,34 @@ class CalculationStore:
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def list_calculations(self, *, sort_by: str = "kitten_id", descending: bool = True,
|
||||
limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""Return admin rows with safe, application-level sorting by kitten identity."""
|
||||
limit = max(1, min(int(limit), 500))
|
||||
fetch_limit = 5000
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
rows = connection.execute(
|
||||
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at
|
||||
FROM belki_calculations ORDER BY created_at DESC LIMIT %s""", (fetch_limit,)
|
||||
).fetchall()
|
||||
else:
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
rows = connection.execute(
|
||||
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at
|
||||
FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,)
|
||||
).fetchall()
|
||||
records = []
|
||||
for row in rows:
|
||||
input_data = row[4] if isinstance(row[4], dict) else json.loads(row[4])
|
||||
result_data = row[5] if isinstance(row[5], dict) or row[5] is None else json.loads(row[5])
|
||||
records.append({
|
||||
"id": row[0], "actor_id": row[1], "source": row[2], "mode": row[3],
|
||||
"input": input_data, "result": result_data, "message": row[6],
|
||||
"created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7],
|
||||
})
|
||||
if sort_by not in {"kitten_id", "kitten_name"}:
|
||||
sort_by = "kitten_id"
|
||||
records.sort(key=lambda item: (item["input"].get(sort_by) is None, item["input"].get(sort_by, "")),
|
||||
reverse=descending)
|
||||
return records[:limit]
|
||||
+30
-4
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user