i-darrshan's picture
initial update of the vite site
62c3fe0
const fs = require('fs');
const { google } = require('googleapis');
require('dotenv').config();
// import the OAuth2 client
const { oAuth2Client } = require('../config/googleOAuth');
// Controller function for /auth route
const redirectToGoogleOAuth = (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'], // Scopes
});
res.redirect(authUrl); // Redirect to Google's OAuth consent page
console.log('Redirecting for OAuth consent...');
};
// Controller function to handle OAuth callback
const handleOAuthCallback = async (req, res) => {
const code = req.query.code;
try {
const { tokens } = await oAuth2Client.getToken(code); // Exchange code for tokens
console.log('Received tokens:', tokens); // Log tokens for debugging
// Set tokens to the OAuth2 client
oAuth2Client.setCredentials(tokens);
// Save tokens to the .env file
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
const saveTokensToEnv = (tokens) => {
const envVariables = `
ACCESS_TOKEN=${tokens.access_token}
REFRESH_TOKEN=${tokens.refresh_token || 'No refresh token available'}
`;
// Append tokens to the .env file
fs.appendFileSync('.env', envVariables, 'utf8');
console.log('Tokens saved to .env file.');
};
module.exports = { redirectToGoogleOAuth, handleOAuthCallback };