diff --git a/OAuth2-Backend-Approach.md b/OAuth2-Backend-Approach.md index 3e08c36..e47fa13 100644 --- a/OAuth2-Backend-Approach.md +++ b/OAuth2-Backend-Approach.md @@ -178,10 +178,11 @@ app.get('/callback', async (req, res) => { sameSite: 'strict', // CSRF protection maxAge: 24 * 60 * 60 * 1000, // 24 hours }); - res.redirect('https://myapp/authentication-success'); + res.redirect('https://myapp/dashboard'); + } catch (error) { - res.redirect('https://myapp/authentication-error'); + res.redirect('https://myapp/login'); } }); ``` @@ -248,54 +249,76 @@ curl -X GET "https://www.googleapis.com/oauth2/v3/userinfo" \ ### Frontend Code ```js -import React, { useState, useEffect } from 'react'; -import axios from 'axios'; +// DashboardPage.jsx +import { useEffect, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; -const App = () => { - const [user, setUser] = useState(null); - const [isAuthenticated, setIsAuthenticated] = useState(false); - - // Fetch user data from the backend's /profile endpoint - const fetchUserData = async () => { - try { - const response = await axios.get('http://localhost:3000/profile', { - withCredentials: true, // Important: Ensure cookies are sent with the request - }); - setUser(response.data); // Set the user data from the response - setIsAuthenticated(true); - } catch (error) { - console.error('Error fetching user profile:', error); - } - }; +function DashboardPage() { + const navigate = useNavigate(); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const [dashboardData, setDashboardData] = useState(null); useEffect(() => { - // Check if the user is authenticated by checking the cookie - if (document.cookie.includes('access_token')) { - fetchUserData(); // Fetch user profile if the access token is available in cookies + async function initializeDashboard() { + try { + + // + // First verify auth + // + const authResponse = await fetch('https://myapp/api/verify-auth', { + credentials: 'include', + }); + + if (!authResponse.ok) { + throw new Error('Authentication failed'); + } + + // + // 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(); + setDashboardData(data); + setIsLoading(false); + } catch (err) { + // + // Redirect to login on auth failure + // + setError(err.message); + navigate('/login'); + } } - }, []); + + initializeDashboard(); + }, [navigate]); + + if (isLoading) { + return ( +
Please wait while we verify your session.
+Please log in with Google to access your profile:
- -Email: {user?.email}
-