Files
Neon-Desk/hooks/use-auth-guard.ts

48 lines
1.2 KiB
TypeScript

'use client';
import { useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { authClient } from '@/lib/auth-client';
type UseAuthGuardOptions = {
required?: boolean;
};
export function useAuthGuard(options: UseAuthGuardOptions = {}) {
const { required = true } = options;
const pathname = usePathname();
const router = useRouter();
const { data: rawSession, isPending } = authClient.useSession();
const session = (rawSession ?? null) as {
user?: {
id?: string;
name?: string | null;
email?: string | null;
image?: string | null;
};
} | null;
const isAuthenticated = Boolean(session?.user?.id);
useEffect(() => {
if (!required || isPending || isAuthenticated || pathname.startsWith('/auth')) {
return;
}
const currentPath = typeof window === 'undefined'
? pathname
: `${window.location.pathname}${window.location.search}`;
const query = currentPath && currentPath !== '/'
? `?next=${encodeURIComponent(currentPath)}`
: '';
router.replace(`/auth/signin${query}`);
}, [required, isPending, isAuthenticated, pathname, router]);
return {
session,
isPending,
isAuthenticated
};
}