// index.js const express = require('express'); const { google } = require('googleapis'); const fs = require('fs'); require('dotenv').config(); // For loading environment variables const app = express(); const port = 7860; // Set up OAuth2 client const oAuth2Client = new google.auth.OAuth2( process.env.CLIENT_ID, process.env.CLIENT_SECRET, process.env.REDIRECT_URI ); let userTokens = null; // Store user tokens temporarily in memory // Step 1: Generate the OAuth URL and redirect app.get('/auth', (req, res) => { const authUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', // Request offline access for refresh token scope: ['https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/calendar'], // Gmail send scope }); res.redirect(authUrl); // Redirect to Google's OAuth consent page console.log("Redirecting for OAuth consent..."); }); // Step 2: Handle OAuth callback, exchange code for tokens app.get('/oauth2callback', async (req, res) => { const code = req.query.code; try { const { tokens } = await oAuth2Client.getToken(code); // console.log('Received tokens:', tokens); // Log tokens for debugging // Store tokens securely (in memory, DB, or .env file) oAuth2Client.setCredentials(tokens); userTokens = tokens; // Store tokens in memory // Save the tokens to .env file (for future use) saveTokensToEnv(tokens); res.send('Authorization successful! You can now send emails.'); } catch (error) { console.error('Error during OAuth callback:', error); res.status(500).send('Failed to authenticate with Google'); } }); // Helper function to save tokens to .env file function saveTokensToEnv(tokens) { if (tokens.refresh_token){ const envVariables = ` ACCESS_TOKEN=${tokens.access_token} REFRESH_TOKEN=${tokens.refresh_token || 'No refresh token available'} `; // Save tokens in the .env file fs.appendFileSync('.env', envVariables, 'utf8'); console.log('Tokens saved to .env file.'); }else{ const envVariables = ` ACCESS_TOKEN=${tokens.access_token} `; // Save tokens in the .env file fs.appendFileSync('.env', envVariables, 'utf8'); console.log('Tokens saved to .env file.'); } } // Method to check if the access token is expired async function checkAndRefreshAccessToken() { if (oAuth2Client.isTokenExpiring()) { try { // If the access token is expired or about to expire, refresh it const response = await oAuth2Client.refreshAccessToken(); const newTokens = response.credentials; oAuth2Client.setCredentials(newTokens); // Set the new credentials userTokens = newTokens; // Update the tokens console.log('Access token refreshed.'); } catch (error) { console.error('Error refreshing access token:', error); } } } // Start the Express server app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });