feat: 完善鉴权模块 #142
@@ -116,7 +116,7 @@ async function request<T>(
|
||||
}
|
||||
|
||||
return { data: body as T, status };
|
||||
} catch (err) {
|
||||
} catch {
|
||||
return {
|
||||
error: { code: "NETWORK_ERROR", message: "网络连接失败,请检查网络" },
|
||||
status: 0,
|
||||
|
||||
@@ -109,20 +109,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
[clearRefreshTimer, persistAuth]
|
||||
);
|
||||
|
||||
// 用 ref 保存最新回调,供 API 层 401 拦截器使用(避免闭包陈旧)
|
||||
const persistAuthRef = useRef(persistAuth);
|
||||
const scheduleRefreshRef = useRef(scheduleRefresh);
|
||||
persistAuthRef.current = persistAuth;
|
||||
scheduleRefreshRef.current = scheduleRefresh;
|
||||
|
||||
// 注册 API 层认证回调(用于 401 拦截器)
|
||||
useEffect(() => {
|
||||
setAuthCallbacks({
|
||||
getAccessToken: () => loadAccessToken(),
|
||||
getRefreshToken: () => loadRefreshToken(),
|
||||
onRefreshSuccess: (u, at, rt) => {
|
||||
persistAuthRef.current(u, at, rt);
|
||||
scheduleRefreshRef.current(at);
|
||||
persistAuth(u, at, rt);
|
||||
scheduleRefresh(at);
|
||||
},
|
||||
onRefreshFailed: () => {
|
||||
clearAuth();
|
||||
@@ -130,7 +124,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setAccessToken(null);
|
||||
},
|
||||
});
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}, [persistAuth, scheduleRefresh]);
|
||||
|
||||
// 初始化:检查已有 token 并尝试刷新
|
||||
useEffect(() => {
|
||||
|
||||
Reference in New Issue
Block a user