i-darrshan's picture
initial update of the vite site
62c3fe0
// utils/refreshToken.js
const { oAuth2Client } = require('../config/googleOAuth'); // Import the OAuth client
// Store the user's tokens
let userTokens = {};
// Method to check if the access token is expired and refresh it
async function checkAndRefreshAccessToken() {
userTokens = {}; // Reset tokens at start
if (process.env.ACCESS_TOKEN && process.env.REFRESH_TOKEN) {
userTokens = {
access_token: process.env.ACCESS_TOKEN,
refresh_token: process.env.REFRESH_TOKEN,
};
oAuth2Client.setCredentials(userTokens);
console.log('Using tokens from .env file');
} else {
console.log('No tokens found in .env file. Please authenticate.');
}
// console.log(oAuth2Client)
if (oAuth2Client.isTokenExpiring()) {
try {
// Refresh the token if it's expired or about to expire
const response = await oAuth2Client.refreshAccessToken();
const newTokens = response.credentials;
oAuth2Client.setCredentials(newTokens); // Set new credentials
userTokens = newTokens; // Update tokens
process.env.ACCESS_TOKEN = newTokens.access_token
process.env.REFRESH_TOKEN = newTokens.refresh_token
console.log('Access token refreshed.');
} catch (error) {
console.error('Error refreshing access token:', error);
}
}
return userTokens
}
module.exports = { checkAndRefreshAccessToken };