-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.js
65 lines (60 loc) · 2.04 KB
/
graph.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var graph = require('@microsoft/microsoft-graph-client');
require('isomorphic-fetch');
module.exports = {
getUserDetails: async function(msalClient, userId) {
const client = getAuthenticatedClient(msalClient, userId);
const user = await client
.api('/me')
.select('displayName,mail,mailboxSettings,userPrincipalName')
.get();
return user;
},
// <GetInboxEmailsSnippet>
getInboxEmails: async function(msalClient, userId, top = 10) {
const client = getAuthenticatedClient(msalClient, userId);
return client
.api('/me/messages')
.select('subject,from,receivedDateTime,body')
.top(top)
.orderby('receivedDateTime desc')
.get();
}
// </GetInboxEmailsSnippet>
};
function getAuthenticatedClient(msalClient, userId) {
if (!msalClient || !userId) {
throw new Error(
`Invalid MSAL state. Client: ${msalClient ? 'present' : 'missing'}, User ID: ${userId ? 'present' : 'missing'}`);
}
// Initialize Graph client
const client = graph.Client.init({
// Implement an auth provider that gets a token
// from the app's MSAL instance
authProvider: async (done) => {
try {
// Get the user's account
const account = await msalClient
.getTokenCache()
.getAccountByHomeId(userId);
if (account) {
// Attempt to get the token silently
// This method uses the token cache and
// refreshes expired tokens as needed
const scopes = process.env.OAUTH_SCOPES || 'https://graph.microsoft.com/.default';
const response = await msalClient.acquireTokenSilent({
scopes: scopes.split(','),
redirectUri: process.env.OAUTH_REDIRECT_URI,
account: account
});
// First param to callback is the error,
// Set to null in success case
done(null, response.accessToken);
}
} catch (err) {
console.log(JSON.stringify(err, Object.getOwnPropertyNames(err)));
done(err, null);
}
}
});
return client;
}