using System; using xCommons.Extensions; using xCommons.Configurations; using xIdentityService.Constants; using xIdentityService.Interfaces; using System.Collections.Concurrent; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Caching.Memory; namespace xIdentityService.Providers { /// /// Thread-safe local cache; IMemoryCache gives TTL, /// ConcurrentDictionary gives key tracking for Clear() ... /// public class XAuthorizationCache : IXAuthorizationCache { private readonly TimeSpan ttl; private readonly IMemoryCache cache; private readonly ConcurrentDictionary keys = new(); private readonly XAppConfiguration appConfiguration; public XAuthorizationCache( IMemoryCache cache, XAppConfiguration appConfiguration ) { // this.cache = cache; this.appConfiguration = appConfiguration; ttl = TimeSpan.FromMinutes(appConfiguration.DefaultCacheTtlMinutes); } public bool TryGetPolicy( string name, out AuthorizationPolicy policy ) { // policy = null; // var result = !name.IsNullOrEmpty() && cache.TryGetValue(Key(name), out policy); return result; } public void SetPolicy( string name, AuthorizationPolicy policy ) { // if (name.IsNullOrEmpty() || policy.IsNull()) { return; } // cache.Set(Key(name), policy, ttl); keys[Key(name)] = 0; } public void RemovePolicy(string name) { // if (name.IsNullOrEmpty()) { return; } // cache.Remove(Key(name)); keys.TryRemove(Key(name), out _); } public void Clear() { // foreach (var key in keys.Keys) { cache.Remove(key); } // keys.Clear(); } // #region Private ... private static string Key(string name) => XIdentityServiceConstants.PolicyCacheKeyPrefix + name.ToNormalString(); #endregion } }