-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectionManager.txt
81 lines (74 loc) · 3.72 KB
/
ConnectionManager.txt
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Json;
using Microsoft.Extensions.Options;
namespace {TargetNamespace} {
public class ConnectionManager {
private readonly HttpClient _httpClient;
private readonly GenesysCloudCredentials _credentials;
private AuthTokenInfo? _tokenInfo;
private DateTime _tokenExpiresAt = DateTime.MinValue;
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionManager"/> class through dependency injection.
/// </summary>
/// <param name="genesysCloudCredentials">An instance of <see cref="IOptions<GenesysCloudCredentials>"/> which holds the credentials for the access.</param>
public ConnectionManager(IOptions<GenesysCloudCredentials> genesysCloudCredentials) {
_credentials = genesysCloudCredentials.Value;
_httpClient = new HttpClient {
BaseAddress = new Uri($"https://api.{_credentials.Environment}")
};
}
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionManager"/> class.
/// </summary>
/// <param name="genesysCloudCredentials">An instance of <see cref="GenesysCloudCredentials"/> which holds the credentials for the access.</param>
public ConnectionManager(GenesysCloudCredentials genesysCloudCredentials) {
_credentials = genesysCloudCredentials;
_httpClient = new HttpClient {
BaseAddress = new Uri($"https://api.{_credentials.Environment}")
};
}
internal async Task<HttpClient> GetClient() {
await CheckToken();
return _httpClient;
}
private async Task CheckToken() {
if (_tokenInfo == null || _tokenInfo.AccessToken == null || _tokenExpiresAt < DateTime.Now) {
await GetToken();
}
if (_tokenInfo == null || _tokenInfo.AccessToken == null) {
throw new Exception("Token invalid");
}
if ((_tokenExpiresAt - DateTime.Now).TotalMinutes < 5 && _tokenInfo.RefreshToken != null) {
await GetToken(_tokenInfo.RefreshToken);
}
}
private async Task GetToken(string? refreshToken = null) {
var basicAuthauth = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{_credentials.ClientId}:{_credentials.ClientSecret}"));
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicAuthauth);
var form = new List<KeyValuePair<string, string>>();
if (string.IsNullOrEmpty(refreshToken)) {
form.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
}
else {
form.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));
form.Add(new KeyValuePair<string, string>("refresh_token", refreshToken));
}
var response = await _httpClient.PostAsync($"https://login.{_credentials.Environment}/oauth/token", new FormUrlEncodedContent(form));
response.EnsureSuccessStatusCode();
_tokenInfo = await response.Content.ReadFromJsonAsync<AuthTokenInfo>();
if (_tokenInfo != null) {
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _tokenInfo.AccessToken);
if (_tokenInfo.ExpiresIn.HasValue) {
_tokenExpiresAt = DateTime.Now.AddSeconds((int)_tokenInfo.ExpiresIn);
}
}
}
}
}