Files
douyi_guaji_main/license_server/api.py
T

221 lines
7.3 KiB
Python

from __future__ import annotations
import os
from html import escape
from pathlib import Path
from typing import Any
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseActionResult, LicenseService
class ActivateRequest(BaseModel):
card_key: str
machine_fingerprint: str
class VerifyRequest(BaseModel):
card_key: str
machine_fingerprint: str
def result_response(result: LicenseActionResult) -> JSONResponse:
body: dict[str, Any] = {
"ok": result.ok,
"reason": result.reason,
"message": result.message,
}
if result.license_doc is not None:
body["license"] = result.license_doc
if result.expires_at is not None:
body["expires_at"] = result.expires_at.isoformat().replace("+00:00", "Z")
status = 200 if result.ok else _status_for_reason(result.reason)
return JSONResponse(body, status_code=status)
def _status_for_reason(reason: str) -> int:
if reason == "not_found":
return 404
if reason in {"revoked", "inactive", "device_limit", "machine_mismatch"}:
return 403
if reason in {"missing_machine", "not_activated"}:
return 400
return 400
def load_private_key_pem() -> bytes:
raw_path = str(os.environ.get("DYGJ_LICENSE_PRIVATE_KEY_PATH") or "").strip()
if raw_path:
return Path(raw_path).read_bytes()
raw_pem = str(os.environ.get("DYGJ_LICENSE_PRIVATE_KEY_PEM") or "").strip()
if raw_pem:
return raw_pem.encode("utf-8")
return DEV_PRIVATE_KEY_PEM
def create_service_from_env() -> LicenseService:
db_path = os.environ.get("DYGJ_LICENSE_DB_PATH") or "/opt/douyin-license-server/data/app.db"
return LicenseService(db_path=db_path, private_key_pem=load_private_key_pem())
def admin_token_from_env() -> str:
return str(os.environ.get("DYGJ_LICENSE_ADMIN_TOKEN") or "").strip()
def _admin_allowed(request: Request, admin_token: str) -> bool:
expected = str(admin_token or "").strip()
if not expected:
return False
supplied = str(request.query_params.get("token") or "").strip()
if supplied == expected:
return True
auth = str(request.headers.get("authorization") or "").strip()
return auth == f"Bearer {expected}"
def _admin_forbidden() -> HTMLResponse:
return HTMLResponse("<h1>403</h1><p>需要管理员 token。</p>", status_code=403)
def _admin_page(token: str, message: str = "", cards: list[str] | None = None) -> HTMLResponse:
token_attr = escape(token, quote=True)
rows = "".join(f"<li><code>{escape(card)}</code></li>" for card in (cards or []))
message_html = f"<p class='msg'>{escape(message)}</p>" if message else ""
html = f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>卡密管理</title>
<style>
body {{ max-width: 920px; margin: 32px auto; font-family: sans-serif; background: #f6f7f9; color: #111827; }}
section {{ background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 18px; margin: 14px 0; }}
label {{ display: block; margin: 8px 0; }}
input {{ padding: 8px 10px; min-width: 260px; }}
button {{ padding: 9px 14px; cursor: pointer; }}
code {{ font-size: 16px; }}
.msg {{ padding: 10px 12px; background: #ecfdf5; border: 1px solid #a7f3d0; border-radius: 8px; }}
</style>
</head>
<body>
<h1>卡密管理</h1>
{message_html}
<section>
<h2>生成卡密</h2>
<form method="post" action="/admin/create?token={token_attr}">
<label>天数 <input name="days" value="30" /></label>
<label>数量 <input name="count" value="1" /></label>
<label>设备数 <input name="max_devices" value="1" /></label>
<label>备注/客户 <input name="customer" value="" /></label>
<button type="submit">生成</button>
</form>
<ul>{rows}</ul>
</section>
<section>
<h2>禁用卡密</h2>
<form method="post" action="/admin/revoke?token={token_attr}">
<label>卡密 <input name="card_key" /></label>
<button type="submit">禁用</button>
</form>
</section>
<section>
<h2>解绑设备</h2>
<form method="post" action="/admin/unbind?token={token_attr}">
<label>卡密 <input name="card_key" /></label>
<button type="submit">解绑</button>
</form>
</section>
</body>
</html>"""
return HTMLResponse(html)
def create_app(
*,
service: LicenseService | None = None,
admin_token: str | None = None,
) -> FastAPI:
app = FastAPI(title="Douyin Guaji License Server")
app.state.license_service = service
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
def get_service() -> LicenseService:
if app.state.license_service is None:
app.state.license_service = create_service_from_env()
return app.state.license_service
@app.get("/api/v1/health")
def health() -> dict[str, Any]:
return {"ok": True, "service": "douyin-license-server"}
@app.post("/api/v1/activate")
def activate(req: ActivateRequest) -> JSONResponse:
return result_response(
get_service().activate(
req.card_key,
machine_fingerprint=req.machine_fingerprint,
)
)
@app.post("/api/v1/verify")
def verify(req: VerifyRequest) -> JSONResponse:
return result_response(
get_service().verify(
req.card_key,
machine_fingerprint=req.machine_fingerprint,
)
)
@app.get("/admin")
def admin(request: Request) -> HTMLResponse:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
return _admin_page(str(request.query_params.get("token") or ""))
@app.post("/admin/create")
def admin_create(
request: Request,
days: int = Form(30),
count: int = Form(1),
max_devices: int = Form(1),
customer: str = Form(""),
) -> HTMLResponse:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
cards = get_service().create_cards(
days=days,
count=count,
max_devices=max_devices,
customer=customer,
)
return _admin_page(
str(request.query_params.get("token") or ""),
message=f"已生成 {len(cards)} 个卡密,customer={customer}",
cards=[card.code for card in cards],
)
@app.post("/admin/revoke")
def admin_revoke(request: Request, card_key: str = Form("")) -> HTMLResponse:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
ok = get_service().revoke(card_key)
msg = "已禁用" if ok else "卡密不存在"
return _admin_page(str(request.query_params.get("token") or ""), message=msg)
@app.post("/admin/unbind")
def admin_unbind(request: Request, card_key: str = Form("")) -> HTMLResponse:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
count = get_service().unbind(card_key)
return _admin_page(
str(request.query_params.get("token") or ""),
message=f"已解绑 {count} 台设备",
)
return app
app = create_app()