-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTokenService.cs
65 lines (53 loc) · 1.97 KB
/
TokenService.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Utils
{
/// <summary>
/// Represents result of token finding with success indicator
/// </summary>
public struct TokenResult
{
private TokenResult(string token, bool success)
{
Token = token;
IsSuccessful = success;
}
public readonly string Token;
public readonly bool IsSuccessful;
internal static TokenResult Success(string token) => new(token, true);
internal static TokenResult Fail() => new(null!, false);
}
public static class TokenFinding
{
/// <summary>
/// Find your token in specified paths
/// <para/> Log process to specified logger
/// </summary>
/// <param name="configuration">Configuration where token will be finding</param>
/// <param name="logger">Logger to log</param>
/// <param name="keys">Possible paths to token</param>
/// <returns>Found token with success indicator</returns>
public static TokenResult Find(this IConfiguration configuration, ILogger? logger, params string[] keys)
{
string? token = null;
foreach (var key in keys)
if (TryGetToken(key))
break;
if (token != null) return TokenResult.Success(token);
logger?.LogWarning("Can't get token from keys");
return TokenResult.Fail();
bool TryGetToken(string key)
{
token = configuration[key];
if (token == null) return false;
logger?.LogDebug("Get token from {Key}", key);
return true;
}
}
public static string GetTokenOrThrow(this TokenResult result)
{
if (result.IsSuccessful) return result.Token;
throw new InvalidOperationException("Token wasn't get successful");
}
}
}