File size: 3,124 Bytes
62c3fe0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// 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}`);
});