|
| 1 | +using Microsoft.AspNetCore.Http; |
| 2 | +using Microsoft.Extensions.Caching.Memory; |
| 3 | +using System.Security.Claims; |
| 4 | +using CentralizedLogging.Sdk.Abstractions; |
| 5 | + |
| 6 | +namespace CentralizedLogging.Sdk |
| 7 | +{ |
| 8 | + public sealed class MemoryCacheAccessTokenProvider : IAccessTokenProvider |
| 9 | + { |
| 10 | + private readonly IMemoryCache _cache; |
| 11 | + private readonly IHttpContextAccessor _http; |
| 12 | + |
| 13 | + public MemoryCacheAccessTokenProvider(IMemoryCache cache, IHttpContextAccessor http) |
| 14 | + { |
| 15 | + _cache = cache; |
| 16 | + _http = http; |
| 17 | + } |
| 18 | + |
| 19 | + public Task<string?> GetAccessTokenAsync(CancellationToken ct = default) |
| 20 | + { |
| 21 | + var user = _http.HttpContext?.User; |
| 22 | + var uid = |
| 23 | + user?.FindFirst("sub")?.Value |
| 24 | + ?? user?.FindFirst(ClaimTypes.NameIdentifier)?.Value; |
| 25 | + |
| 26 | + if (string.IsNullOrEmpty(uid)) return Task.FromResult<string?>(null); |
| 27 | + |
| 28 | + var key = $"token:{uid}"; |
| 29 | + _cache.TryGetValue(key, out string? token); |
| 30 | + return Task.FromResult(token); |
| 31 | + } |
| 32 | + |
| 33 | + // Optional helper method to set the token into cache |
| 34 | + public void SetAccessToken(string token, int userId, DateTime expiresAtUtc) |
| 35 | + { |
| 36 | + var ttl = ToTtl(expiresAtUtc); |
| 37 | + _cache.Set($"token:{userId}", token, ttl); |
| 38 | + } |
| 39 | + |
| 40 | + public Task RemoveAsync(string userId, CancellationToken ct = default) |
| 41 | + { |
| 42 | + _cache.Remove($"token:{userId}"); |
| 43 | + return Task.CompletedTask; |
| 44 | + } |
| 45 | + |
| 46 | + public static TimeSpan ToTtl(DateTime expiresAtUtc, TimeSpan? safety = null) |
| 47 | + { |
| 48 | + // ensure it's treated as UTC |
| 49 | + if (expiresAtUtc.Kind != DateTimeKind.Utc) |
| 50 | + expiresAtUtc = DateTime.SpecifyKind(expiresAtUtc, DateTimeKind.Utc); |
| 51 | + |
| 52 | + var ttl = expiresAtUtc - DateTime.UtcNow; |
| 53 | + |
| 54 | + // subtract a small safety margin to avoid edge expiries |
| 55 | + ttl -= safety ?? TimeSpan.FromSeconds(15); |
| 56 | + |
| 57 | + return ttl > TimeSpan.Zero ? ttl : TimeSpan.Zero; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments