| | | 1 | | using ArturRios.Util.WebApi.Security.Interfaces; |
| | | 2 | | using Microsoft.Extensions.Caching.Memory; |
| | | 3 | | |
| | | 4 | | namespace ArturRios.Util.WebApi.Security.Providers; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// An <see cref="IAuthenticationProvider"/> decorator that caches resolved users in an |
| | | 8 | | /// <see cref="IMemoryCache"/>, so repeated lookups of the same user within the configured |
| | | 9 | | /// time-to-live are served from memory instead of the underlying store. |
| | | 10 | | /// </summary> |
| | 8 | 11 | | public class CachedAuthenticationProvider( |
| | 8 | 12 | | IAuthenticationProvider inner, |
| | 8 | 13 | | IMemoryCache cache, |
| | 8 | 14 | | CachedAuthenticationProviderOptions? options = null) : IAuthenticationProvider |
| | | 15 | | { |
| | 8 | 16 | | private readonly CachedAuthenticationProviderOptions _options = options ?? new CachedAuthenticationProviderOptions() |
| | | 17 | | |
| | | 18 | | /// <inheritdoc /> |
| | | 19 | | public IAuthenticatedUser? GetAuthenticatedUserById(Guid id) => |
| | 19 | 20 | | GetOrLoad($"{_options.CacheKeyPrefix}{id}", () => inner.GetAuthenticatedUserById(id)); |
| | | 21 | | |
| | | 22 | | /// <inheritdoc /> |
| | | 23 | | public IAuthenticatedUser? GetAuthenticatedUserByEmail(string email) => |
| | 8 | 24 | | GetOrLoad($"{_options.EmailCacheKeyPrefix}{email}", () => inner.GetAuthenticatedUserByEmail(email)); |
| | | 25 | | |
| | | 26 | | private IAuthenticatedUser? GetOrLoad(string key, Func<IAuthenticatedUser?> load) |
| | | 27 | | { |
| | 16 | 28 | | if (cache.TryGetValue(key, out IAuthenticatedUser? cachedUser)) |
| | | 29 | | { |
| | 5 | 30 | | return cachedUser; |
| | | 31 | | } |
| | | 32 | | |
| | 11 | 33 | | var user = load(); |
| | | 34 | | |
| | 11 | 35 | | if (user is not null || _options.CacheMisses) |
| | | 36 | | { |
| | 9 | 37 | | cache.Set(key, user, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = _options.Ttl }); |
| | | 38 | | } |
| | | 39 | | |
| | 11 | 40 | | return user; |
| | | 41 | | } |
| | | 42 | | } |