This code provides a function to authenticate with the Google Calendar API, handling both existing tokens and OAuth 2.0 authorization for new tokens.
npm run import -- "use Google calendar API"
var {google} = require('googleapis');
var importer = require('../Core');
var authorize = importer.import("google oauth token client");
// Authorize a client with the loaded credentials, then call the
// Google Calendar API.
var oauth2Client;
function authorizeCalendar(options = {}) {
if(options.auth) {
return Promise.resolve(google.calendar({version: 'v3', auth: options.auth}))
}
return authorize(options.scopes || [
'https://www.googleapis.com/auth/calendar'])
.then(c => {
options.auth = c;
return google.calendar({version: 'v3', auth: c});
})
}
module.exports = authorizeCalendar;
const { google } = require('googleapis');
const { AuthorizeClient } = require('../Core');
const authorizeClient = new AuthorizeClient();
/**
* Authorize a client with the loaded credentials, then call the Google Calendar API.
*
* @param {Object} options - Options for authorizing the client.
* @param {Array} [options.scopes] - Scopes to authorize for.
* @param {Object} [options.auth] - Existing authorization object.
* @returns {Promise} Authorized Google Calendar client.
*/
async function authorizeCalendar(options = {}) {
if (options.auth) {
// Use existing authorization object if provided
return google.calendar({ version: 'v3', auth: options.auth });
}
// Load scopes dynamically if not provided
const scopes = options.scopes || [
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
];
// Authorize client and get the access token
const authClient = await authorizeClient.getAccessToken(scopes);
// Use the authorized client to create a Google Calendar instance
return google.calendar({ version: 'v3', auth: authClient });
}
module.exports = authorizeCalendar;
This code sets up authentication with the Google Calendar API.
Here's a breakdown:
Dependencies:
googleapis
library for interacting with Google APIs.authorize
function from a local module (../Core
) to handle OAuth 2.0 authentication with Google.authorizeCalendar
Function:
options
object that can include:
auth
: An existing OAuth 2.0 access token.scopes
: An array of required Google API scopes (permissions).auth
object is provided, it directly returns a Google Calendar API client initialized with the provided credentials.authorize
function to obtain an access token using the specified scopes.Export:
authorizeCalendar
function is exported as a module, making it available for use in other parts of the application.Purpose:
This code provides a reusable function to authenticate with the Google Calendar API, either using an existing access token or by obtaining a new one through OAuth 2.0 authorization.