中控
This commit is contained in:
@@ -32,6 +32,7 @@ from settings_store import (
|
||||
from hub_web_auth import (
|
||||
SESSION_COOKIE,
|
||||
SESSION_MAX_AGE_SEC,
|
||||
clear_session_cookie,
|
||||
cookie_secure_for_request,
|
||||
create_session_token,
|
||||
embed_allowed,
|
||||
@@ -211,8 +212,9 @@ def api_auth_login(body: LoginBody, request: Request):
|
||||
if not verify_credentials(body.username, body.password):
|
||||
raise HTTPException(status_code=401, detail="用户名或密码错误")
|
||||
token = create_session_token(body.username)
|
||||
resp = JSONResponse({"ok": True, "session_token": token})
|
||||
set_session_cookie(resp, request, token)
|
||||
embed = (request.headers.get("x-hub-embed") or "").strip() == "1"
|
||||
resp = JSONResponse({"ok": True, "session_token": token, "embed": embed})
|
||||
set_session_cookie(resp, request, token, embed=embed)
|
||||
return resp
|
||||
|
||||
|
||||
@@ -231,15 +233,15 @@ def embed_auth_login(request: Request, token: str = "", next: str = "/monitor"):
|
||||
q = urlencode({"next": dest, "embed": "1"})
|
||||
return RedirectResponse(f"/login?{q}", 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
|
||||
|
||||
|
||||
@app.post("/api/auth/logout")
|
||||
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.delete_cookie(SESSION_COOKIE, path="/", secure=secure)
|
||||
clear_session_cookie(resp, request, embed=embed)
|
||||
return resp
|
||||
|
||||
|
||||
|
||||
@@ -137,19 +137,40 @@ def embed_frame_ancestors() -> str:
|
||||
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=True:LocalNav 等跨站 iframe 嵌入时须 SameSite=None + Secure(仅 HTTPS 有效)。
|
||||
"""
|
||||
secure = cookie_secure_for_request(request)
|
||||
samesite = "lax"
|
||||
if embed:
|
||||
secure = True
|
||||
samesite = "none"
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
samesite=samesite,
|
||||
path="/",
|
||||
max_age=SESSION_MAX_AGE_SEC,
|
||||
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:
|
||||
p = (path or "").split("?")[0].rstrip("/") or "/"
|
||||
if p.startswith("/assets"):
|
||||
|
||||
@@ -4,11 +4,7 @@
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<title>登录 · 复盘系统中控</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<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" />
|
||||
<link rel="stylesheet" href="/assets/app.css?v=20260530-hub-embed-login" />
|
||||
</head>
|
||||
<body class="login-page">
|
||||
<div class="login-bg" aria-hidden="true"></div>
|
||||
@@ -23,29 +19,53 @@
|
||||
<form id="login-form" class="login-form" autocomplete="on">
|
||||
<label class="field">
|
||||
<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 class="field">
|
||||
<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>
|
||||
<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-hint" class="login-foot" hidden></p>
|
||||
</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>
|
||||
<script>
|
||||
(function () {
|
||||
const form = document.getElementById("login-form");
|
||||
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 params = new URLSearchParams(location.search);
|
||||
const next = params.get("next") || "/monitor";
|
||||
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) {
|
||||
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 embedUrl = "/embed-auth?" + q.toString();
|
||||
try {
|
||||
@@ -59,6 +79,8 @@
|
||||
"*"
|
||||
);
|
||||
} catch (_) {}
|
||||
submitBtn.textContent = "跳转中…";
|
||||
submitBtn.disabled = true;
|
||||
location.replace(embedUrl);
|
||||
return;
|
||||
}
|
||||
@@ -73,29 +95,47 @@
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
form.onsubmit = async (e) => {
|
||||
form.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
err.hidden = true;
|
||||
submitBtn.disabled = true;
|
||||
const oldLabel = submitBtn.textContent;
|
||||
submitBtn.textContent = "登录中…";
|
||||
const username = userInput.value.trim();
|
||||
const password = document.getElementById("login-password").value;
|
||||
const headers = { "Content-Type": "application/json", Accept: "application/json" };
|
||||
if (inFrame) headers["X-Hub-Embed"] = "1";
|
||||
try {
|
||||
const r = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers,
|
||||
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) {
|
||||
gotoAfterLogin(j.session_token || null, next);
|
||||
if (!inFrame) {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = oldLabel;
|
||||
}
|
||||
return;
|
||||
}
|
||||
err.textContent = j.detail || j.msg || "用户名或密码错误";
|
||||
err.hidden = false;
|
||||
if (r.status === 403) {
|
||||
showErr("访问被拒绝(403):云端 hub 需设置 HUB_ALLOW_PUBLIC=true");
|
||||
} else {
|
||||
showErr(j.detail || j.msg || "用户名或密码错误 (" + r.status + ")");
|
||||
}
|
||||
} catch (ex) {
|
||||
err.textContent = String(ex);
|
||||
err.hidden = false;
|
||||
showErr("网络错误:" + ex);
|
||||
}
|
||||
};
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = oldLabel;
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
Reference in New Issue
Block a user