import React, { useEffect, useState } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { apiCall } from '../utils/api'; const OAuthCallback: React.FC = () => { const navigate = useNavigate(); const [searchParams] = useSearchParams(); const [error, setError] = useState(null); const [processing, setProcessing] = useState(true); useEffect(() => { const handleCallback = async () => { // Check for errors from OAuth provider const errorParam = searchParams.get('error'); if (errorParam) { setError(`Authentication failed: ${errorParam}`); setProcessing(false); return; } // Get the authorization code const code = searchParams.get('code'); if (!code) { setError('No authorization code received'); setProcessing(false); return; } try { // Exchange the code for a token const response = await apiCall('/auth/google/exchange', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ code }), }); if (response.error === 'pending_approval') { // User needs approval localStorage.setItem('authToken', response.data.token); localStorage.setItem('user', JSON.stringify(response.data.user)); navigate('/pending-approval'); return; } if (response.data && response.data.token) { // Success! Store the token and user data localStorage.setItem('authToken', response.data.token); localStorage.setItem('user', JSON.stringify(response.data.user)); // Redirect to dashboard window.location.href = '/'; } else { setError('Failed to authenticate'); } } catch (err: any) { console.error('OAuth callback error:', err); if (err.message?.includes('pending_approval')) { // This means the user was created but needs approval navigate('/'); } else { setError(err.message || 'Authentication failed'); } } finally { setProcessing(false); } }; handleCallback(); }, [navigate, searchParams]); if (processing) { return (

Completing sign in...

); } if (error) { return (

Authentication Failed

{error}

); } return null; }; export default OAuthCallback;