加入自动登录支持
This commit is contained in:
@@ -52,7 +52,9 @@ model_hold:
|
|||||||
# 登录页 /login,会话 token 以 HttpOnly cookie 下发(替代 nginx htpasswd:
|
# 登录页 /login,会话 token 以 HttpOnly cookie 下发(替代 nginx htpasswd:
|
||||||
# 手机浏览器原生下载不带 Basic 认证头,cookie 则会自动携带,下载不再失败)。
|
# 手机浏览器原生下载不带 Basic 认证头,cookie 则会自动携带,下载不再失败)。
|
||||||
# 仍兼容 Authorization: Basic 头(curl/API 脚本可用)。
|
# 仍兼容 Authorization: Basic 头(curl/API 脚本可用)。
|
||||||
# secret:签名密钥;留空则启动时随机生成(重启后需重新登录)。
|
# secret:签名密钥;留空则启动时随机生成(重启后需重新登录),建议固定随机串。
|
||||||
|
# 登录页支持用 localStorage 里的 token 静默恢复登录态(POST /api/login_restore),
|
||||||
|
# 兼容 Android WebView 封装 APK 杀进程后 cookie 未落盘的场景。
|
||||||
# 整段删除或 users 留空则不启用认证。
|
# 整段删除或 users 留空则不启用认证。
|
||||||
# auth:
|
# auth:
|
||||||
# secret: "change-me" # 选填;建议固定,避免重启掉登录态
|
# secret: "change-me" # 选填;建议固定,避免重启掉登录态
|
||||||
|
|||||||
+17
-3
@@ -71,7 +71,7 @@ function basicAuthUser(req, users) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 免认证路径(登录页自身需要的资源) ----------
|
// ---------- 免认证路径(登录页自身需要的资源) ----------
|
||||||
const PUBLIC_EXACT = new Set(['/login', '/logout', '/api/login', '/api/logout', '/api/health']);
|
const PUBLIC_EXACT = new Set(['/login', '/logout', '/api/login', '/api/logout', '/api/login_restore', '/api/health']);
|
||||||
function isPublicPath(p) {
|
function isPublicPath(p) {
|
||||||
if (PUBLIC_EXACT.has(p)) return true;
|
if (PUBLIC_EXACT.has(p)) return true;
|
||||||
if (p.startsWith('/css/')) return true; // 登录页复用 style.css
|
if (p.startsWith('/css/')) return true; // 登录页复用 style.css
|
||||||
@@ -104,6 +104,7 @@ function createAuth(cfg) {
|
|||||||
const token = signToken(username, Date.now() + ttlMs, secret);
|
const token = signToken(username, Date.now() + ttlMs, secret);
|
||||||
res.setHeader('Set-Cookie', COOKIE_NAME + '=' + encodeURIComponent(token)
|
res.setHeader('Set-Cookie', COOKIE_NAME + '=' + encodeURIComponent(token)
|
||||||
+ '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + Math.floor(ttlMs / 1000));
|
+ '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + Math.floor(ttlMs / 1000));
|
||||||
|
return token;
|
||||||
}
|
}
|
||||||
function clearAuthCookie(res) {
|
function clearAuthCookie(res) {
|
||||||
res.setHeader('Set-Cookie', COOKIE_NAME + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0');
|
res.setHeader('Set-Cookie', COOKIE_NAME + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0');
|
||||||
@@ -124,7 +125,19 @@ function createAuth(cfg) {
|
|||||||
return res.status(401).json({ error: '用户名或密码错误' });
|
return res.status(401).json({ error: '用户名或密码错误' });
|
||||||
}
|
}
|
||||||
setAuthCookie(res, String(user));
|
setAuthCookie(res, String(user));
|
||||||
res.json({ ok: true, user: String(user) });
|
// token 一并回给前端:WebView 封装 APK 杀进程后 cookie 可能没落盘,
|
||||||
|
// 前端存 localStorage,下次进登录页用 /api/login_restore 自动恢复。
|
||||||
|
res.json({ ok: true, user: String(user), token: signToken(String(user), Date.now() + ttlMs, secret) });
|
||||||
|
});
|
||||||
|
|
||||||
|
// 自动恢复登录态(主要是 WebView 封装场景):cookie 丢了但 localStorage 里的 token 还在,
|
||||||
|
// 携 Authorization: Bearer <token> 请求本接口,验签通过则重新下发 cookie。
|
||||||
|
router.post('/api/login_restore', (req, res) => {
|
||||||
|
const h = String(req.headers.authorization || '');
|
||||||
|
const data = readToken(h.startsWith('Bearer ') ? h.slice(7).trim() : '', secret);
|
||||||
|
if (!data || !validUsers.has(data.user)) return res.status(401).json({ error: '登录态已失效,请重新登录' });
|
||||||
|
setAuthCookie(res, data.user); // 重新签发,顺带续期
|
||||||
|
res.json({ ok: true, user: data.user });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/logout', (req, res) => {
|
router.post('/api/logout', (req, res) => {
|
||||||
@@ -178,7 +191,8 @@ function createAuth(cfg) {
|
|||||||
|
|
||||||
router.get('/logout', (req, res) => {
|
router.get('/logout', (req, res) => {
|
||||||
clearAuthCookie(res);
|
clearAuthCookie(res);
|
||||||
res.redirect('/login');
|
// 带标记:登录页据此清掉 localStorage 里的恢复 token,避免自动登录把用户“投回去”
|
||||||
|
res.redirect('/login?logged_out=1');
|
||||||
});
|
});
|
||||||
|
|
||||||
// ----- 全局认证中间件:cookie 或 Basic 任一通过;否则 API 回 401、页面跳登录页 -----
|
// ----- 全局认证中间件:cookie 或 Basic 任一通过;否则 API 回 401、页面跳登录页 -----
|
||||||
|
|||||||
@@ -38,6 +38,25 @@
|
|||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
'use strict';
|
'use strict';
|
||||||
|
const TOKEN_KEY = 'agent_token';
|
||||||
|
// WebView 封装 APK 杀进程后 HttpOnly cookie 可能没落盘,但 localStorage 还在:
|
||||||
|
// 登录成功后把 token 另存一份,下次进来先尝试用旧 token 静默恢复登录态。
|
||||||
|
async function autoRestore() {
|
||||||
|
if (new URLSearchParams(location.search).has('logged_out')) {
|
||||||
|
localStorage.removeItem(TOKEN_KEY); // 显式登出:不恢复,并清掉旧 token
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const t = localStorage.getItem(TOKEN_KEY);
|
||||||
|
if (!t) return;
|
||||||
|
const form = document.getElementById('login-form');
|
||||||
|
form.style.visibility = 'hidden'; // 恢复期间先藏表单,避免闪现
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/login_restore', { method: 'POST', headers: { Authorization: 'Bearer ' + t } });
|
||||||
|
if (res.ok) { location.replace('/'); return; }
|
||||||
|
} catch (_) { /* 网络错误交给表单正常登录 */ }
|
||||||
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
|
form.style.visibility = '';
|
||||||
|
}
|
||||||
async function doLogin(e) {
|
async function doLogin(e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const btn = document.getElementById('login-btn');
|
const btn = document.getElementById('login-btn');
|
||||||
@@ -58,6 +77,8 @@
|
|||||||
try { msg = (await res.json()).error || msg; } catch (_) {}
|
try { msg = (await res.json()).error || msg; } catch (_) {}
|
||||||
throw new Error(msg);
|
throw new Error(msg);
|
||||||
}
|
}
|
||||||
|
const j = await res.json().catch(() => ({}));
|
||||||
|
if (j && j.token) localStorage.setItem(TOKEN_KEY, j.token);
|
||||||
location.href = '/';
|
location.href = '/';
|
||||||
} catch (e2) {
|
} catch (e2) {
|
||||||
errEl.textContent = e2.message || '登录失败';
|
errEl.textContent = e2.message || '登录失败';
|
||||||
@@ -65,6 +86,7 @@
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
autoRestore();
|
||||||
document.getElementById('login-user').focus();
|
document.getElementById('login-user').focus();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
Reference in New Issue
Block a user