implement better-auth auth with postgres and route protection
This commit is contained in:
@@ -1,16 +1,47 @@
|
||||
'use client';
|
||||
|
||||
export function useAuthGuard() {
|
||||
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: {
|
||||
user: {
|
||||
id: 1,
|
||||
name: 'Local Operator',
|
||||
email: 'operator@local.fiscal',
|
||||
image: null
|
||||
}
|
||||
},
|
||||
isPending: false,
|
||||
isAuthenticated: true
|
||||
session,
|
||||
isPending,
|
||||
isAuthenticated
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user