require('isomorphic-fetch'); // const { PublicClientApplication } = require('@azure/msal-node'); // const { TokenCredentialAuthenticationProvider } = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials'); const graph = require('@microsoft/microsoft-graph-client'); const azure = require('@azure/identity'); const authProviders = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials'); let _settings = undefined; let _clientSecretCredential = undefined; let _appClient = undefined; function initializeGraphForAppOnlyAuth(settings) { // Ensure settings isn't null if (!settings) { throw new Error('Settings cannot be undefined'); } _settings = settings; // Ensure settings isn't null if (!_settings) { throw new Error('Settings cannot be undefined'); } if (!_clientSecretCredential) { _clientSecretCredential = new azure.ClientSecretCredential( _settings.tenantId, _settings.clientId, _settings.clientSecret ); } if (!_appClient) { const authProvider = new authProviders.TokenCredentialAuthenticationProvider( _clientSecretCredential, { scopes: ['https://graph.microsoft.com/.default'] }); _appClient = graph.Client.initWithMiddleware({ authProvider: authProvider }); } } module.exports.initializeGraphForAppOnlyAuth = initializeGraphForAppOnlyAuth; let _userClient = undefined; function initializeGraphForUserAuth(settings, deviceCodeCallback) { if (!settings) { throw new Error('Settings cannot be undefined'); } const msalConfig = { auth: { clientId: settings.clientId, authority: `https://login.microsoftonline.com/${settings.tenantId}` } }; const pca = new PublicClientApplication(msalConfig); const deviceCodeRequest = { scopes: settings.graphUserScopes, deviceCodeCallback: (response) => { // console.log(response.message); deviceCodeCallback(response); }, // Your callback function to handle the message scopes: settings.graphUserScopes }; pca.acquireTokenByDeviceCode(deviceCodeRequest).then((response) => { const authProvider = new TokenCredentialAuthenticationProvider(pca, { scopes: settings.graphUserScopes, getToken: async () => response.accessToken }); _userClient = graph.Client.initWithMiddleware({ authProvider }); }).catch((error) => { console.error("Error acquiring token by device code", error); }); } module.exports.initializeGraphForUserAuth = initializeGraphForUserAuth; async function getCalendarView(resourceUPN, startDateTime, endDateTime) { if (!_appClient) { throw new Error('Graph has not been initialized for user auth'); } try { const apiUrl = `/users/${resourceUPN}/calendarView?startDateTime=${startDateTime}&endDateTime=${endDateTime}`; const calendarView = await _appClient?.api(apiUrl) .get(); if (calendarView && calendarView.value) { return calendarView.value; } else { return []; } } catch (error) { console.error('Error in getCalendarView:', error); } } module.exports.getCalendarView = getCalendarView;