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; +``` + +