47 lines
1.4 KiB
JavaScript
47 lines
1.4 KiB
JavaScript
const { PublicClientApplication } = require('@azure/msal-node');
|
|
const { msalConfig, graphScopes } = require('./authConfig');
|
|
const fetch = (...args) =>
|
|
import('node-fetch').then(({default: fetch}) => fetch(...args));
|
|
|
|
class GraphHelper {
|
|
constructor() {
|
|
this.pca = new PublicClientApplication(msalConfig);
|
|
}
|
|
|
|
async getAccessToken() {
|
|
const accounts = await this.pca.getTokenCache().getAllAccounts();
|
|
if (accounts.length > 0) {
|
|
try {
|
|
return await this.pca.acquireTokenSilent({
|
|
account: accounts[0],
|
|
scopes: graphScopes
|
|
});
|
|
} catch (error) {
|
|
return this.login();
|
|
}
|
|
}
|
|
return this.login();
|
|
}
|
|
|
|
async login() {
|
|
return this.pca.acquireTokenInteractive({
|
|
scopes: graphScopes,
|
|
openBrowser: async (url) => {
|
|
const { shell } = require('electron');
|
|
await shell.openExternal(url);
|
|
}
|
|
});
|
|
}
|
|
|
|
async listFolderContents(folderPath) {
|
|
const token = await this.getAccessToken();
|
|
const response = await fetch(`https://graph.microsoft.com/v1.0/me/drive/root:${folderPath}:/children`, {
|
|
headers: {
|
|
Authorization: `Bearer ${token.accessToken}`
|
|
}
|
|
});
|
|
return response.json();
|
|
}
|
|
}
|
|
|
|
module.exports = new GraphHelper();
|