refactor: auth expiry - sync JWT exp check, remove async validation

Previous async validateAuth() approach caused: recursion loop,
wrong /me path (404 -> session cleared), init() fetching auth-required
settings without token (cleared session every load).

New synchronous approach:
- Auth.expired(): decodes JWT payload locally, checks exp timestamp
- Auth.logged(): token+user exist AND not expired; auto-clears stale
  session on expiry (no network, no async, no loops)
- route(): simple sync guard - if !Auth.logged() reset + redirect to
  #/login; home page stays public (clears stale cookie only)
- API.req: 401 response -> Auth.reset() + redirect to login unless on
  public page (fallback for server-side revocation/invalid signature)
- Removed validateAuth/_validating/_doRoute entirely
This commit is contained in:
2026-08-21 21:01:30 +08:00
parent edf561729f
commit 188e083719
3 changed files with 27 additions and 43 deletions

View File

@@ -23,7 +23,25 @@ const Auth = {
token() { return localStorage.getItem(this.TK); },
user() { try { return JSON.parse(localStorage.getItem(this.US)); } catch { return null; } },
logged() { return !!(this.token() && this.user()); },
// JWT payload 里的 exp(秒) 已过期?
expired() {
const t = this.token();
if (!t) return true;
try {
let b64 = t.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
b64 = b64.padEnd(b64.length + (4 - b64.length % 4) % 4, '=');
const payload = JSON.parse(atob(b64));
return payload.exp ? payload.exp * 1000 < Date.now() : false;
} catch { return true; }
},
// 登录态判断: token+user 存在 且 未过期;过期自动清除(不跳转)
logged() {
if (!this.token() || !this.user()) return false;
if (this.expired()) { this.reset(); return false; }
return true;
},
async login(username, password) {
const d = await API.post('/auth/login', { username, password });