feat: expand license admin dashboard

This commit is contained in:
Your Name committed 2026-06-18 19:04:07 +08:00
1 parent 28709d2d97
commit d6312d8813
3 files changed
+244 -25

No files matched your search

+112 -25
View File
@@ -80,9 +80,42 @@ 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:
def _admin_page(
service: LicenseService,
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 []))
stats = service.stats()
card_rows = service.list_cards(limit=50)
audit_rows = service.audit_logs(limit=30)
created_rows = "".join(
f"<li><code>{escape(card)}</code></li>" for card in (cards or [])
)
table_rows = "".join(
"<tr>"
f"<td>#{row.id}</td>"
f"<td><code>{escape(row.code_hint)}</code></td>"
f"<td><span class='status {escape(row.status)}'>{escape(row.status)}</span></td>"
f"<td>{row.days}</td>"
f"<td>{row.activation_count}/{row.max_devices}</td>"
f"<td>{escape(row.customer)}</td>"
f"<td>{escape(row.created_at)}</td>"
f"<td>{escape(row.last_seen_at)}</td>"
"</tr>"
for row in card_rows
)
audit_html = "".join(
"<tr>"
f"<td>{escape(row.created_at)}</td>"
f"<td>{escape(row.action)}</td>"
f"<td><code>{escape(row.code_hint)}</code></td>"
f"<td><code>{escape(row.machine_fingerprint[:16])}</code></td>"
f"<td>{escape(row.reason)}</td>"
"</tr>"
for row in audit_rows
)
message_html = f"<p class='msg'>{escape(message)}</p>" if message else ""
html = f"""<!doctype html>
<html lang="zh-CN">
@@ -90,43 +123,91 @@ def _admin_page(token: str, message: str = "", cards: list[str] | None = None) -
<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; }}
body {{ margin: 0; font-family: "Microsoft YaHei", sans-serif; background: #eef2f7; color: #111827; }}
main {{ max-width: 1180px; margin: 28px auto; padding: 0 18px 32px; }}
header {{ display: flex; justify-content: space-between; align-items: end; gap: 16px; margin-bottom: 18px; }}
h1 {{ margin: 0; font-size: 30px; }}
h2 {{ margin: 0 0 14px; font-size: 18px; }}
.sub {{ color: #64748b; margin-top: 6px; }}
.grid {{ display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }}
.stat {{ background: linear-gradient(135deg, #0f172a, #1f2937); color: white; border-radius: 16px; padding: 18px; }}
.stat b {{ display: block; font-size: 28px; margin-top: 8px; }}
section {{ background: #fff; border: 1px solid #e5e7eb; border-radius: 16px; padding: 18px; margin: 14px 0; box-shadow: 0 12px 30px rgba(15, 23, 42, .06); }}
form.inline {{ display: grid; grid-template-columns: repeat(5, minmax(120px, 1fr)); gap: 10px; align-items: end; }}
label {{ display: block; color: #475569; font-size: 13px; }}
input {{ width: 100%; box-sizing: border-box; padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 10px; margin-top: 5px; }}
button {{ padding: 10px 16px; cursor: pointer; border: 0; border-radius: 10px; background: #2563eb; color: white; font-weight: 700; }}
button.danger {{ background: #dc2626; }}
button.secondary {{ background: #334155; }}
code {{ font-size: 14px; }}
table {{ width: 100%; border-collapse: collapse; font-size: 14px; }}
th, td {{ text-align: left; padding: 10px; border-bottom: 1px solid #e5e7eb; vertical-align: top; }}
th {{ color: #475569; background: #f8fafc; }}
.status {{ padding: 3px 8px; border-radius: 999px; font-size: 12px; background: #e2e8f0; }}
.status.active {{ background: #dcfce7; color: #166534; }}
.status.revoked {{ background: #fee2e2; color: #991b1b; }}
.msg {{ padding: 10px 12px; background: #ecfdf5; border: 1px solid #a7f3d0; border-radius: 8px; }}
.cards {{ display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }}
@media (max-width: 860px) {{ .grid, .cards, form.inline {{ grid-template-columns: 1fr; }} }}
</style>
</head>
<body>
<h1>卡密管理</h1>
<main>
<header>
<div>
<h1>卡密管理</h1>
<div class="sub">生成、禁用、解绑设备,并查看最近激活日志。</div>
</div>
</header>
<div class="grid">
<div class="stat">总卡密 <b>{stats["total"]}</b></div>
<div class="stat">活跃卡密 <b>{stats["active"]}</b></div>
<div class="stat">已禁用 <b>{stats["revoked"]}</b></div>
<div class="stat">已绑定设备 <b>{stats["activations"]}</b></div>
</div>
{message_html}
<section>
<h2>生成卡密</h2>
<form method="post" action="/admin/create?token={token_attr}">
<form class="inline" 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>
<ul>{created_rows}</ul>
</section>
<div class="cards">
<section>
<h2>禁用卡密</h2>
<form method="post" action="/admin/revoke?token={token_attr}">
<label>卡密 <input name="card_key" placeholder="DG-..." /></label>
<button class="danger" type="submit">禁用</button>
</form>
</section>
<section>
<h2>解绑设备</h2>
<form method="post" action="/admin/unbind?token={token_attr}">
<label>卡密 <input name="card_key" placeholder="DG-..." /></label>
<button class="secondary" type="submit">解绑</button>
</form>
</section>
</div>
<section>
<h2>最近卡密</h2>
<table>
<thead><tr><th>ID</th><th>卡密</th><th>状态</th><th>天数</th><th>设备</th><th>客户</th><th>创建时间</th><th>最后在线</th></tr></thead>
<tbody>{table_rows}</tbody>
</table>
</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>
<h2>最近审计日志</h2>
<table>
<thead><tr><th>时间</th><th>动作</th><th>卡密</th><th>机器</th><th>结果</th></tr></thead>
<tbody>{audit_html}</tbody>
</table>
</section>
</main>
</body>
</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} 台设备",
)
+105
View File
@@ -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:
+27
View File
@@ -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