-
Notifications
You must be signed in to change notification settings - Fork 2
/
GraphHelper.cs
50 lines (41 loc) · 1.52 KB
/
GraphHelper.cs
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
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
public class GraphHelper
{
// Settings object
private static Settings? _settings;
// User auth token credential
private static DeviceCodeCredential? _deviceCodeCredential;
// Client configured with user authentication
private static GraphServiceClient? _userClient;
public static void InitializeGraphForUserAuth(Settings settings,
Func<DeviceCodeInfo, CancellationToken, Task> deviceCodePrompt)
{
_settings = settings;
_deviceCodeCredential = new DeviceCodeCredential(deviceCodePrompt,
settings.TenantId, settings.ClientId);
_userClient = new GraphServiceClient(_deviceCodeCredential, settings.GraphUserScopes);
}
public static async Task<string> GetUserTokenAsync()
{
// Ensure credential isn't null
_ = _deviceCodeCredential ??
throw new System.NullReferenceException("Graph has not been initialized for user auth");
// Ensure scopes isn't null
_ = _settings?.GraphUserScopes ?? throw new System.ArgumentNullException("Argument 'scopes' cannot be null");
// Request token with given scopes
var context = new TokenRequestContext(_settings.GraphUserScopes);
var response = await _deviceCodeCredential.GetTokenAsync(context);
return response.Token;
}
public static Task<Presence> GetUsersPresenceAsync(string userId)
{
// Ensure client isn't null
_ = _userClient ??
throw new System.NullReferenceException("Graph has not been initialized for user auth");
return _userClient.Users[userId].Presence
.Request()
.GetAsync();
}
}