部分重型模块的原子化拆解

This commit is contained in:
2026-07-23 20:46:16 +08:00
parent 2afff129b9
commit 5fa1b99c5d
12 changed files with 1688 additions and 875 deletions
+49
View File
@@ -0,0 +1,49 @@
// modules/auth.js
import { apiFetch } from './api.js';
export function parseJwtExpire(token) {
try {
const payload = JSON.parse(atob(token.split('.')[1]));
return payload.exp * 1000;
} catch {
return Date.now() + 7 * 24 * 60 * 60 * 1000;
}
}
export function saveAuthState(token, username) {
const expire = parseJwtExpire(token);
localStorage.setItem('frpc_token', token);
localStorage.setItem('frpc_token_expire', String(expire));
localStorage.setItem('frpc_username', username);
return expire;
}
export function loadAuthState() {
const token = localStorage.getItem('frpc_token');
const expire = parseInt(localStorage.getItem('frpc_token_expire') || '0', 10);
const username = localStorage.getItem('frpc_username') || '';
if (token && expire > Date.now()) {
return { token, expire, username, valid: true };
}
clearAuthState();
return { token: '', expire: 0, username: '', valid: false };
}
export function clearAuthState() {
localStorage.removeItem('frpc_token');
localStorage.removeItem('frpc_token_expire');
localStorage.removeItem('frpc_username');
}
export async function login(username, password) {
const data = await apiFetch('/login', {
method: 'POST',
body: JSON.stringify({ username, password }),
});
if (data.code === 0) {
const token = data.data.token;
const expire = saveAuthState(token, username);
return { success: true, token, expire };
}
return { success: false, error: data.msg || '登录失败' };
}