|
|
|
const express = require('express'); |
|
const { google } = require('googleapis'); |
|
const fs = require('fs'); |
|
require('dotenv').config(); |
|
|
|
const app = express(); |
|
const port = 7860; |
|
|
|
|
|
const oAuth2Client = new google.auth.OAuth2( |
|
process.env.CLIENT_ID, |
|
process.env.CLIENT_SECRET, |
|
process.env.REDIRECT_URI |
|
); |
|
|
|
let userTokens = null; |
|
|
|
|
|
app.get('/auth', (req, res) => { |
|
const authUrl = oAuth2Client.generateAuthUrl({ |
|
access_type: 'offline', |
|
scope: ['https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/calendar'], |
|
}); |
|
res.redirect(authUrl); |
|
console.log("Redirecting for OAuth consent..."); |
|
}); |
|
|
|
|
|
app.get('/oauth2callback', async (req, res) => { |
|
const code = req.query.code; |
|
|
|
try { |
|
const { tokens } = await oAuth2Client.getToken(code); |
|
|
|
|
|
|
|
oAuth2Client.setCredentials(tokens); |
|
userTokens = tokens; |
|
|
|
|
|
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'); |
|
} |
|
}); |
|
|
|
|
|
function saveTokensToEnv(tokens) { |
|
if (tokens.refresh_token){ |
|
const envVariables = ` |
|
ACCESS_TOKEN=${tokens.access_token} |
|
REFRESH_TOKEN=${tokens.refresh_token || 'No refresh token available'} |
|
`; |
|
|
|
|
|
fs.appendFileSync('.env', envVariables, 'utf8'); |
|
console.log('Tokens saved to .env file.'); |
|
}else{ |
|
const envVariables = ` |
|
ACCESS_TOKEN=${tokens.access_token} |
|
`; |
|
|
|
|
|
fs.appendFileSync('.env', envVariables, 'utf8'); |
|
console.log('Tokens saved to .env file.'); |
|
} |
|
|
|
} |
|
|
|
|
|
async function checkAndRefreshAccessToken() { |
|
if (oAuth2Client.isTokenExpiring()) { |
|
try { |
|
|
|
const response = await oAuth2Client.refreshAccessToken(); |
|
const newTokens = response.credentials; |
|
oAuth2Client.setCredentials(newTokens); |
|
userTokens = newTokens; |
|
|
|
console.log('Access token refreshed.'); |
|
} catch (error) { |
|
console.error('Error refreshing access token:', error); |
|
} |
|
} |
|
} |
|
|
|
|
|
app.listen(port, () => { |
|
console.log(`Server running at http://localhost:${port}`); |
|
}); |
|
|