Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes. Co-authored-by: Cursor <cursoragent@cursor.com>
189 lines
5.8 KiB
Python
189 lines
5.8 KiB
Python
"""Admin API for visual feature/site configuration."""
|
|
|
|
import base64
|
|
import json
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
from fastapi import APIRouter, Header
|
|
from fastapi.responses import JSONResponse
|
|
from pydantic import BaseModel
|
|
|
|
from ..config import get_settings
|
|
from ..db import get_pb
|
|
from ..services.payment_providers import get_payment_provider, upsert_payment_provider
|
|
|
|
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
|
|
|
EBOOK_ROOT = Path(__file__).resolve().parents[3] # .../ebook
|
|
FEATURES_FILE = EBOOK_ROOT / "content" / "features.json"
|
|
SITE_FILE = EBOOK_ROOT / "content" / "site.json"
|
|
BACKEND_ENV_FILE = EBOOK_ROOT / "backend" / ".env"
|
|
|
|
|
|
def _check_auth(authorization: str | None) -> bool:
|
|
if not authorization or not authorization.startswith("Basic "):
|
|
return False
|
|
try:
|
|
raw = base64.b64decode(authorization.split(" ", 1)[1]).decode("utf-8")
|
|
username, password = raw.split(":", 1)
|
|
except Exception:
|
|
return False
|
|
s = get_settings()
|
|
return username == s.admin_username and password == s.admin_password
|
|
|
|
|
|
def _read_json(path: Path) -> dict:
|
|
if not path.exists():
|
|
return {}
|
|
return json.loads(path.read_text(encoding="utf-8"))
|
|
|
|
|
|
def _write_json(path: Path, data: dict) -> None:
|
|
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
|
|
def _read_env_file(path: Path) -> dict[str, str]:
|
|
if not path.exists():
|
|
return {}
|
|
out: dict[str, str] = {}
|
|
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
line = raw.strip()
|
|
if not line or line.startswith("#"):
|
|
continue
|
|
if "=" not in line:
|
|
continue
|
|
k, v = line.split("=", 1)
|
|
out[k.strip()] = v.strip()
|
|
return out
|
|
|
|
|
|
def _write_env_file(path: Path, updates: dict[str, str]) -> None:
|
|
current = _read_env_file(path)
|
|
for k, v in updates.items():
|
|
# allow setting to empty string; do not allow deleting for safety
|
|
current[k] = v
|
|
lines = [f"{k}={v}" for k, v in sorted(current.items())]
|
|
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
|
|
|
|
class AdminConfigPayload(BaseModel):
|
|
features: dict
|
|
site: dict
|
|
|
|
|
|
class PaymentProviderPayload(BaseModel):
|
|
secrets: dict = {}
|
|
config: dict = {}
|
|
|
|
|
|
@router.post("/login")
|
|
async def admin_login(authorization: str | None = Header(None)):
|
|
if not _check_auth(authorization):
|
|
return JSONResponse({"ok": False, "error": "invalid credentials"}, 401)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.get("/config")
|
|
async def get_config(authorization: str | None = Header(None)):
|
|
if not _check_auth(authorization):
|
|
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
|
return {
|
|
"ok": True,
|
|
"features": _read_json(FEATURES_FILE),
|
|
"site": _read_json(SITE_FILE),
|
|
}
|
|
|
|
|
|
@router.put("/config")
|
|
async def save_config(payload: AdminConfigPayload, authorization: str | None = Header(None)):
|
|
if not _check_auth(authorization):
|
|
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
|
_write_json(FEATURES_FILE, payload.features)
|
|
_write_json(SITE_FILE, payload.site)
|
|
subprocess.Popen(
|
|
["bash", "-lc", "sleep 1 && systemctl restart ebook-api >/dev/null 2>&1 || true"],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
return {"ok": True, "message": "saved; backend reload scheduled"}
|
|
|
|
|
|
@router.get("/payment-providers")
|
|
async def list_payment_providers(authorization: str | None = Header(None)):
|
|
if not _check_auth(authorization):
|
|
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
|
|
|
# Supported providers
|
|
providers = ["creem", "nowpayments"]
|
|
return {
|
|
"ok": True,
|
|
"providers": {p: get_payment_provider(p) for p in providers},
|
|
}
|
|
|
|
|
|
@router.put("/payment-providers/{provider}")
|
|
async def save_payment_provider(
|
|
provider: str,
|
|
payload: PaymentProviderPayload,
|
|
authorization: str | None = Header(None),
|
|
):
|
|
if not _check_auth(authorization):
|
|
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
|
|
|
if provider not in ["creem", "nowpayments"]:
|
|
return JSONResponse({"ok": False, "error": "unsupported provider"}, 400)
|
|
|
|
upsert_payment_provider(provider, payload.secrets or {}, payload.config or {})
|
|
|
|
# reload backend so services pick up new keys
|
|
subprocess.Popen(
|
|
["bash", "-lc", "sleep 1 && systemctl restart ebook-api >/dev/null 2>&1 || true"],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
return {"ok": True}
|
|
|
|
|
|
@router.get("/orders")
|
|
async def list_orders(
|
|
authorization: str | None = Header(None),
|
|
provider: str | None = None,
|
|
status: str | None = None,
|
|
limit: int = 20,
|
|
):
|
|
if not _check_auth(authorization):
|
|
return JSONResponse({"ok": False, "error": "unauthorized"}, 401)
|
|
|
|
pb = get_pb()
|
|
# Avoid PocketBase sort/filter quirks; fetch first page and filter in Python.
|
|
recs = pb.collection("orders").get_list(1, 50)
|
|
all_items = [
|
|
{
|
|
"id": r.id,
|
|
"provider": r.provider,
|
|
"provider_id": r.provider_id,
|
|
"email": r.email,
|
|
"amount_usd": r.amount_usd,
|
|
"currency": r.currency,
|
|
"status": r.status,
|
|
"invoice_url": r.invoice_url,
|
|
"created": r.get_created(),
|
|
}
|
|
for r in (recs.items or [])
|
|
]
|
|
|
|
def match(item: dict):
|
|
if provider and item.get("provider") != provider:
|
|
return False
|
|
if status and item.get("status") != status:
|
|
return False
|
|
return True
|
|
|
|
items = [it for it in all_items if match(it)]
|
|
# If created exists, sort desc; otherwise keep original order.
|
|
try:
|
|
items.sort(key=lambda x: x.get("created") or 0, reverse=True)
|
|
except Exception:
|
|
pass
|
|
return {"ok": True, "items": items[: max(1, min(limit, 50))]}
|