Update OAuth2-Backend-Approach.md

This commit is contained in:
Ste Vaidis 2025-01-08 10:12:28 +02:00
parent 12c65d6cbb
commit d393509b1c

View File

@ -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 {
//
// First verify auth
// Single request that both verifies auth and gets data
//
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 (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">
<h2>Loading Dashboard...</h2>
<p>Please wait while we verify your session.</p>
</div>
</div>
);
}
if (error) {
return null;
return <div>Loading...</div>;
}
return (
@ -321,3 +300,4 @@ function DashboardPage() {
);
}
```