This commit is contained in:
dekun
2026-05-30 16:01:35 +08:00
parent 979054546c
commit cdbe087202
6 changed files with 235 additions and 20 deletions
+32
View File
@@ -246,9 +246,41 @@ async def login_post(request: Request, body: LoginBody) -> JSONResponse | Redire
if body.username.strip() != settings.auth.username.strip() or _hash_password(body.password) != _password_hash():
return JSONResponse({"ok": False, "detail": "账号或密码错误"}, status_code=401)
request.session["logged_in"] = True
embed_hdr = (request.headers.get("x-nav-embed") or "").strip() == "1"
try:
from nav_session_auth import create_embed_bootstrap_token, nav_embed_session_active, safe_next_path
from urllib.parse import urlencode
if embed_hdr or nav_embed_session_active():
nxt = safe_next_path("/dashboard")
boot = create_embed_bootstrap_token(body.username.strip(), secret=settings.app.session_secret)
q = urlencode({"token": boot, "next": nxt, "embed": "1"})
return JSONResponse(
{
"ok": True,
"redirect": nxt,
"session_token": boot,
"embed_auth_url": f"/embed-auth?{q}",
}
)
except Exception:
pass
return JSONResponse({"ok": True, "redirect": "/dashboard"})
@app.get("/embed-auth", response_model=None)
async def embed_auth(request: Request, token: str = "", next: str = "/dashboard") -> RedirectResponse:
from nav_session_auth import safe_next_path, validate_embed_bootstrap_token
if not settings.auth.enabled:
return RedirectResponse(safe_next_path(next), status_code=302)
ok, _user = validate_embed_bootstrap_token(token, secret=settings.app.session_secret)
if ok:
request.session["logged_in"] = True
return RedirectResponse(safe_next_path(next), status_code=302)
return RedirectResponse("/login", status_code=302)
@app.get("/logout", response_model=None)
async def logout(request: Request) -> RedirectResponse:
request.session.clear()
+13 -4
View File
@@ -78,7 +78,10 @@
var password = fd.get("password");
fetch("/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
headers: {
"Content-Type": "application/json",
"X-Nav-Embed": window.self !== window.top ? "1" : "0",
},
credentials: "same-origin",
body: JSON.stringify({ username: username, password: password }),
})
@@ -88,9 +91,15 @@
});
})
.then(function (x) {
if (x.ok && x.body && x.body.redirect) {
window.location.href = x.body.redirect;
return;
if (x.ok && x.body) {
var dest =
window.self !== window.top && x.body.embed_auth_url
? x.body.embed_auth_url
: x.body.redirect || "/dashboard";
if (dest) {
window.location.href = dest;
return;
}
}
errEl.textContent = (x.body && x.body.detail) || "登录失败";
})