fix: preserve cached data during refresh failures
This commit is contained in:
@@ -34,4 +34,58 @@ describe("AuthProvider", () => {
|
||||
|
||||
expect(authorization).toBe("Bearer restored-token");
|
||||
});
|
||||
|
||||
it("settles unauthenticated and clears cached data when cold-start refresh has a transport error", async () => {
|
||||
server.use(http.post("*/api/v1/auth/refresh", () => HttpResponse.error()));
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.ready).toBe(true));
|
||||
|
||||
expect(result.current.user).toBeNull();
|
||||
expect(result.current.accessToken).toBeNull();
|
||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the original protected 401 when serialized refresh has a transport error", async () => {
|
||||
let refreshCalls = 0;
|
||||
server.use(
|
||||
http.post("*/api/v1/auth/refresh", () => {
|
||||
refreshCalls += 1;
|
||||
return refreshCalls === 1
|
||||
? HttpResponse.json({
|
||||
accessToken: "restored-token",
|
||||
user: { id: "user-1", email: "user@example.com" },
|
||||
})
|
||||
: HttpResponse.error();
|
||||
}),
|
||||
http.get("*/api/v1/brokerage-accounts", () =>
|
||||
HttpResponse.json({ code: "UNAUTHORIZED" }, { status: 401 }),
|
||||
),
|
||||
);
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(["cached-query"], { value: "stale" });
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.accessToken).toBe("restored-token"),
|
||||
);
|
||||
const response = await apiClient.GET("/api/v1/brokerage-accounts");
|
||||
|
||||
expect(response.response.status).toBe(401);
|
||||
await waitFor(() => expect(result.current.user).toBeNull());
|
||||
expect(result.current.accessToken).toBeNull();
|
||||
expect(queryClient.getQueryData(["cached-query"])).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { createContext, useContext, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { apiClient, configureAuthClient } from "@/shared/api";
|
||||
import type { paths } from "@/shared/api/generated/schema";
|
||||
|
||||
@@ -41,40 +48,52 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
const refreshPromise = useRef<Promise<boolean> | null>(null);
|
||||
const applyAuthentication = useCallback((authentication: Authentication) => {
|
||||
setUser(authentication.user);
|
||||
setAccessToken(authentication.accessToken);
|
||||
accessTokenRef.current = authentication.accessToken;
|
||||
}, []);
|
||||
const clearSession = useCallback(() => {
|
||||
setUser(null);
|
||||
setAccessToken(null);
|
||||
accessTokenRef.current = null;
|
||||
queryClient.clear();
|
||||
}, [queryClient]);
|
||||
|
||||
async function refresh(): Promise<boolean> {
|
||||
const refresh = useCallback(async (): Promise<boolean> => {
|
||||
if (refreshPromise.current) return refreshPromise.current;
|
||||
refreshPromise.current = (async () => {
|
||||
const run = async () => {
|
||||
const { data } = await apiClient.POST("/api/v1/auth/refresh");
|
||||
if (!data) return false;
|
||||
const authentication = data as Authentication;
|
||||
setUser(authentication.user);
|
||||
setAccessToken(authentication.accessToken);
|
||||
accessTokenRef.current = authentication.accessToken;
|
||||
return true;
|
||||
try {
|
||||
const { data } = await apiClient.POST("/api/v1/auth/refresh");
|
||||
if (!data) {
|
||||
clearSession();
|
||||
return false;
|
||||
}
|
||||
applyAuthentication(data as Authentication);
|
||||
return true;
|
||||
} catch {
|
||||
clearSession();
|
||||
return false;
|
||||
}
|
||||
};
|
||||
return "locks" in navigator
|
||||
? navigator.locks.request("wealth-ledger-refresh", run)
|
||||
: run();
|
||||
try {
|
||||
return "locks" in navigator
|
||||
? navigator.locks.request("wealth-ledger-refresh", run)
|
||||
: run();
|
||||
} catch {
|
||||
clearSession();
|
||||
return false;
|
||||
}
|
||||
})().finally(() => {
|
||||
refreshPromise.current = null;
|
||||
});
|
||||
return refreshPromise.current;
|
||||
}
|
||||
}, [applyAuthentication, clearSession]);
|
||||
|
||||
useEffect(() => {
|
||||
void apiClient
|
||||
.POST("/api/v1/auth/refresh")
|
||||
.then(({ data }) => {
|
||||
if (!data) return;
|
||||
const authentication = data as Authentication;
|
||||
setUser(authentication.user);
|
||||
setAccessToken(authentication.accessToken);
|
||||
accessTokenRef.current = authentication.accessToken;
|
||||
})
|
||||
.finally(() => setReady(true));
|
||||
}, []);
|
||||
void refresh().finally(() => setReady(true));
|
||||
}, [refresh]);
|
||||
|
||||
async function authenticate(
|
||||
path: "/api/v1/auth/login" | "/api/v1/auth/register",
|
||||
@@ -82,19 +101,14 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
password: string,
|
||||
) {
|
||||
const authentication = await request(path, email, password);
|
||||
setUser(authentication.user);
|
||||
setAccessToken(authentication.accessToken);
|
||||
accessTokenRef.current = authentication.accessToken;
|
||||
applyAuthentication(authentication);
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await apiClient.POST("/api/v1/auth/logout");
|
||||
} finally {
|
||||
setUser(null);
|
||||
setAccessToken(null);
|
||||
accessTokenRef.current = null;
|
||||
queryClient.clear();
|
||||
clearSession();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,12 +116,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
configureAuthClient({
|
||||
accessToken: () => accessTokenRef.current,
|
||||
refresh,
|
||||
clear: () => {
|
||||
setUser(null);
|
||||
setAccessToken(null);
|
||||
accessTokenRef.current = null;
|
||||
queryClient.clear();
|
||||
},
|
||||
clear: clearSession,
|
||||
});
|
||||
return () => configureAuthClient(null);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user