feat: add license admin web login

This commit is contained in:
Your Name committed 2026-06-19 01:29:41 +08:00
1 parent a39545ed5d
commit 240f49825f
3 files changed
+145 -17

No files matched your search

+1 -1
View File
@@ -65,7 +65,7 @@ http://127.0.0.1:18100
http://服务器IP:18100/admin
```
浏览器会弹出 Basic 登录框,用户名可随便填,密码填写管理员 token。管理员 token 建议放在服务器:
打开后会显示网页登录页,密码填写管理员 token。管理员 token 建议放在服务器:
```text
/opt/douyin-license-server/secrets/admin_token.txt
+96 -8
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import base64
import hmac
import hashlib
import os
import secrets
import time
@@ -10,7 +11,7 @@ from pathlib import Path
from typing import Any
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from pydantic import BaseModel
from license_server.core import LicenseActionResult, LicenseService
@@ -19,6 +20,8 @@ from license_server.core import LicenseActionResult, LicenseService
RATE_LIMIT_WINDOW_SECONDS = 60
RATE_LIMIT_MAX_REQUESTS = 30
ADMIN_CSRF_COOKIE = "dygj_admin_csrf"
ADMIN_SESSION_COOKIE = "dygj_admin_session"
ADMIN_SESSION_SECONDS = 12 * 60 * 60
class ActivateRequest(BaseModel):
@@ -80,6 +83,11 @@ def _admin_allowed(request: Request, admin_token: str) -> bool:
expected = str(admin_token or "").strip()
if not expected:
return False
session = str(request.cookies.get(ADMIN_SESSION_COOKIE) or "").strip()
sessions: dict[str, float] = request.app.state.admin_sessions
expires_at = sessions.get(_session_hash(session), 0.0)
if session and expires_at > time.time():
return True
auth = str(request.headers.get("authorization") or "").strip()
if hmac.compare_digest(auth, f"Bearer {expected}"):
return True
@@ -95,12 +103,61 @@ def _admin_allowed(request: Request, admin_token: str) -> bool:
return hmac.compare_digest(supplied, expected)
def _session_hash(raw: str) -> str:
return hashlib.sha256(str(raw or "").encode("utf-8")).hexdigest()
def _new_admin_session(request: Request) -> str:
raw = secrets.token_urlsafe(32)
request.app.state.admin_sessions[_session_hash(raw)] = time.time() + ADMIN_SESSION_SECONDS
return raw
def _drop_admin_session(request: Request) -> None:
raw = str(request.cookies.get(ADMIN_SESSION_COOKIE) or "").strip()
if raw:
request.app.state.admin_sessions.pop(_session_hash(raw), None)
def _admin_forbidden() -> HTMLResponse:
return HTMLResponse(
"<h1>403</h1><p>需要管理员登录。</p>",
status_code=403,
headers={"WWW-Authenticate": 'Basic realm="Douyin License Admin"'},
)
return _login_page("请先登录后台。", status_code=403)
def _login_page(message: str = "", *, status_code: int = 200) -> HTMLResponse:
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 {{ margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: "Microsoft YaHei", sans-serif; background: radial-gradient(circle at top left, #dbeafe, transparent 32%), #0f172a; color: #0f172a; }}
main {{ width: min(420px, calc(100vw - 32px)); background: #fff; border-radius: 24px; padding: 28px; box-shadow: 0 28px 80px rgba(15, 23, 42, .35); }}
h1 {{ margin: 0 0 8px; font-size: 28px; }}
p {{ color: #64748b; margin: 0 0 18px; }}
label {{ display: block; color: #475569; font-size: 14px; }}
input {{ width: 100%; box-sizing: border-box; padding: 12px 14px; border: 1px solid #cbd5e1; border-radius: 12px; margin-top: 8px; font-size: 15px; }}
button {{ width: 100%; margin-top: 16px; padding: 12px 16px; cursor: pointer; border: 0; border-radius: 12px; background: #2563eb; color: white; font-weight: 800; font-size: 15px; }}
.msg {{ padding: 10px 12px; background: #fff7ed; border: 1px solid #fed7aa; border-radius: 10px; color: #9a3412; }}
.hint {{ font-size: 13px; color: #64748b; margin-top: 14px; }}
</style>
</head>
<body>
<main>
<h1>卡密后台登录</h1>
<p>请输入服务器管理员 token。</p>
{message_html}
<form method="post" action="/admin/login">
<label>管理员 token
<input name="admin_token" type="password" autocomplete="current-password" autofocus />
</label>
<button type="submit">登录后台</button>
</form>
<div class="hint">登录后会写入 HttpOnly 会话 cookie,不会把 token 放进 URL。</div>
</main>
</body>
</html>"""
return HTMLResponse(html, status_code=status_code)
def _csrf_token(request: Request) -> str:
@@ -214,6 +271,7 @@ def _admin_page(
<h1>卡密管理</h1>
<div class="sub">生成、禁用、解绑设备,并查看最近激活日志。</div>
</div>
<form method="post" action="/admin/logout"><button class="secondary" type="submit">退出登录</button></form>
</header>
<div class="grid">
<div class="stat">总卡密 <b>{stats["total"]}</b></div>
@@ -281,6 +339,7 @@ def create_app(
app.state.license_service = service
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
app.state.rate_limit_buckets = {}
app.state.admin_sessions = {}
def get_service() -> LicenseService:
if app.state.license_service is None:
@@ -314,14 +373,43 @@ def create_app(
)
@app.get("/admin")
def admin(request: Request) -> HTMLResponse:
def admin(request: Request) -> Response:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
return RedirectResponse("/admin/login", status_code=303)
csrf = _csrf_token(request)
response = _admin_page(get_service(), csrf)
response.set_cookie(ADMIN_CSRF_COOKIE, csrf, httponly=True, samesite="lax")
return response
@app.get("/admin/login")
def admin_login_page() -> HTMLResponse:
return _login_page()
@app.post("/admin/login")
def admin_login(request: Request, admin_token: str = Form("")) -> HTMLResponse:
expected = str(app.state.admin_token or "").strip()
supplied = str(admin_token or "").strip()
if not expected or not hmac.compare_digest(supplied, expected):
return _login_page("管理员 token 不正确。", status_code=403)
session = _new_admin_session(request)
response = RedirectResponse("/admin", status_code=303)
response.set_cookie(
ADMIN_SESSION_COOKIE,
session,
max_age=ADMIN_SESSION_SECONDS,
httponly=True,
samesite="lax",
)
return response
@app.post("/admin/logout")
def admin_logout(request: Request) -> RedirectResponse:
_drop_admin_session(request)
response = RedirectResponse("/admin/login", status_code=303)
response.delete_cookie(ADMIN_SESSION_COOKIE)
response.delete_cookie(ADMIN_CSRF_COOKIE)
return response
@app.post("/admin/create")
def admin_create(
request: Request,
+48 -8
View File
@@ -57,9 +57,10 @@ def test_admin_page_requires_token(tmp_path):
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
resp = client.get("/admin")
resp = client.get("/admin", follow_redirects=False)
assert resp.status_code == 403
assert resp.status_code == 303
assert resp.headers["location"] == "/admin/login"
def test_admin_page_can_create_and_revoke_card(tmp_path):
@@ -71,10 +72,10 @@ def test_admin_page_can_create_and_revoke_card(tmp_path):
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
created = client.post(
"/admin/create",
auth=("admin", "secret"),
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
data={"csrf_token": "csrf-token", "days": "8", "count": "1", "customer": "web-admin"},
)
@@ -82,11 +83,11 @@ def test_admin_page_can_create_and_revoke_card(tmp_path):
card = "DG-" + card.strip()
revoked = client.post(
"/admin/revoke",
auth=("admin", "secret"),
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
data={"csrf_token": "csrf-token", "card_key": card},
)
assert login.status_code == 303
assert created.status_code == 200
assert "web-admin" in created.text
assert card.startswith("DG-")
@@ -108,9 +109,11 @@ def test_admin_page_shows_stats_cards_and_audit_logs(tmp_path):
service.activate(active.code, machine_fingerprint="machine-a")
service.revoke(revoked.code)
client = TestClient(api.create_app(service=service, admin_token="secret"))
login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
resp = client.get("/admin", auth=("admin", "secret"))
resp = client.get("/admin")
assert login.status_code == 303
assert resp.status_code == 200
body = resp.text
assert "总卡密" in body
@@ -133,9 +136,10 @@ def test_admin_query_token_is_rejected(tmp_path):
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
resp = client.get("/admin?token=secret")
resp = client.get("/admin?token=secret", follow_redirects=False)
assert resp.status_code == 403
assert resp.status_code == 303
assert resp.headers["location"] == "/admin/login"
def test_admin_create_requires_csrf(tmp_path):
@@ -147,10 +151,10 @@ def test_admin_create_requires_csrf(tmp_path):
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
resp = client.post(
"/admin/create",
auth=("admin", "secret"),
data={"days": "8", "count": "1", "customer": "web-admin"},
)
@@ -158,6 +162,42 @@ def test_admin_create_requires_csrf(tmp_path):
assert "CSRF 校验失败" in resp.text
def test_admin_login_rejects_wrong_token(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
resp = client.post("/admin/login", data={"admin_token": "wrong"})
assert resp.status_code == 403
assert "管理员 token 不正确" in resp.text
def test_admin_logout_clears_session(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
assert client.get("/admin").status_code == 200
logout = client.post("/admin/logout", follow_redirects=False)
after = client.get("/admin", follow_redirects=False)
assert logout.status_code == 303
assert after.status_code == 303
assert after.headers["location"] == "/admin/login"
def test_api_rate_limits_repeated_failed_activation(tmp_path, monkeypatch):
from fastapi.testclient import TestClient