// Кто вошёл. Сервер хранит сессию в httpOnly-cookie, здесь только узнаём пользователя. import { useEffect } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import type { Role, UserDto } from '@kb/shared'; import { api, ApiError } from './api'; import { clearPrivateCaches } from './offline'; import { getStored, type RecentItem, setStored, useStored } from './store'; const USER_KEY = 'kb-user'; /** * Состояние входа: * loading: ещё спрашиваем сервер; * user: вошёл (или нет сети, но на этом устройстве уже входили: тогда читаем сохранённое); * null: не вошёл. */ export function useAuth() { const [cached, setCached] = useStored(USER_KEY, null); const q = useQuery({ queryKey: ['me'], queryFn: async () => { try { const { user } = await api<{ user: UserDto }>('/auth/me'); return user; } catch (e) { if (e instanceof ApiError && e.status === 401) return null; throw e; // нет сети: оставляем сохранённого пользователя } }, staleTime: 5 * 60_000, retry: false, }); useEffect(() => { if (q.data === undefined) return; if (q.data === null && cached) { // Сессия кончилась: убираем с устройства сохранённые закрытые статьи setCached(null); void clearPrivateCaches(); } else if (q.data && JSON.stringify(q.data) !== JSON.stringify(cached)) { setCached(q.data); } }, [q.data, cached, setCached]); // Если на устройстве уже входили, не ждём ответа сервера: сразу показываем приложение // (так оно открывается мгновенно и работает без сети). Сервер ответит 401: покажем экран входа. const user = q.data !== undefined ? q.data : (cached ?? (q.isError ? null : undefined)); return { user: user ?? null, loading: user === undefined, isEditor: user?.role === 'EDITOR' || user?.role === 'ADMIN', isAdmin: user?.role === 'ADMIN', }; } export const roleAtLeast = (role: Role | undefined, min: Role) => !!role && ['VIEWER', 'EDITOR', 'ADMIN'].indexOf(role) >= ['VIEWER', 'EDITOR', 'ADMIN'].indexOf(min); export function useAuthActions() { const qc = useQueryClient(); return { /** После входа: запоминаем пользователя и перезапрашиваем всё (теперь видны закрытые статьи). */ async onLogin(user: UserDto) { setStored(USER_KEY, user); qc.setQueryData(['me'], user); await syncPersonal(); await qc.invalidateQueries({ predicate: (query) => query.queryKey[0] !== 'me' }); }, async logout() { await api('/auth/logout', { method: 'POST' }).catch(() => undefined); setStored(USER_KEY, null); await clearPrivateCaches(); qc.setQueryData(['me'], null); qc.removeQueries({ predicate: (query) => query.queryKey[0] !== 'me' }); }, }; } // ---------- Синхронизация избранного и недавних между устройствами ---------- interface PersonalState { favorites: string[]; recent: RecentItem[]; } /** Объединяет локальные данные с серверными (ничего не теряя) и отправляет результат на сервер. */ export async function syncPersonal() { try { const remote = await api('/me/state'); const favs = [...new Set([...getStored('kb-fav', []), ...remote.favorites])]; setStored('kb-fav', favs); const recent = new Map(); for (const r of [...remote.recent, ...getStored('kb-recent', [])]) { recent.set(r.slug, Math.max(recent.get(r.slug) ?? 0, r.at)); } setStored( 'kb-recent', [...recent].map(([slug, at]) => ({ slug, at })).sort((a, b) => b.at - a.at).slice(0, 12), ); await pushFavorites(favs); } catch { // нет сети: синхронизируемся в следующий раз } } export const pushFavorites = (slugs: string[]) => api('/me/favorites', { method: 'PUT', json: { slugs } }).catch(() => undefined); export const pushRecentView = (slug: string) => api('/me/recent', { method: 'POST', json: { slug } }).catch(() => undefined);