'use client'; import { useEffect, useState } from 'react'; import { useRouter, usePathname } from 'next/navigation'; import { useStore } from '@/lib/store'; import { authApi } from '@/lib/api'; import { Loader2 } from 'lucide-react'; // Pages that don't require authentication const PUBLIC_PAGES = ['/login', '/signup']; export default function AuthProvider({ children }: { children: React.ReactNode }) { const router = useRouter(); const pathname = usePathname(); const { user, token, setUser, setToken, logout } = useStore(); const [loading, setLoading] = useState(true); useEffect(() => { const initAuth = async () => { // If on a public page, no need to check auth if (PUBLIC_PAGES.includes(pathname)) { setLoading(false); return; } // Try to verify auth with the backend (uses cookie automatically) try { const response = await authApi.me(); if (response.data) { const userData = { id: response.data.id, email: response.data.email, name: response.data.display_name || response.data.email, role: response.data.role, avatar_url: response.data.avatar_url, }; setUser(userData); // Also set a dummy token for compatibility (actual auth is via cookie) setToken('cookie-auth'); } } catch (error) { // Not authenticated, clear state and redirect console.log('Not authenticated, redirecting to login'); logout(); router.push('/login'); } setLoading(false); }; initAuth(); }, [pathname]); // Show loading spinner while checking auth if (loading && !PUBLIC_PAGES.includes(pathname)) { return (
Loading...