"use client"; import { useEffect } from 'react'; import { useRouter } from 'next/navigation'; import { useAuth } from '@/contexts/auth-context'; import { useApiKey } from '@/lib/hooks/use-api-key'; import { Loader2, Key, AlertCircle } from 'lucide-react'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Alert, AlertDescription } from '@/components/ui/alert'; interface RequireApiKeyProps { children: React.ReactNode; fallbackPath?: string; } export function RequireApiKey({ children, fallbackPath = '/dashboard/api-keys' }: RequireApiKeyProps) { const { user, authLoading } = useAuth(); const { hasApiKey, loading: apiKeyLoading, error } = useApiKey(); const router = useRouter(); useEffect(() => { if (!authLoading && !user) { router.push('/login'); return; } if (!authLoading && user && !apiKeyLoading && !hasApiKey) { // Don't redirect if already on API keys page if (window.location.pathname !== fallbackPath) { router.push(fallbackPath); } } }, [user, authLoading, hasApiKey, apiKeyLoading, router, fallbackPath]); // Show loading while checking authentication and API keys if (authLoading || apiKeyLoading) { return (

Loading...

); } // Redirect to login if not authenticated if (!user) { return null; } // Show API key required message if on a protected page without API key if (!hasApiKey && window.location.pathname !== fallbackPath) { return (
API Key Required You need to create an API key to access this feature
{error && ( {error} )}

API keys are required to access our scraping APIs and services. Create your first API key to get started.

); } // Render children if user has API key or is on the API keys page return <>{children}; }