'use client'; import { useState, useEffect, useRef } from 'react'; import { apiClient, isAuthorizedState } from '@/utils/api'; import { createGlobalState } from 'react-global-hooks'; interface AuthWrapperProps { authRequired: boolean; children: React.ReactNode | React.ReactNode[]; } export default function AuthWrapper({ authRequired, children }: AuthWrapperProps) { const [token, setToken] = useState(''); // start with true, and deauth if needed const [isAuthorizedGlobal, setIsAuthorized] = isAuthorizedState.use(); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(''); const [isBrowser, setIsBrowser] = useState(false); const inputRef = useRef(null); const isAuthorized = authRequired ? isAuthorizedGlobal : true; // Set isBrowser to true when component mounts useEffect(() => { setIsBrowser(true); // Get token from localStorage only after component has mounted const storedToken = localStorage.getItem('AI_TOOLKIT_AUTH') || ''; setToken(storedToken); checkAuth(); }, []); // auto focus on input when not authorized useEffect(() => { if (isAuthorized) { return; } setTimeout(() => { if (inputRef.current) { inputRef.current.focus(); } }, 100); }, [isAuthorized]); const checkAuth = async () => { // always get current stored token here to avoid state race conditions const currentToken = localStorage.getItem('AI_TOOLKIT_AUTH') || ''; if (!authRequired || isLoading || currentToken === '') { return; } setIsLoading(true); setError(''); try { const response = await apiClient.get('/api/auth'); if (response.data.isAuthenticated) { setIsAuthorized(true); } else { setIsAuthorized(false); setError('Invalid token. Please try again.'); } } catch (err) { setIsAuthorized(false); console.log(err); setError('Invalid token. Please try again.'); } setIsLoading(false); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(''); if (!token.trim()) { setError('Please enter your token'); return; } if (isBrowser) { localStorage.setItem('AI_TOOLKIT_AUTH', token); checkAuth(); } }; if (isAuthorized) { return <>{children}; } return (
{/* Left side - decorative or brand area */}
{/* Replace with your own logo */}
Ostris AI Toolkit

AI Toolkit

{/* Right side - login form */}
{/* Mobile logo */}
Ostris AI Toolkit

AI Toolkit

setToken(e.target.value)} className="w-full px-4 py-3 rounded-lg bg-gray-800 border border-gray-700 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 text-gray-100 transition duration-200" placeholder="Enter your token" />
{error && (
{error}
)}
); }