fix and update

This commit is contained in:
lendry
2026-07-01 00:26:16 +03:00
parent a0c1722a8d
commit 115fc140af
7 changed files with 115 additions and 28 deletions

View File

@@ -5,6 +5,7 @@ import { usePathname, useRouter } from 'next/navigation';
import {
apiFetch,
ApiError,
AUTH_SESSION_INVALID_EVENT,
AUTH_REFRESH_KEY,
AUTH_SESSION_KEY,
AUTH_TOKEN_KEY,
@@ -106,14 +107,12 @@ function applySessionState(
}
function readInitialAuthState() {
if (typeof window === 'undefined') {
return { token: null as string | null, hasStoredSession: false };
}
const token = window.localStorage.getItem(AUTH_TOKEN_KEY);
const refresh = window.localStorage.getItem(AUTH_REFRESH_KEY);
// Первичный render должен совпадать на сервере и в браузере. Токены из
// localStorage читаются уже в refreshProfile(), иначе авторизованная вкладка
// получает hydration mismatch (React #418) ещё до запуска эффектов.
return {
token,
hasStoredSession: Boolean(refresh || token)
token: null as string | null,
hasStoredSession: false
};
}
@@ -274,6 +273,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
router.push('/auth/login');
}, [clearPinLock, router]);
React.useEffect(() => {
function handleInvalidSession() {
if (!window.localStorage.getItem(AUTH_TOKEN_KEY) && !window.localStorage.getItem(AUTH_REFRESH_KEY)) return;
logout();
}
window.addEventListener(AUTH_SESSION_INVALID_EVENT, handleInvalidSession);
return () => window.removeEventListener(AUTH_SESSION_INVALID_EVENT, handleInvalidSession);
}, [logout]);
const applyUserPatch = React.useCallback((patch: Partial<PublicUser>) => {
setUser((current) => {
if (!current) return current;
@@ -291,7 +300,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const task: Promise<void> = (async () => {
const currentToken = window.localStorage.getItem(AUTH_TOKEN_KEY);
const refreshToken = window.localStorage.getItem(AUTH_REFRESH_KEY);
setHasStoredSession(Boolean(refreshToken));
setHasStoredSession(Boolean(currentToken || refreshToken));
if (!currentToken && !refreshToken) {
window.localStorage.removeItem(AUTH_USER_CACHE_KEY);