auth.js
2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
文件名: app/static/js/auth.js
职责: 全局认证状态管理:校验登录、显示用户信息、自动处理 401、退出登录。
注意: 不要删除这个注释。
*/
(function() {
// 拦截全局 fetch,自动携带 Cookie 并处理 401
const originalFetch = window.fetch;
window.fetch = async function(...args) {
const options = args[1] || {};
options.credentials = 'include';
args[1] = options;
try {
const response = await originalFetch.apply(this, args);
if (response.status === 401 && !window.location.pathname.includes('/login')) {
window.location.href = '/login';
}
return response;
} catch (err) {
throw err;
}
};
// API 基础路径始终为 /api(FastAPI 统一挂载)
window.API_BASE = '/api';
// 登录页不执行后续逻辑
if (window.location.pathname.includes('/login')) {
return;
}
// 获取当前用户信息
async function loadCurrentUser() {
try {
const res = await fetch(window.API_BASE + '/auth/me', { credentials: 'include' });
if (res.status === 401) {
window.location.href = '/login';
return;
}
if (!res.ok) {
console.error('获取用户信息失败:', res.status);
return;
}
const user = await res.json();
renderUserInfo(user.username);
} catch (err) {
console.error('加载用户信息失败:', err);
}
}
// 渲染右上角用户信息
function renderUserInfo(username) {
const userInfo = document.getElementById('user-info') || document.querySelector('.user-info');
if (!userInfo) return;
userInfo.innerHTML = '';
const nameSpan = document.createElement('span');
nameSpan.textContent = username || '管理员';
nameSpan.style.marginRight = '10px';
const logoutLink = document.createElement('a');
logoutLink.href = '#';
logoutLink.textContent = '退出';
logoutLink.style.color = '#ff6b6b';
logoutLink.style.textDecoration = 'none';
logoutLink.style.fontSize = '13px';
logoutLink.addEventListener('click', async (e) => {
e.preventDefault();
try {
await fetch(window.API_BASE + '/auth/logout', { method: 'POST', credentials: 'include' });
} catch (err) {
console.error('退出请求失败:', err);
}
window.location.href = '/login';
});
userInfo.appendChild(nameSpan);
userInfo.appendChild(logoutLink);
}
document.addEventListener('DOMContentLoaded', loadCurrentUser);
})();