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:
2026-11-09 13:32:46 +01:00
co-authored by Claude Sonnet 5.5
parent 2cdcb9d868
commit 2f3f7fbb2f
11 changed files with 299 additions and 15 deletions
@@ -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>;
}