This commit is contained in:
2025-12-08 23:52:36 +01:00
parent 2d0860d66c
commit 35f988f885
46 changed files with 4624 additions and 1041 deletions

View File

@@ -18,6 +18,7 @@ type AuthContextValue = {
loading: boolean;
login: (returnTo?: string) => void;
logout: () => Promise<void>;
refreshSession: () => Promise<void>;
};
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
@@ -32,41 +33,34 @@ export function AuthProvider({ initialSession = null, children }: AuthProviderPr
const [session, setSession] = useState<AuthSession | null>(initialSession);
const [loading, setLoading] = useState(false);
const fetchSession = useCallback(async () => {
try {
const res = await fetch('/api/auth/session', {
method: 'GET',
credentials: 'include',
});
if (!res.ok) {
setSession(null);
return;
}
const data = (await res.json()) as { session: AuthSession | null };
setSession(data.session ?? null);
} catch {
setSession(null);
}
}, []);
const refreshSession = useCallback(async () => {
await fetchSession();
}, [fetchSession]);
useEffect(() => {
if (initialSession) return;
let cancelled = false;
async function loadSession() {
try {
const res = await fetch('/api/auth/session', {
method: 'GET',
credentials: 'include',
});
if (!res.ok) {
if (!cancelled) setSession(null);
return;
}
const data = (await res.json()) as { session: AuthSession | null };
if (!cancelled) {
setSession(data.session ?? null);
}
} catch {
if (!cancelled) {
setSession(null);
}
}
}
loadSession();
return () => {
cancelled = true;
};
}, [initialSession]);
fetchSession();
}, [initialSession, fetchSession]);
const login = useCallback(
(returnTo?: string) => {
@@ -105,8 +99,9 @@ export function AuthProvider({ initialSession = null, children }: AuthProviderPr
loading,
login,
logout,
refreshSession,
}),
[session, loading, login, logout],
[session, loading, login, logout, refreshSession],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;