fix(auth): не выкидывать пользователя при сетевой ошибке refresh, access token 30 дней
- queryClient: refreshSession возвращает reason (network/unauthorized); при network-ошибке не делаем logout, а бросаем network_error_during_refresh. - useAuth: checkAuth и refreshUser не сбрасывают сессию при network-ошибке во время refresh, переводят в офлайн-режим. - auth.service: remember берётся из сессии, race tolerance 5 минут. - access token lifetime унифицирован до 30 дней по умолчанию, cookie maxAge теперь совпадает с JWT expiry (было 15 минут fallback).
This commit is contained in:
@@ -68,11 +68,14 @@ export function useAuthProvider() {
|
||||
}
|
||||
} catch (error) {
|
||||
// Network failure: keep offline session alive if we have a cached user.
|
||||
// A failed refresh because the laptop/phone was asleep or had no signal
|
||||
// must NOT be treated as a permanent logout.
|
||||
if (
|
||||
error instanceof TypeError ||
|
||||
(error instanceof DOMException && error.name === 'AbortError') ||
|
||||
!navigator.onLine ||
|
||||
(error instanceof Error && error.message === 'AUTH_CHECK_TIMEOUT')
|
||||
(error instanceof Error && error.message === 'AUTH_CHECK_TIMEOUT') ||
|
||||
(error instanceof Error && error.message === 'network_error_during_refresh')
|
||||
) {
|
||||
enterOfflineSession(cachedUser);
|
||||
return;
|
||||
@@ -141,7 +144,9 @@ export function useAuthProvider() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const handleAuthFailure = () => {
|
||||
const handleAuthFailure = (event: Event) => {
|
||||
const detail = (event as CustomEvent).detail;
|
||||
console.warn('[Auth] Unauthorized, redirecting to login:', detail);
|
||||
logout().finally(() => {
|
||||
const currentPath = window.location.pathname + window.location.search;
|
||||
const isAuthPage = currentPath.startsWith('/login') || currentPath === '/';
|
||||
@@ -198,8 +203,16 @@ export function useAuthProvider() {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('User refresh failed:', error);
|
||||
setUser(null);
|
||||
authService.clearCachedUser();
|
||||
// Don't clear the session if we just couldn't reach the server.
|
||||
const isNetworkError =
|
||||
error instanceof TypeError ||
|
||||
(error instanceof DOMException && error.name === 'AbortError') ||
|
||||
!navigator.onLine ||
|
||||
(error instanceof Error && error.message === 'network_error_during_refresh');
|
||||
if (!isNetworkError) {
|
||||
setUser(null);
|
||||
authService.clearCachedUser();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
export const AUTH_FAILURE_EVENT = 'auth:unauthorized';
|
||||
|
||||
export function dispatchAuthFailure(): void {
|
||||
window.dispatchEvent(new CustomEvent(AUTH_FAILURE_EVENT));
|
||||
export function dispatchAuthFailure(reason?: string): void {
|
||||
// Capture the reason and the current navigation context for easier debugging
|
||||
// of unexpected logouts on background tabs/PWAs.
|
||||
const detail = {
|
||||
reason: reason ?? 'unknown',
|
||||
url: window.location.href,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.warn('[Auth] dispatchAuthFailure:', detail);
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent(AUTH_FAILURE_EVENT, { detail }));
|
||||
}
|
||||
|
||||
@@ -114,12 +114,16 @@ export async function fetchWithTimeout(
|
||||
}
|
||||
|
||||
// Singleton refresh promise — prevents concurrent refresh races
|
||||
let _refreshPromise: Promise<boolean> | null = null;
|
||||
let _refreshPromise: Promise<RefreshResult> | null = null;
|
||||
|
||||
async function refreshSession(): Promise<boolean> {
|
||||
type RefreshResult =
|
||||
| { ok: true }
|
||||
| { ok: false; reason: 'network' | 'unauthorized' };
|
||||
|
||||
async function refreshSession(): Promise<RefreshResult> {
|
||||
if (_refreshPromise) return _refreshPromise;
|
||||
|
||||
_refreshPromise = (async (): Promise<boolean> => {
|
||||
_refreshPromise = (async (): Promise<RefreshResult> => {
|
||||
try {
|
||||
const res = await fetchWithTimeout(
|
||||
'/api/auth/refresh',
|
||||
@@ -136,17 +140,19 @@ async function refreshSession(): Promise<boolean> {
|
||||
const result = await res.json();
|
||||
if (result.success && result.user) {
|
||||
authService.setCachedUser(result.user);
|
||||
return true;
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
// Server explicitly rejected the session.
|
||||
return { ok: false, reason: 'unauthorized' };
|
||||
} catch (error) {
|
||||
if (isNetworkFailure(error)) {
|
||||
console.warn('Token refresh skipped — no network connection or timeout');
|
||||
} else {
|
||||
console.error('Token refresh failed:', error);
|
||||
return { ok: false, reason: 'network' };
|
||||
}
|
||||
console.error('Token refresh failed:', error);
|
||||
return { ok: false, reason: 'unauthorized' };
|
||||
}
|
||||
return false;
|
||||
})().finally(() => {
|
||||
_refreshPromise = null;
|
||||
});
|
||||
@@ -210,8 +216,8 @@ export async function apiRequest(
|
||||
|
||||
// If we got 401/403, try to refresh the session and retry once.
|
||||
if ((res.status === 401 || res.status === 403) && !url.includes('/api/auth/')) {
|
||||
const refreshSuccess = await refreshSession();
|
||||
if (refreshSuccess) {
|
||||
const refreshResult = await refreshSession();
|
||||
if (refreshResult.ok) {
|
||||
const retryRes = await fetchWithTimeout(
|
||||
url,
|
||||
{ method, headers, body, credentials: "include" },
|
||||
@@ -220,8 +226,13 @@ export async function apiRequest(
|
||||
await throwIfResNotOk(retryRes);
|
||||
return retryRes;
|
||||
}
|
||||
// Refresh failed — session is permanently invalid
|
||||
dispatchAuthFailure();
|
||||
if (refreshResult.reason === 'network') {
|
||||
// The session may still be valid; we just couldn't reach the server.
|
||||
// Don't force a logout — propagate a generic error so the caller can retry.
|
||||
throw new Error('network_error_during_refresh');
|
||||
}
|
||||
// Server explicitly rejected the session — permanent logout.
|
||||
dispatchAuthFailure('refresh_rejected_by_server');
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
|
||||
@@ -248,8 +259,8 @@ export const getQueryFn: <T>(options: {
|
||||
|
||||
// Пытаемся обновить сессию и повторить запрос (только если это не auth endpoint)
|
||||
if (!url.includes('/api/auth/')) {
|
||||
const refreshSuccess = await refreshSession();
|
||||
if (refreshSuccess) {
|
||||
const refreshResult = await refreshSession();
|
||||
if (refreshResult.ok) {
|
||||
const retryRes = await fetchWithTimeout(url, {
|
||||
credentials: "include",
|
||||
}, 10000);
|
||||
@@ -262,8 +273,12 @@ export const getQueryFn: <T>(options: {
|
||||
await throwIfResNotOk(retryRes);
|
||||
return await retryRes.json();
|
||||
}
|
||||
if (refreshResult.reason === 'network') {
|
||||
// Don't force logout when the refresh request itself failed on the network.
|
||||
throw new Error('network_error_during_refresh');
|
||||
}
|
||||
// Refresh failed — session is permanently invalid
|
||||
dispatchAuthFailure();
|
||||
dispatchAuthFailure('refresh_rejected_by_server');
|
||||
throw new UnauthorizedError();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user