diff --git a/OAuth2-Backend-Approach.md b/OAuth2-Backend-Approach.md index 9e6efe9..a57c492 100644 --- a/OAuth2-Backend-Approach.md +++ b/OAuth2-Backend-Approach.md @@ -248,70 +248,49 @@ curl -X GET "https://www.googleapis.com/oauth2/v3/userinfo" \ ### Frontend Code ```js -// DashboardPage.jsx import { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; function DashboardPage() { const navigate = useNavigate(); const [isLoading, setIsLoading] = useState(true); - const [error, setError] = useState(null); const [dashboardData, setDashboardData] = useState(null); useEffect(() => { - async function initializeDashboard() { + async function loadDashboard() { try { - + + // + // Single request that both verifies auth and gets data // - // First verify auth - // - const authResponse = await fetch('https://myapp/api/verify-auth', { - credentials: 'include', + const response = await fetch('https://myapp/api/dashboard-data', { + credentials: 'include' // Sends the auth cookie }); - if (!authResponse.ok) { - throw new Error('Authentication failed'); + if (!response.ok) { + // + // If auth is invalid, the backend will return 401 + // + if (response.status === 401) { + navigate('/login'); + return; + } + throw new Error('Failed to load dashboard'); } - // - // Auth is valid, now fetch dashboard data - // - const dataResponse = await fetch('https://myapp/api/dashboard-data', { - credentials: 'include', - }); - - if (!dataResponse.ok) { - throw new Error('Failed to load dashboard data'); - } - - const data = await dataResponse.json(); + const data = await response.json(); setDashboardData(data); setIsLoading(false); } catch (err) { - // - // Redirect to login on auth failure - // - setError(err.message); navigate('/login'); } } - initializeDashboard(); + loadDashboard(); }, [navigate]); if (isLoading) { - return ( -
Please wait while we verify your session.
-