From cddb8b51603d7bb6e381de24f6449f98c2d988b1 Mon Sep 17 00:00:00 2001 From: Ste Vaidis Date: Tue, 7 Jan 2025 13:30:09 +0200 Subject: [PATCH] Update OAuth2-Backend-Approach.md --- OAuth2-Backend-Approach.md | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/OAuth2-Backend-Approach.md b/OAuth2-Backend-Approach.md index e6e95c8..e8cda69 100644 --- a/OAuth2-Backend-Approach.md +++ b/OAuth2-Backend-Approach.md @@ -130,6 +130,60 @@ app.get('/auth/google/callback', async (req, res) => { +```js +import React, { useState, useEffect } from 'react'; +import axios from 'axios'; + +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); + } + }; + + 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 + } + }, []); + + return ( +
+

Google OAuth2 with React

+ + {!isAuthenticated ? ( +
+

Please log in with Google to access your profile:

+ +
+ ) : ( +
+

Welcome, {user?.name}

+

Email: {user?.email}

+ Profile +
+ )} +
+ ); +}; + +export default App; +``` + +