Repository Public
1"use client";2import { useQuery, useQueryClient } from "@tanstack/react-query";3import { createContext, useCallback, useContext, useEffect, useMemo, type ReactNode } from "react";4import { apiGet, apiPost, transport, type Schemas } from "@/api/client";5import { ApiError } from "@/api/errors";6import { useI18n } from "@/i18n";78export type Me = Schemas["Me"];9export const ME_KEY = ["/me", { path: null, query: null }] as const;1011export interface Session {12 status: "loading" | "authenticated" | "anonymous" | "error";13 me: Me | null;14 error: ApiError | null;15 /** UI reflection of the server decision: GET /me lists the effective permissions. The server enforces them. */16 can: (permission: string) => boolean;17 /** Seed the session right after a successful ceremony (sign-in, registration). */18 adopt: (auth: { csrf_token?: string | undefined; user: Schemas["User"]; session: Schemas["Session"] }) => Promise<void>;19 refresh: () => Promise<void>;20 signOut: () => Promise<void>;21}2223const Ctx = createContext<Session | null>(null);2425export function SessionProvider({ children }: { children: ReactNode }) {26 const qc = useQueryClient();27 const { setLocale, locale } = useI18n();28 const q = useQuery<Me | null, ApiError>({29 queryKey: ME_KEY,30 queryFn: async () => {31 try {32 const me = await apiGet("/me");33 if (me.csrf_token) transport.setCsrf(me.csrf_token);34 return me;35 } catch (e) {36 if (e instanceof ApiError && e.unauthenticated) {37 transport.setCsrf(null);38 return null;39 }40 throw e;41 }42 },43 staleTime: 60_000,44 refetchOnWindowFocus: true,45 retry: (count, e) => (e.status === 0 || e.status >= 500) && count < 2,46 });4748 // any API call answering 401 means the session ended (expiry, revocation): drop to anonymous49 useEffect(() => {50 transport.setHooks({51 onUnauthenticated: () => {52 transport.setCsrf(null);53 qc.setQueryData(ME_KEY, null);54 },55 });56 return () => transport.setHooks({ onUnauthenticated: undefined });57 }, [qc]);5859 const userLocale = q.data?.user.locale;60 useEffect(() => {61 if (userLocale && userLocale !== locale) setLocale(userLocale);62 // eslint-disable-next-line react-hooks/exhaustive-deps -- follow the profile when it changes, not local previews63 }, [userLocale]);6465 const refresh = useCallback(async () => {66 await qc.invalidateQueries({ queryKey: ME_KEY });67 }, [qc]);68 const adopt = useCallback<Session["adopt"]>(69 async (auth) => {70 if (auth.csrf_token) transport.setCsrf(auth.csrf_token);71 await qc.fetchQuery({ queryKey: ME_KEY, staleTime: 0 });72 },73 [qc],74 );75 const signOut = useCallback(async () => {76 try {77 await apiPost("/auth/logout");78 } catch {79 /* the session may already be gone: the local state is cleared either way */80 }81 transport.setCsrf(null);82 qc.setQueryData(ME_KEY, null);83 // drop every cached server answer of the previous session (the /me observer itself must stay attached)84 qc.removeQueries({ predicate: (q) => q.queryKey[0] !== ME_KEY[0] });85 }, [qc]);8687 const value = useMemo<Session>(() => {88 const me = q.data ?? null;89 const perms = new Set(me?.permissions ?? []);90 return {91 status: q.data === undefined ? (q.isError ? "error" : "loading") : q.data === null ? "anonymous" : "authenticated",92 me,93 error: q.error,94 can: (p) => perms.has(p),95 adopt,96 refresh,97 signOut,98 };99 }, [q.data, q.isError, q.error, adopt, refresh, signOut]);100 return <Ctx.Provider value={value}>{children}</Ctx.Provider>;101}102103export function useSession(): Session {104 const v = useContext(Ctx);105 if (!v) throw new Error("useSession outside SessionProvider");106 return v;107}108109/** Narrowed access for screens inside the authenticated shell. */110export function useMe(): Me {111 const { me } = useSession();112 if (!me) throw new Error("useMe outside the authenticated shell");113 return me;114}115