Files
IdP/apps/frontend/hooks/use-require-auth.ts
2026-06-30 16:03:33 +03:00

32 lines
934 B
TypeScript

'use client';
import { useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '@/components/id/auth-provider';
export function useRequireAuth() {
const router = useRouter();
const pathname = usePathname();
const { user, isLoading, isApiReady, isSessionReady, isPinLocked, hasStoredSession, token } = useAuth();
const authResolved = !isLoading && isSessionReady;
const isAuthenticated = Boolean(user || isPinLocked);
useEffect(() => {
if (!authResolved) return;
if (isAuthenticated || hasStoredSession || token) return;
if (pathname.startsWith('/auth/')) return;
router.replace('/auth/login');
}, [authResolved, hasStoredSession, isAuthenticated, pathname, router, token]);
return {
user,
isLoading,
isPinLocked,
isApiReady,
isSessionReady,
authResolved,
isReady: authResolved && isAuthenticated && isApiReady
};
}