-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthContext.tsx
More file actions
406 lines (368 loc) · 12.4 KB
/
authContext.tsx
File metadata and controls
406 lines (368 loc) · 12.4 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { User } from './types';
import { apiDelete, apiGet, apiPatch, apiPost, ApiError } from './utils/apiClient';
import { clearAuthToken, getAuthToken, setAuthToken } from './utils/authToken';
import { cancelCloudWarmup, warmupCloudDataByPriority } from './utils/dataWarmup';
import { clearFocusStatsCache } from './utils/focusStatsCache';
import { clearFocusTimerStateCache } from './utils/focusTimerStateCache';
import { clearPeriodTrackerCache } from './utils/periodTrackerCache';
import { onSessionSync, triggerSessionSync } from './utils/sessionSync';
export interface Notification {
id: string;
userId: string;
title: string;
message: string;
type: 'system' | 'interaction';
read: boolean;
createdAt: string;
}
interface AuthResponse {
token: string;
user: User;
partner: User | null;
}
interface CodeRequestResult {
ok: boolean;
message?: string;
expiresInMinutes?: number;
}
interface AuthContextType {
currentUser: User | null;
partner: User | null;
users: User[];
refreshAuthData: () => Promise<void>;
requestRegisterCode: (email: string, password: string) => Promise<CodeRequestResult>;
verifyRegisterCode: (email: string, code: string, password?: string) => Promise<boolean>;
requestPasswordResetCode: (email: string) => Promise<CodeRequestResult>;
resetPasswordWithCode: (email: string, code: string, newPassword: string) => Promise<boolean>;
login: (email: string, password: string) => Promise<boolean>;
logout: () => Promise<void>;
isEmailTaken: (email: string) => boolean;
updateProfile: (updates: Partial<User>) => Promise<void>;
notifications: Notification[];
addNotification: (
title: string,
message: string,
type?: 'system' | 'interaction'
) => Promise<void>;
markAsRead: (id: string) => Promise<void>;
markAllAsRead: () => Promise<void>;
clearNotifications: () => Promise<void>;
unreadCount: number;
lastError: string | null;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [users, setUsers] = useState<User[]>([]);
const [currentUser, setCurrentUser] = useState<User | null>(null);
const [partner, setPartner] = useState<User | null>(null);
const [allNotifications, setAllNotifications] = useState<Notification[]>([]);
const [lastError, setLastError] = useState<string | null>(null);
const refreshInFlightRef = useRef<Promise<void> | null>(null);
const notifications = useMemo(
() =>
allNotifications
.filter((n) => n.userId === currentUser?.id)
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()),
[allNotifications, currentUser?.id]
);
const unreadCount = useMemo(() => notifications.filter((n) => !n.read).length, [notifications]);
const resetAuthState = useCallback(() => {
setCurrentUser(null);
setPartner(null);
setUsers([]);
setAllNotifications([]);
cancelCloudWarmup();
clearFocusStatsCache();
clearFocusTimerStateCache();
clearPeriodTrackerCache();
}, []);
const refreshAuthData = useCallback(async () => {
if (refreshInFlightRef.current) {
return refreshInFlightRef.current;
}
const refreshTask = (async () => {
const token = getAuthToken();
if (!token) {
resetAuthState();
return;
}
try {
const [me, notificationsResult] = await Promise.all([
apiGet<{ user: User; partner: User | null }>('/auth/me'),
apiGet<{ notifications: Notification[] }>('/notifications?limit=200'),
]);
const nextUsers: User[] = me.partner ? [me.user, me.partner] : [me.user];
setUsers(nextUsers);
setCurrentUser(me.user);
setPartner(me.partner);
setAllNotifications(notificationsResult.notifications || []);
setLastError(null);
warmupCloudDataByPriority(me.user.id, me.partner?.id || null);
} catch (error) {
console.error('Failed to refresh auth data:', error);
if (error instanceof ApiError && error.status === 401) {
clearAuthToken();
resetAuthState();
}
}
})().finally(() => {
refreshInFlightRef.current = null;
});
refreshInFlightRef.current = refreshTask;
return refreshTask;
}, [resetAuthState]);
useEffect(() => {
refreshAuthData();
return onSessionSync(() => {
refreshAuthData();
});
}, [refreshAuthData]);
/**
* Local-only check: returns true when `email` matches a user already loaded
* into the auth state (current user or their partner). This does NOT query
* the backend, so it cannot detect emails registered by other accounts.
*/
const isEmailTaken = (email: string) =>
users.some((u) => u.email.toLowerCase() === email.toLowerCase());
const handleAuthSuccess = useCallback(async (result: AuthResponse) => {
setAuthToken(result.token);
setCurrentUser(result.user);
setPartner(result.partner);
setUsers(result.partner ? [result.user, result.partner] : [result.user]);
warmupCloudDataByPriority(result.user.id, result.partner?.id || null);
triggerSessionSync();
if (!result.user?.invitationCode) {
await refreshAuthData();
}
}, [refreshAuthData]);
const requestRegisterCode = async (email: string, password: string): Promise<CodeRequestResult> => {
try {
const result = await apiPost<{
ok: boolean;
message: string;
expiresInMinutes: number;
}>('/auth/register/request-code', {
email,
password,
});
setLastError(null);
return {
ok: result.ok,
message: result.message,
expiresInMinutes: result.expiresInMinutes,
};
} catch (error: any) {
const message = error?.message || '发送验证码失败';
setLastError(message);
console.error('requestRegisterCode failed:', error);
return { ok: false, message };
}
};
const verifyRegisterCode = async (
email: string,
code: string,
password?: string
): Promise<boolean> => {
try {
const result = await apiPost<AuthResponse>('/auth/register/verify', {
email,
code,
password,
});
await handleAuthSuccess(result);
setLastError(null);
return true;
} catch (error: any) {
const isTimeout = error instanceof ApiError ? error.status === 408 : Number(error?.status) === 408;
if (password && isTimeout) {
// Verification may have completed server-side; poll login briefly to recover session.
for (let i = 0; i < 3; i += 1) {
await sleep(700 * (i + 1));
try {
const loginResult = await apiPost<AuthResponse>('/auth/login', { email, password });
await handleAuthSuccess(loginResult);
setLastError(null);
return true;
} catch (_ignored) {
// continue retry
}
}
}
const message = error?.message || '验证码校验失败';
setLastError(message);
console.error('verifyRegisterCode failed:', error);
return false;
}
};
const requestPasswordResetCode = async (email: string): Promise<CodeRequestResult> => {
try {
const result = await apiPost<{
ok: boolean;
message: string;
expiresInMinutes: number;
}>('/auth/password/request-reset-code', {
email,
});
setLastError(null);
return {
ok: result.ok,
message: result.message,
expiresInMinutes: result.expiresInMinutes,
};
} catch (error: any) {
const message = error?.message || '发送重置验证码失败';
setLastError(message);
console.error('requestPasswordResetCode failed:', error);
return { ok: false, message };
}
};
const resetPasswordWithCode = async (
email: string,
code: string,
newPassword: string
): Promise<boolean> => {
try {
await apiPost<{ ok: boolean; message: string }>('/auth/password/reset', {
email,
code,
newPassword,
});
setLastError(null);
return true;
} catch (error: any) {
const message = error?.message || '重置密码失败';
setLastError(message);
console.error('resetPasswordWithCode failed:', error);
return false;
}
};
const login = async (email: string, password: string): Promise<boolean> => {
try {
const result = await apiPost<AuthResponse>('/auth/login', { email, password });
await handleAuthSuccess(result);
setLastError(null);
return true;
} catch (error: any) {
const message = error?.message || '登录失败';
setLastError(message);
console.error('Login failed:', error);
return false;
}
};
const logout = async () => {
clearAuthToken();
setLastError(null);
resetAuthState();
triggerSessionSync();
};
const updateProfile = async (updates: Partial<User>) => {
if (!currentUser) return;
try {
const result = await apiPatch<{ user: User }>('/auth/profile', updates);
setCurrentUser(result.user);
setUsers((prev) => {
const exists = prev.some((u) => u.id === result.user.id);
if (!exists) return [...prev, result.user];
return prev.map((u) => (u.id === result.user.id ? result.user : u));
});
triggerSessionSync();
setLastError(null);
} catch (error: any) {
console.error('updateProfile failed:', error);
const message = error?.message || '更新资料失败';
setLastError(message);
throw error instanceof Error ? error : new Error(message);
}
};
const addNotification = async (
title: string,
message: string,
type: 'system' | 'interaction' = 'system'
) => {
if (!currentUser) return;
try {
const result = await apiPost<{ notification: Notification }>('/notifications', {
title,
message,
type,
});
setAllNotifications((prev) => [result.notification, ...prev]);
setLastError(null);
} catch (error: any) {
console.error('addNotification failed:', error);
setLastError(error?.message || '创建通知失败');
}
};
const markAsRead = async (id: string) => {
if (!currentUser) return;
try {
const result = await apiPatch<{ notification: Notification }>(`/notifications/${id}/read`, {});
setAllNotifications((prev) => prev.map((n) => (n.id === id ? result.notification : n)));
setLastError(null);
} catch (error: any) {
console.error('markAsRead failed:', error);
setAllNotifications((prev) => prev.map((n) => (n.id === id ? { ...n, read: true } : n)));
setLastError(error?.message || '标记已读失败');
}
};
const markAllAsRead = async () => {
if (!currentUser) return;
try {
await apiPatch<{ ok: boolean }>('/notifications/read-all', {});
setAllNotifications((prev) =>
prev.map((n) => (n.userId === currentUser.id ? { ...n, read: true } : n))
);
setLastError(null);
} catch (error: any) {
console.error('markAllAsRead failed:', error);
setLastError(error?.message || '一键标记已读失败');
}
};
const clearNotifications = async () => {
if (!currentUser) return;
try {
await apiDelete('/notifications');
setLastError(null);
} catch (error: any) {
console.error('clearNotifications failed:', error);
setLastError(error?.message || '清空通知失败');
}
setAllNotifications((prev) => prev.filter((n) => n.userId !== currentUser.id));
};
return (
<AuthContext.Provider
value={{
currentUser,
partner,
refreshAuthData,
requestRegisterCode,
verifyRegisterCode,
requestPasswordResetCode,
resetPasswordWithCode,
login,
logout,
updateProfile,
users,
isEmailTaken,
notifications,
addNotification,
markAsRead,
markAllAsRead,
clearNotifications,
unreadCount,
lastError,
}}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};