Neah/components/auth/auth-check.tsx
2025-05-02 12:56:20 +02:00

61 lines
1.9 KiB
TypeScript

"use client";
import { useSession, signOut } from "next-auth/react";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useCallback } from "react";
export function AuthCheck({ children }: { children: React.ReactNode }) {
const { data: session, status } = useSession();
const pathname = usePathname();
const router = useRouter();
// Create a memoized function to handle sign out to prevent excessive rerenders
const handleSessionError = useCallback((error: string) => {
console.log(`Session error detected: ${error}, signing out`);
// Force a clean sign out and redirect to login
signOut({
callbackUrl: `/signin?error=${encodeURIComponent(error)}`,
redirect: true
});
}, []);
useEffect(() => {
// Handle expired sessions immediately
if (session?.error) {
handleSessionError(session.error);
return;
}
// Handle unauthenticated status (after checking for errors)
if (status === "unauthenticated" && !pathname.includes("/signin")) {
console.log("User is not authenticated, redirecting to signin page");
router.push("/signin");
}
}, [status, session, router, pathname, handleSessionError]);
// Show loading state
if (status === "loading") {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto"></div>
<p className="mt-4 text-gray-600">Chargement...</p>
</div>
</div>
);
}
// Do not render with session errors
if (session?.error) {
return null;
}
// Do not render if not authenticated and not on signin page
if (status === "unauthenticated" && !pathname.includes("/signin")) {
return null;
}
// Authentication is valid, render children
return <>{children}</>;
}