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