From 24dcb6791c015e5068adfb415373fa7818464837 Mon Sep 17 00:00:00 2001 From: Ste Vaidis Date: Sun, 15 Dec 2024 15:15:42 +0200 Subject: [PATCH] Update OAuth2.md --- OAuth2.md | 83 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 75 insertions(+), 8 deletions(-) diff --git a/OAuth2.md b/OAuth2.md index e5907db..5c539f3 100644 --- a/OAuth2.md +++ b/OAuth2.md @@ -463,27 +463,94 @@ Authorization: Bearer ya29.a0AfH6SMC8Op6zXZkHi2XITkDoOVzYXt3hTY6sny54UlWlxrnKlX5

Backend GET Code

```js -app.get('/api/user-profile', async (req, res) => { - const accessToken = req.headers['authorization'].split(' ')[1]; // Extract token from Authorization header - +const express = require('express'); +const axios = require('axios'); + +const app = express(); +app.use(express.json()); // To parse JSON bodies + +const clientId = 'YOUR_GOOGLE_CLIENT_ID'; // Google Client ID +const clientSecret = 'YOUR_GOOGLE_CLIENT_SECRET'; // Google Client Secret +const redirectUri = 'https://xorismesiti.gr/api/auth/callback'; // Must match the one used in frontend + +// Function to validate the access token by making a request to the Google user info endpoint +const validateAccessToken = async (accessToken) => { try { const response = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', { headers: { Authorization: `Bearer ${accessToken}`, }, }); - - // Send the user profile data to the frontend - res.json(response.data); + + // If this succeeds, the token is valid + return response.data; // Return the user data } catch (error) { - console.error('Error fetching user profile:', error); - res.status(500).json({ error: 'Failed to fetch user profile' }); + // If the request fails (token is invalid or expired), throw an error + throw new Error('Invalid or expired access token'); } +}; + +// Example route for fetching the user profile +app.get('/api/user-profile', async (req, res) => { + const accessToken = req.headers['authorization']?.split(' ')[1]; // Extract token from Authorization header + + if (!accessToken) { + return res.status(400).json({ error: 'No access token provided' }); + } + + try { + // Validate the access token by fetching user info from Google + const userData = await validateAccessToken(accessToken); + + // Send the user profile data to the frontend + res.json(userData); + } catch (error) { + // Handle invalid or expired token + console.error('Error validating access token:', error); + res.status(401).json({ error: 'Invalid or expired access token' }); + } +}); + +// Start the server +app.listen(3000, () => { + console.log('Server running on http://localhost:3000'); }); ``` +
+

Front GET Code

+ +```js +// After receiving the token, store it in the frontend (e.g., localStorage or context) +localStorage.setItem('access_token', response.access_token); + +// Use it to make authenticated API requests to the backend +fetch('/api/user-profile', { + headers: { + 'Authorization': `Bearer ${localStorage.getItem('access_token')}`, + }, +}) + .then(response => { + if (response.status === 401) { + // Handle token expiration or invalid token + console.error('Access token expired or invalid. Please log in again.'); + // Optionally, redirect to login page or refresh token + } else { + return response.json(); + } + }) + .then(data => { + // Handle user data + console.log(data); + }) + .catch(error => { + console.error('Error fetching user profile:', error); + }); +``` +
+