useAuthStore.ts
4.49 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export interface AuthUser {
username: string;
}
/** 启动续期最多等这么久,超了就当后台没在,直接放页面进去 */
const BOOTSTRAP_TIMEOUT_MS = 4000;
interface AuthState {
token: string | null;
user: AuthUser | null;
status: 'idle' | 'loading' | 'authed' | 'error';
error: string | null;
/** 最近一次登录失败的机器可读原因,登录页据此决定要不要立刻换一张验证码 */
errorCode: string | null;
login: (username: string, password: string, captcha: LoginCaptcha) => Promise<boolean>;
logout: () => Promise<void>;
/** 启动续期:用本地 token 调 /api/me 校验,失效则清态 */
bootstrap: () => Promise<void>;
}
/** 服务端签发的验证码:id 与图片,明文码不在前端 */
export interface LoginCaptcha {
id: string;
code: string;
}
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
token: null,
user: null,
status: 'idle',
error: null,
errorCode: null,
async login(username, password, captcha) {
set({ status: 'loading', error: null, errorCode: null });
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username,
password,
captchaId: captcha.id,
captchaCode: captcha.code,
}),
});
if (!res.ok) {
// 服务端已经给了具体原因(验证码错 / 过期 / 锁定),照抄比统一糊成
// 「用户名或密码错误」有用得多——否则用户会一直重试密码,其实是图错了
const data = (await res.json().catch(() => ({}))) as {
error?: string;
message?: string;
};
const code = data.error ?? `http_${res.status}`;
set({
status: 'error',
errorCode: code,
error: data.message ?? '用户名或密码错误',
});
return false;
}
const data = (await res.json()) as { token: string; user: AuthUser };
set({ token: data.token, user: data.user, status: 'authed', error: null, errorCode: null });
return true;
} catch {
set({
status: 'error',
errorCode: 'network',
error: '登录服务不可用,请确认后台已启动',
});
return false;
}
},
async logout() {
const token = get().token;
if (token) {
// 无状态 JWT:后端不留存会话,调一下仅作语义清晰,失败不阻塞前端清态
try {
await fetch('/api/logout', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
} catch {
/* ignore */
}
}
set({ token: null, user: null, status: 'idle', error: null, errorCode: null });
},
async bootstrap() {
const token = get().token;
if (!token) return;
try {
const res = await fetch('/api/me', {
headers: { Authorization: `Bearer ${token}` },
// 有上限的等待:这个 fetch 挂在 RequireAuth 前面,它不返回,受保护页面就一直不出内容。
// 后台没起来 / 端口被上一次 concurrently 的残留进程占住时,连接会一直悬着而不是立刻失败。
signal: AbortSignal.timeout(BOOTSTRAP_TIMEOUT_MS),
});
if (res.ok) {
const data = (await res.json()) as { user: AuthUser };
set({ user: data.user, status: 'authed' });
} else if (res.status === 401 || res.status === 403) {
// 只有「凭证本身不被接受」才清 token(过期 / 伪造),回到未登录
set({ token: null, user: null, status: 'idle' });
}
// 其它非 2xx(dev 代理连不上后台时是 502/504):当成没联系上后台,
// 保留本地 token 让页面照常出内容,不把人踢到登录页
} catch {
// 超时或网络错先保留本地 token,下次启动再续期,不强制登出
}
},
}),
{
name: 'hm-auth',
// 只持久化凭证,状态机字段不入库
partialize: (s) => ({ token: s.token, user: s.user }),
},
),
);