This commit is contained in:
dekun
2026-05-30 12:04:03 +08:00
parent 8ffe46a344
commit 61c4d54305
3 changed files with 88 additions and 25 deletions
+7 -5
View File
@@ -32,6 +32,7 @@ from settings_store import (
from hub_web_auth import ( from hub_web_auth import (
SESSION_COOKIE, SESSION_COOKIE,
SESSION_MAX_AGE_SEC, SESSION_MAX_AGE_SEC,
clear_session_cookie,
cookie_secure_for_request, cookie_secure_for_request,
create_session_token, create_session_token,
embed_allowed, embed_allowed,
@@ -211,8 +212,9 @@ def api_auth_login(body: LoginBody, request: Request):
if not verify_credentials(body.username, body.password): if not verify_credentials(body.username, body.password):
raise HTTPException(status_code=401, detail="用户名或密码错误") raise HTTPException(status_code=401, detail="用户名或密码错误")
token = create_session_token(body.username) token = create_session_token(body.username)
resp = JSONResponse({"ok": True, "session_token": token}) embed = (request.headers.get("x-hub-embed") or "").strip() == "1"
set_session_cookie(resp, request, token) resp = JSONResponse({"ok": True, "session_token": token, "embed": embed})
set_session_cookie(resp, request, token, embed=embed)
return resp return resp
@@ -231,15 +233,15 @@ def embed_auth_login(request: Request, token: str = "", next: str = "/monitor"):
q = urlencode({"next": dest, "embed": "1"}) q = urlencode({"next": dest, "embed": "1"})
return RedirectResponse(f"/login?{q}", status_code=302) return RedirectResponse(f"/login?{q}", status_code=302)
resp = RedirectResponse(dest, status_code=302) resp = RedirectResponse(dest, status_code=302)
set_session_cookie(resp, request, token) set_session_cookie(resp, request, token, embed=True)
return resp return resp
@app.post("/api/auth/logout") @app.post("/api/auth/logout")
def api_auth_logout(request: Request): def api_auth_logout(request: Request):
secure = cookie_secure_for_request(request) embed = (request.headers.get("x-hub-embed") or "").strip() == "1"
resp = JSONResponse({"ok": True}) resp = JSONResponse({"ok": True})
resp.delete_cookie(SESSION_COOKIE, path="/", secure=secure) clear_session_cookie(resp, request, embed=embed)
return resp return resp
+23 -2
View File
@@ -137,19 +137,40 @@ def embed_frame_ancestors() -> str:
return " ".join(origins) if origins else "*" return " ".join(origins) if origins else "*"
def set_session_cookie(response, request, token: str) -> None: def set_session_cookie(response, request, token: str, *, embed: bool = False) -> None:
"""
embed=TrueLocalNav 等跨站 iframe 嵌入时须 SameSite=None + Secure(仅 HTTPS 有效)。
"""
secure = cookie_secure_for_request(request) secure = cookie_secure_for_request(request)
samesite = "lax"
if embed:
secure = True
samesite = "none"
response.set_cookie( response.set_cookie(
SESSION_COOKIE, SESSION_COOKIE,
token, token,
httponly=True, httponly=True,
samesite="lax", samesite=samesite,
path="/", path="/",
max_age=SESSION_MAX_AGE_SEC, max_age=SESSION_MAX_AGE_SEC,
secure=secure, secure=secure,
) )
def clear_session_cookie(response, request, *, embed: bool = False) -> None:
secure = cookie_secure_for_request(request)
samesite = "lax"
if embed:
secure = True
samesite = "none"
response.delete_cookie(
SESSION_COOKIE,
path="/",
secure=secure,
samesite=samesite,
)
def is_public_path(path: str, method: str) -> bool: def is_public_path(path: str, method: str) -> bool:
p = (path or "").split("?")[0].rstrip("/") or "/" p = (path or "").split("?")[0].rstrip("/") or "/"
if p.startswith("/assets"): if p.startswith("/assets"):
+58 -18
View File
@@ -4,11 +4,7 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>登录 · 复盘系统中控</title> <title>登录 · 复盘系统中控</title>
<link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="stylesheet" href="/assets/app.css?v=20260530-hub-embed-login" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Orbitron:wght@500;600;700&display=swap" rel="stylesheet" media="print" onload="this.media='all'" />
<noscript><link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Orbitron:wght@500;600;700&display=swap" rel="stylesheet" /></noscript>
<link rel="stylesheet" href="/assets/app.css?v=20260526-hub-key3col" />
</head> </head>
<body class="login-page"> <body class="login-page">
<div class="login-bg" aria-hidden="true"></div> <div class="login-bg" aria-hidden="true"></div>
@@ -23,29 +19,53 @@
<form id="login-form" class="login-form" autocomplete="on"> <form id="login-form" class="login-form" autocomplete="on">
<label class="field"> <label class="field">
<span>用户名</span> <span>用户名</span>
<input type="text" name="username" id="login-username" required autocomplete="username" placeholder="HUB_USERNAME" /> <input type="text" name="username" id="login-username" required autocomplete="username" />
</label> </label>
<label class="field"> <label class="field">
<span>密码</span> <span>密码</span>
<input type="password" name="password" id="login-password" required autocomplete="current-password" placeholder="HUB_PASSWORD" /> <input type="password" name="password" id="login-password" required autocomplete="current-password" />
</label> </label>
<button type="submit" class="primary login-submit">进入系统</button> <button type="submit" class="primary login-submit" id="login-submit">进入系统</button>
<p id="login-err" class="login-err" hidden></p> <p id="login-err" class="login-err" hidden></p>
<p id="login-hint" class="login-foot" hidden></p>
</form> </form>
<p class="login-foot"> hub <code>.env</code> 设置 <code>HUB_USERNAME</code> <code>HUB_PASSWORD</code>(未设用户名时默认为 <code>admin</code></p> <p class="login-foot">账号在云端 hub <code>.env</code><code>HUB_USERNAME</code> / <code>HUB_PASSWORD</code></p>
</div> </div>
<script> <script>
(function () { (function () {
const form = document.getElementById("login-form"); const form = document.getElementById("login-form");
const err = document.getElementById("login-err"); const err = document.getElementById("login-err");
const hint = document.getElementById("login-hint");
const submitBtn = document.getElementById("login-submit");
const userInput = document.getElementById("login-username"); const userInput = document.getElementById("login-username");
const params = new URLSearchParams(location.search); const params = new URLSearchParams(location.search);
const next = params.get("next") || "/monitor"; const next = params.get("next") || "/monitor";
const inFrame = window.self !== window.top; const inFrame = window.self !== window.top;
const isHttps = location.protocol === "https:";
if (inFrame) {
hint.hidden = false;
hint.textContent = isHttps
? "嵌入模式:登录成功后将自动写入会话。"
: "嵌入模式需 HTTPS 中控;HTTP 时请用本地导航工具栏「中控登录」。";
}
function showErr(msg) {
err.textContent = msg;
err.hidden = false;
}
function gotoAfterLogin(token, dest) { function gotoAfterLogin(token, dest) {
const target = dest.startsWith("/") ? dest : "/monitor"; const target = dest.startsWith("/") ? dest : "/monitor";
if (token && inFrame) { if (inFrame) {
if (!token) {
showErr("登录响应缺少 session_token,请升级云端 hub 或使用本地导航「中控登录」。");
return;
}
if (!isHttps) {
showErr("跨站 iframe 登录需要 HTTPS 中控;请改用本地导航「中控登录」按钮。");
return;
}
const q = new URLSearchParams({ token, next: target }); const q = new URLSearchParams({ token, next: target });
const embedUrl = "/embed-auth?" + q.toString(); const embedUrl = "/embed-auth?" + q.toString();
try { try {
@@ -59,6 +79,8 @@
"*" "*"
); );
} catch (_) {} } catch (_) {}
submitBtn.textContent = "跳转中…";
submitBtn.disabled = true;
location.replace(embedUrl); location.replace(embedUrl);
return; return;
} }
@@ -73,29 +95,47 @@
}) })
.catch(() => {}); .catch(() => {});
form.onsubmit = async (e) => { form.addEventListener("submit", async (e) => {
e.preventDefault(); e.preventDefault();
err.hidden = true; err.hidden = true;
submitBtn.disabled = true;
const oldLabel = submitBtn.textContent;
submitBtn.textContent = "登录中…";
const username = userInput.value.trim(); const username = userInput.value.trim();
const password = document.getElementById("login-password").value; const password = document.getElementById("login-password").value;
const headers = { "Content-Type": "application/json", Accept: "application/json" };
if (inFrame) headers["X-Hub-Embed"] = "1";
try { try {
const r = await fetch("/api/auth/login", { const r = await fetch("/api/auth/login", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers,
body: JSON.stringify({ username, password }), body: JSON.stringify({ username, password }),
}); });
const j = await r.json().catch(() => ({})); let j = {};
try {
j = await r.json();
} catch (_) {
j = {};
}
if (r.ok && j.ok) { if (r.ok && j.ok) {
gotoAfterLogin(j.session_token || null, next); gotoAfterLogin(j.session_token || null, next);
if (!inFrame) {
submitBtn.disabled = false;
submitBtn.textContent = oldLabel;
}
return; return;
} }
err.textContent = j.detail || j.msg || "用户名或密码错误"; if (r.status === 403) {
err.hidden = false; showErr("访问被拒绝(403):云端 hub 需设置 HUB_ALLOW_PUBLIC=true");
} else {
showErr(j.detail || j.msg || "用户名或密码错误 (" + r.status + ")");
}
} catch (ex) { } catch (ex) {
err.textContent = String(ex); showErr("网络错误:" + ex);
err.hidden = false;
} }
}; submitBtn.disabled = false;
submitBtn.textContent = oldLabel;
});
})(); })();
</script> </script>
</body> </body>