|
1 | 1 | const express = require("express"); |
| 2 | +const axios = require('axios'); |
| 3 | +const cors = require('cors'); |
| 4 | + |
| 5 | +const { OAuth2Client } = require('google-auth-library'); |
| 6 | +const oauth2Client = new OAuth2Client() |
2 | 7 |
|
3 | 8 | // Create an Express app and listen for incoming requests on port 3000 |
4 | 9 | const app = express(); |
5 | 10 | const router = express.Router(); |
6 | 11 | const port = process.env.PORT || 3000; |
7 | 12 |
|
| 13 | +// static files |
8 | 14 | app.use(express.static('files')) |
9 | 15 |
|
| 16 | +// Enable CORS for all routes |
| 17 | +app.use(cors()); |
| 18 | + |
| 19 | +// 1. Call the Google SDK from the frontend using whatever frontend |
| 20 | +//2. Extract the code or access token and send to your backend for verification. |
| 21 | +//3. Use your backend Google api to verify the code or token. |
| 22 | +//4. If verified, sign them in the backend and then send a response to frontend |
| 23 | + |
| 24 | +app.post('/auth', async (req, res) => { |
| 25 | + try { |
| 26 | + // get the code from frontend |
| 27 | + const code = req.headers.authorization; |
| 28 | + console.log('Authorization Code:', code); |
| 29 | + |
| 30 | + // Exchange the authorization code for an access token |
| 31 | + const response = await axios.post( |
| 32 | + 'https://oauth2.googleapis.com/token', |
| 33 | + { |
| 34 | + code, |
| 35 | + client_id: '587301-d27f8hofgi6i0.apps.googleusercontent.com', |
| 36 | + client_secret: 'GOCSPX-u02eNWutQVi', |
| 37 | + redirect_uri: 'postmessage', |
| 38 | + grant_type: 'authorization_code' |
| 39 | + } |
| 40 | + ); |
| 41 | + const accessToken = response.data.access_token; |
| 42 | + console.log('Access Token:', accessToken); |
| 43 | + |
| 44 | + // Fetch user details using the access token |
| 45 | + const userResponse = await axios.get( |
| 46 | + 'https://www.googleapis.com/oauth2/v3/userinfo', |
| 47 | + { |
| 48 | + headers: { |
| 49 | + Authorization: `Bearer ${accessToken}` |
| 50 | + } |
| 51 | + } |
| 52 | + ); |
| 53 | + const userDetails = userResponse.data; |
| 54 | + console.log('User Details:', userDetails); |
| 55 | + |
| 56 | + // Process user details and perform necessary actions |
| 57 | + |
| 58 | + res.status(200).json({ message: 'Authentication successful' }); |
| 59 | + } catch (error) { |
| 60 | + console.error('Error saving code:', error); |
| 61 | + res.status(500).json({ message: 'Failed to save code' }); |
| 62 | + } |
| 63 | +}); |
| 64 | + |
10 | 65 | // Use middleware to parse incoming requests with JSON and URL-encoded payloads |
11 | 66 | app.use(express.json()); |
12 | 67 | app.use(express.urlencoded()); |
|
0 commit comments