From d6312d88131c8ccdb998881ecf2d412742d5cc9e Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 18 Jun 2026 19:04:07 +0800 Subject: [PATCH] feat: expand license admin dashboard --- license_server/api.py | 137 +++++++++++++++++++++++++------ license_server/core.py | 105 +++++++++++++++++++++++ tests/test_license_server_api.py | 27 ++++++ 3 files changed, 244 insertions(+), 25 deletions(-) diff --git a/license_server/api.py b/license_server/api.py index efc67bd..9d1f9ed 100644 --- a/license_server/api.py +++ b/license_server/api.py @@ -80,9 +80,42 @@ def _admin_forbidden() -> HTMLResponse: return HTMLResponse("

403

需要管理员 token。

", status_code=403) -def _admin_page(token: str, message: str = "", cards: list[str] | None = None) -> HTMLResponse: +def _admin_page( + service: LicenseService, + token: str, + message: str = "", + cards: list[str] | None = None, +) -> HTMLResponse: token_attr = escape(token, quote=True) - rows = "".join(f"
  • {escape(card)}
  • " for card in (cards or [])) + stats = service.stats() + card_rows = service.list_cards(limit=50) + audit_rows = service.audit_logs(limit=30) + created_rows = "".join( + f"
  • {escape(card)}
  • " for card in (cards or []) + ) + table_rows = "".join( + "" + f"#{row.id}" + f"{escape(row.code_hint)}" + f"{escape(row.status)}" + f"{row.days}" + f"{row.activation_count}/{row.max_devices}" + f"{escape(row.customer)}" + f"{escape(row.created_at)}" + f"{escape(row.last_seen_at)}" + "" + for row in card_rows + ) + audit_html = "".join( + "" + f"{escape(row.created_at)}" + f"{escape(row.action)}" + f"{escape(row.code_hint)}" + f"{escape(row.machine_fingerprint[:16])}" + f"{escape(row.reason)}" + "" + for row in audit_rows + ) message_html = f"

    {escape(message)}

    " if message else "" html = f""" @@ -90,43 +123,91 @@ def _admin_page(token: str, message: str = "", cards: list[str] | None = None) - 卡密管理 -

    卡密管理

    +
    +
    +
    +

    卡密管理

    +
    生成、禁用、解绑设备,并查看最近激活日志。
    +
    +
    +
    +
    总卡密 {stats["total"]}
    +
    活跃卡密 {stats["active"]}
    +
    已禁用 {stats["revoked"]}
    +
    已绑定设备 {stats["activations"]}
    +
    {message_html}

    生成卡密

    -
    +
    -
      {rows}
    +
      {created_rows}
    +
    +
    +
    +

    禁用卡密

    +
    + + +
    +
    +
    +

    解绑设备

    +
    + + +
    +
    +
    +
    +

    最近卡密

    + + + {table_rows} +
    ID卡密状态天数设备客户创建时间最后在线
    -

    禁用卡密

    -
    - - -
    -
    -
    -

    解绑设备

    -
    - - -
    +

    最近审计日志

    + + + {audit_html} +
    时间动作卡密机器结果
    +
    """ return HTMLResponse(html) @@ -172,7 +253,7 @@ def create_app( 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 "")) + return _admin_page(get_service(), str(request.query_params.get("token") or "")) @app.post("/admin/create") def admin_create( @@ -191,6 +272,7 @@ def create_app( customer=customer, ) return _admin_page( + get_service(), str(request.query_params.get("token") or ""), message=f"已生成 {len(cards)} 个卡密,customer={customer}", cards=[card.code for card in cards], @@ -202,7 +284,11 @@ def create_app( 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) + return _admin_page( + get_service(), + str(request.query_params.get("token") or ""), + message=msg, + ) @app.post("/admin/unbind") def admin_unbind(request: Request, card_key: str = Form("")) -> HTMLResponse: @@ -210,6 +296,7 @@ def create_app( return _admin_forbidden() count = get_service().unbind(card_key) return _admin_page( + get_service(), str(request.query_params.get("token") or ""), message=f"已解绑 {count} 台设备", ) diff --git a/license_server/core.py b/license_server/core.py index 8fed419..6150c8c 100644 --- a/license_server/core.py +++ b/license_server/core.py @@ -47,6 +47,29 @@ class LicenseActionResult: return target +@dataclass(frozen=True) +class LicenseCardSummary: + id: int + code_hint: str + status: str + days: int + max_devices: int + customer: str + created_at: str + revoked_at: str + activation_count: int + last_seen_at: str + + +@dataclass(frozen=True) +class AuditLogEntry: + action: str + code_hint: str + machine_fingerprint: str + reason: str + created_at: str + + def utcnow() -> datetime: return datetime.now(timezone.utc) @@ -217,6 +240,88 @@ class LicenseService: self._audit(conn, "unbind", code, "", str(cur.rowcount)) return int(cur.rowcount or 0) + def stats(self) -> dict[str, int]: + with self._connect() as conn: + row = conn.execute( + """ + SELECT + COUNT(*) AS total, + SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active, + SUM(CASE WHEN status = 'revoked' THEN 1 ELSE 0 END) AS revoked + FROM license_keys + """ + ).fetchone() + activation_row = conn.execute( + "SELECT COUNT(*) AS total FROM activations" + ).fetchone() + return { + "total": int(row["total"] or 0), + "active": int(row["active"] or 0), + "revoked": int(row["revoked"] or 0), + "activations": int(activation_row["total"] or 0), + } + + def list_cards(self, *, limit: int = 50) -> list[LicenseCardSummary]: + with self._connect() as conn: + rows = conn.execute( + """ + SELECT + lk.id, + lk.code_hint, + lk.status, + lk.days, + lk.max_devices, + lk.customer, + lk.created_at, + COALESCE(lk.revoked_at, '') AS revoked_at, + COUNT(a.id) AS activation_count, + COALESCE(MAX(a.last_seen_at), '') AS last_seen_at + FROM license_keys lk + LEFT JOIN activations a ON a.license_id = lk.id + GROUP BY lk.id + ORDER BY lk.id DESC + LIMIT ? + """, + (max(1, int(limit)),), + ).fetchall() + return [ + LicenseCardSummary( + id=int(row["id"]), + code_hint=str(row["code_hint"] or ""), + status=str(row["status"] or ""), + days=int(row["days"] or 0), + max_devices=int(row["max_devices"] or 0), + customer=str(row["customer"] or ""), + created_at=str(row["created_at"] or ""), + revoked_at=str(row["revoked_at"] or ""), + activation_count=int(row["activation_count"] or 0), + last_seen_at=str(row["last_seen_at"] or ""), + ) + for row in rows + ] + + def audit_logs(self, *, limit: int = 30) -> list[AuditLogEntry]: + with self._connect() as conn: + rows = conn.execute( + """ + SELECT action, code_hint, machine_fingerprint, reason, created_at + FROM audit_logs + ORDER BY id DESC + LIMIT ? + """, + (max(1, int(limit)),), + ).fetchall() + return [ + AuditLogEntry( + action=str(row["action"] or ""), + code_hint=str(row["code_hint"] or ""), + machine_fingerprint=str(row["machine_fingerprint"] or ""), + reason=str(row["reason"] or ""), + created_at=str(row["created_at"] or ""), + ) + for row in rows + ] + def activate(self, code: str, *, machine_fingerprint: str) -> LicenseActionResult: raw_machine = str(machine_fingerprint or "").strip() if not raw_machine: diff --git a/tests/test_license_server_api.py b/tests/test_license_server_api.py index 6261c4c..70afff3 100644 --- a/tests/test_license_server_api.py +++ b/tests/test_license_server_api.py @@ -82,3 +82,30 @@ def test_admin_page_can_create_and_revoke_card(tmp_path): assert revoked.status_code == 200 assert "已禁用" in revoked.text assert service.activate(card, machine_fingerprint="machine-a").reason == "revoked" + + +def test_admin_page_shows_stats_cards_and_audit_logs(tmp_path): + from fastapi.testclient import TestClient + + from license_server import api + from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseService + + service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=DEV_PRIVATE_KEY_PEM) + active = service.create_cards(days=5, count=1, customer="active-user")[0] + revoked = service.create_cards(days=2, count=1, customer="revoked-user")[0] + service.activate(active.code, machine_fingerprint="machine-a") + service.revoke(revoked.code) + client = TestClient(api.create_app(service=service, admin_token="secret")) + + resp = client.get("/admin?token=secret") + + assert resp.status_code == 200 + body = resp.text + assert "总卡密" in body + assert "活跃卡密" in body + assert "已绑定设备" in body + assert "active-user" in body + assert "revoked-user" in body + assert "最近审计日志" in body + assert "activate" in body + assert "revoke" in body