Admin: gebruikerslijst blijft actueel, sessie blijft behouden bij tijdelijke refresh-fouten
- Refresh wist de sessie alleen nog bij 400/401/403; 429/5xx/netwerkfout behoudt hem (opstart: rustig opnieuw proberen met backoff, anders gast zonder het cookie te raken) - Refresh is single-flight (opstart, 401-interceptor, profiel delen een lopende aanvraag) - GET-verzoeken met cache: no-store; gebruikerslijst: refetch bij focus en poll 45 s; sessie ververst als de eigen rol in de lijst afwijkt Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
@@ -9,7 +9,9 @@ import { api } from '@/lib/api-client';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE, mockUser } from '@/features/auth/mocks/fixtures';
|
||||
import { mockGuest } from '@/test/utils';
|
||||
import { makeAuthResponse } from '@/features/auth/mocks/fixtures';
|
||||
import i18n from '@/i18n/config';
|
||||
import { refreshBackoff } from '@/lib/refreshPolicy';
|
||||
|
||||
function wrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
@@ -85,4 +87,96 @@ describe('AuthContext', () => {
|
||||
|
||||
await waitFor(() => expect(result.current.isAuthenticated).toBe(false));
|
||||
});
|
||||
|
||||
describe('refresh failures that say nothing about the session', () => {
|
||||
const original = [...refreshBackoff.delays];
|
||||
beforeEach(() => {
|
||||
refreshBackoff.delays = [5, 5, 5];
|
||||
});
|
||||
afterEach(() => {
|
||||
refreshBackoff.delays = original;
|
||||
});
|
||||
|
||||
it.each([429, 502, 503])('keeps retrying quietly at start-up on a %i and then signs in', async (status) => {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
||||
calls += 1;
|
||||
if (calls <= 2) return HttpResponse.json({ status }, { status });
|
||||
return HttpResponse.json(makeAuthResponse());
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('authenticated'));
|
||||
expect(calls).toBe(3);
|
||||
});
|
||||
|
||||
it('falls back to guest (without a verdict on the cookie) after the last retry', async () => {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
||||
calls += 1;
|
||||
return HttpResponse.json({ status: 429 }, { status: 429 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('guest'));
|
||||
expect(calls).toBe(1 + refreshBackoff.delays.length);
|
||||
});
|
||||
|
||||
it('does not retry when the server rejects the cookie (401)', async () => {
|
||||
let calls = 0;
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
||||
calls += 1;
|
||||
return HttpResponse.json({ status: 401 }, { status: 401 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('guest'));
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps the session when a refresh after a 401 is rate limited', async () => {
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
await waitFor(() => expect(result.current.isAuthenticated).toBe(true));
|
||||
|
||||
server.use(
|
||||
http.get(`${API_BASE}/api/v1/widgets`, () => HttpResponse.json({ status: 401 }, { status: 401 })),
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () => HttpResponse.json({ status: 429 }, { status: 429 })),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await expect(api.get('/api/v1/widgets')).rejects.toThrow();
|
||||
});
|
||||
|
||||
expect(result.current.isAuthenticated).toBe(true);
|
||||
});
|
||||
|
||||
it('runs one refresh at a time: parallel callers share the request', async () => {
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
await waitFor(() => expect(result.current.isAuthenticated).toBe(true));
|
||||
|
||||
let calls = 0;
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, async () => {
|
||||
calls += 1;
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
return HttpResponse.json(makeAuthResponse());
|
||||
}),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await Promise.all([result.current.refresh(), result.current.refresh(), result.current.refresh()]);
|
||||
});
|
||||
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import type { AuthResponse } from '@/features/auth/services/types';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { isAuthRejection, refreshBackoff } from '@/lib/refreshPolicy';
|
||||
import { changeLanguage } from '@/i18n/config';
|
||||
import { AuthContext, type AuthContextValue, type AuthStatus } from '@/features/auth/context/auth-context';
|
||||
|
||||
@@ -44,19 +45,39 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setStatus('guest');
|
||||
}, []);
|
||||
|
||||
const refresh = useCallback(async (): Promise<string | null> => {
|
||||
// One refresh at a time per page. The refresh token is single-use on the server: two parallel refreshes
|
||||
// (start-up + a 401 retry, StrictMode's double mount) would present the same token twice, and the second
|
||||
// one would be treated as token reuse and sign the user out. Callers share the running promise.
|
||||
const inFlight = useRef<Promise<string | null> | null>(null);
|
||||
|
||||
const refreshOnce = useCallback(async (): Promise<string | null> => {
|
||||
try {
|
||||
const data = await api.post<AuthResponse>('/api/v1/auth/refresh', undefined, {
|
||||
skipAuthRefresh: true,
|
||||
});
|
||||
applySession(data);
|
||||
return data.accessToken;
|
||||
} catch {
|
||||
clearSession();
|
||||
return null;
|
||||
} catch (err) {
|
||||
// Only a server verdict on the cookie (400/401/403) ends the session. A rate limit, a restart (5xx)
|
||||
// or a network error says nothing about it: keep the session and let the caller decide.
|
||||
if (isAuthRejection(err)) {
|
||||
clearSession();
|
||||
return null;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}, [applySession, clearSession]);
|
||||
|
||||
/** Resolves to the new token, null when the server rejected the session, and rejects on a transient failure. */
|
||||
const refresh = useCallback((): Promise<string | null> => {
|
||||
if (inFlight.current !== null) return inFlight.current;
|
||||
const running = refreshOnce().finally(() => {
|
||||
inFlight.current = null;
|
||||
});
|
||||
inFlight.current = running;
|
||||
return running;
|
||||
}, [refreshOnce]);
|
||||
|
||||
const login = useCallback(
|
||||
async (email: string, password: string) => {
|
||||
const data = await api.post<AuthResponse>(
|
||||
@@ -92,10 +113,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
// Silent refresh on app mount (BR-U1-01). This intentionally synchronizes
|
||||
// React state with the external session (httpOnly cookie) on startup.
|
||||
// A transient failure (429, 502 during a restart, network) is retried a few times with a backoff; if it
|
||||
// still fails the visitor is a guest for now, and the refresh cookie is untouched so a reload can recover.
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const delays = refreshBackoff.delays;
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
await refresh();
|
||||
return;
|
||||
} catch {
|
||||
if (cancelled || attempt >= delays.length) break;
|
||||
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
||||
if (cancelled) return;
|
||||
}
|
||||
}
|
||||
if (!cancelled) clearSession();
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [refresh, clearSession]);
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({
|
||||
|
||||
@@ -12,7 +12,11 @@ export interface AuthContextValue {
|
||||
isAuthenticated: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
/** Performs a cookie-based silent refresh; resolves to the new token or null. */
|
||||
/**
|
||||
* Cookie-based silent refresh, one at a time (callers share the running one). Resolves to the new token, to
|
||||
* null when the server rejected the session (it is then cleared), and rejects on a transient failure (429, 5xx,
|
||||
* network) with the session left as it was.
|
||||
*/
|
||||
refresh: () => Promise<string | null>;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ export function useUpdateProfile() {
|
||||
mutationFn: (data) => api.put<UserListItem>('/api/v1/Users/me', data),
|
||||
onSuccess: () => {
|
||||
// Sync AuthContext with updated name/email via token refresh
|
||||
void refresh();
|
||||
void refresh().catch(() => undefined); // a transient failure keeps the session as it is
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -209,3 +209,41 @@ describe('UsersPage', () => {
|
||||
expect(screen.getByTestId('invite-dialog-email')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('UsersPage keeps up with changes made elsewhere', () => {
|
||||
it('refreshes the session when the list shows a different role for the signed-in user', async () => {
|
||||
let refreshCalls = 0;
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
||||
refreshCalls += 1;
|
||||
// first call: start-up session; later calls: the role was changed in the meantime
|
||||
return HttpResponse.json(
|
||||
makeAuthResponse({ user: { ...mockUser, role: refreshCalls === 1 ? 'Owner' : 'Administrator' } }),
|
||||
);
|
||||
}),
|
||||
http.get(USERS_URL, () =>
|
||||
HttpResponse.json(getMockUsers().map((u) => (u.id === mockUser.id ? { ...u, role: 'Administrator' } : u))),
|
||||
),
|
||||
);
|
||||
renderApp('/users');
|
||||
|
||||
await screen.findByTestId('users-table');
|
||||
await vi.waitFor(() => expect(refreshCalls).toBeGreaterThanOrEqual(2));
|
||||
});
|
||||
|
||||
it('does not refresh the session while the roles agree', async () => {
|
||||
let refreshCalls = 0;
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
||||
refreshCalls += 1;
|
||||
return HttpResponse.json(makeAuthResponse());
|
||||
}),
|
||||
);
|
||||
renderApp('/users');
|
||||
|
||||
await screen.findByTestId('users-table');
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
expect(refreshCalls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { buildAppUrl } from '@/lib/links';
|
||||
import { toast } from 'sonner';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
@@ -64,7 +64,7 @@ function formatDate(iso: string) {
|
||||
|
||||
export function UsersPage() {
|
||||
const { t } = useTranslation();
|
||||
const { user: currentUser, logout } = useAuth();
|
||||
const { user: currentUser, logout, refresh } = useAuth();
|
||||
const [inviteDialogOpen, setInviteDialogOpen] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<UserListItem | null>(null);
|
||||
const [selfRoleChangeTarget, setSelfRoleChangeTarget] = useState<{
|
||||
@@ -76,6 +76,15 @@ export function UsersPage() {
|
||||
userName: string;
|
||||
} | null>(null);
|
||||
const { data: users, isPending, isError } = useUsers();
|
||||
|
||||
// When somebody else changed the signed-in user's role, the list shows it before the session does: refresh
|
||||
// the session (token and menu) once so the sidebar follows the new role.
|
||||
const ownRoleInList = users?.find((u) => u.id === currentUser?.id)?.role;
|
||||
useEffect(() => {
|
||||
if (ownRoleInList && currentUser && ownRoleInList !== currentUser.role) {
|
||||
void refresh().catch(() => undefined);
|
||||
}
|
||||
}, [ownRoleInList, currentUser, refresh]);
|
||||
const changeRole = useChangeRole();
|
||||
const setUserActive = useSetUserActive();
|
||||
const deleteUser = useDeleteUser();
|
||||
|
||||
@@ -166,3 +166,44 @@ describe('useDeleteUser', () => {
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
});
|
||||
});
|
||||
|
||||
describe('useUsers freshness', () => {
|
||||
it('looks again on window focus and polls lightly (45 s)', async () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
const { result } = renderHook(() => useUsers(), { wrapper });
|
||||
await waitFor(() => expect(result.current.isPending).toBe(false));
|
||||
|
||||
const options = queryClient.getQueryCache().find({ queryKey: ['users'] })!.options as {
|
||||
refetchInterval?: unknown;
|
||||
refetchOnWindowFocus?: unknown;
|
||||
};
|
||||
expect(options.refetchInterval).toBe(45_000);
|
||||
expect(options.refetchOnWindowFocus).toBe('always');
|
||||
});
|
||||
|
||||
it('reloads the list right after a role change', async () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
const { result } = renderHook(() => ({ list: useUsers(), change: useChangeRole() }), { wrapper });
|
||||
await waitFor(() => expect(result.current.list.isPending).toBe(false));
|
||||
const target = getMockUsers().find((u) => u.role === 'User')!;
|
||||
let changed = false;
|
||||
server.use(
|
||||
http.put(`${USERS_URL}/:userId/role`, () => {
|
||||
changed = true;
|
||||
return new HttpResponse(null, { status: 200 });
|
||||
}),
|
||||
http.get(USERS_URL, () => HttpResponse.json(getMockUsers().map((u) => (u.id === target.id && changed ? { ...u, role: 'Administrator' } : u)))),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.change.mutateAsync({ userId: target.id, newRole: 'Administrator' });
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.list.data?.find((u) => u.id === target.id)?.role).toBe('Administrator'));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,11 @@ export function useUsers() {
|
||||
return useQuery<UserListItem[], Error>({
|
||||
queryKey: ['users'],
|
||||
queryFn: () => api.get<UserListItem[]>('/api/v1/Users'),
|
||||
staleTime: 30_000,
|
||||
staleTime: 15_000,
|
||||
// Another administrator may change the list: look again when the tab is shown and every 45 s
|
||||
// (the poll pauses while the tab is in the background).
|
||||
refetchOnWindowFocus: 'always',
|
||||
refetchInterval: 45_000,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -211,3 +211,35 @@ describe('ApiClient', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('ApiClient 401 interceptor with a refresh that fails for a transient reason', () => {
|
||||
it('does not call the auth failure handler and passes on the original 401', async () => {
|
||||
server.use(http.get(`${BASE}/protected-transient`, () => new HttpResponse(null, { status: 401 })));
|
||||
|
||||
const client = makeClient();
|
||||
const failureFn = vi.fn();
|
||||
client.setRefreshHandler(async () => {
|
||||
throw new Error('rate limited');
|
||||
});
|
||||
client.setAuthFailureHandler(failureFn);
|
||||
|
||||
await expect(client.get('/protected-transient')).rejects.toThrow(ProblemDetailsError);
|
||||
expect(failureFn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks for GET responses straight from the server (no cache)', async () => {
|
||||
let cacheMode: string | undefined;
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
cacheMode = init?.cache;
|
||||
return original(input, init);
|
||||
}) as typeof fetch;
|
||||
server.use(http.get(`${BASE}/nocache`, () => HttpResponse.json({})));
|
||||
try {
|
||||
await makeClient().get('/nocache');
|
||||
} finally {
|
||||
globalThis.fetch = original;
|
||||
}
|
||||
expect(cacheMode).toBe('no-store');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -99,10 +99,18 @@ export class ApiClient {
|
||||
|
||||
// 401 intercept: try a single cookie-based refresh, then retry once (BR-U1-04).
|
||||
if (response.status === 401 && !options.skipAuthRefresh && this.refreshHandler !== null) {
|
||||
const newToken = await this.refreshHandler();
|
||||
let newToken: string | null = null;
|
||||
let rejected = false;
|
||||
try {
|
||||
newToken = await this.refreshHandler();
|
||||
rejected = newToken === null;
|
||||
} catch {
|
||||
// Transient (rate limit, restart, network): the session is not known to be gone, so it is not
|
||||
// cleared; the caller gets the original 401.
|
||||
}
|
||||
if (newToken !== null) {
|
||||
response = await this.rawFetch(path, options);
|
||||
} else {
|
||||
} else if (rejected) {
|
||||
this.authFailureHandler?.();
|
||||
}
|
||||
}
|
||||
@@ -126,6 +134,8 @@ export class ApiClient {
|
||||
...rest,
|
||||
headers: finalHeaders,
|
||||
credentials: 'include',
|
||||
// A list read after a change must come from the server, never from an intermediate cache.
|
||||
...(rest.method === 'GET' ? { cache: 'no-store' as const } : {}),
|
||||
body: body !== undefined && body !== null ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
} catch (cause) {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ProblemDetailsError } from '@/lib/api-client';
|
||||
|
||||
/** Waits (ms) between the quiet start-up retries of the silent refresh; tests shorten this. */
|
||||
export const refreshBackoff = { delays: [400, 1200, 2500] as number[] };
|
||||
|
||||
/**
|
||||
* True when the SERVER says the refresh cookie is not (or no longer) valid: 400, 401 or 403. Anything else -
|
||||
* a rate limit (429), a restart (5xx, 502 from the proxy) or a network error - says nothing about the session,
|
||||
* so the session must not be dropped for it.
|
||||
*/
|
||||
export function isAuthRejection(error: unknown): boolean {
|
||||
return error instanceof ProblemDetailsError && (error.status === 400 || error.status === 401 || error.status === 403);
|
||||
}
|
||||
Reference in New Issue
Block a user