File size: 1,493 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 |
// 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 }; |