< Summary

Information
Class: ArturRios.Util.WebApi.Security.Providers.CachedAuthenticationProvider
Assembly: ArturRios.Util.WebApi
File(s): /home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/Security/Providers/CachedAuthenticationProvider.cs
Line coverage
100%
Covered lines: 13
Uncovered lines: 0
Coverable lines: 13
Total lines: 42
Line coverage: 100%
Branch coverage
100%
Covered branches: 8
Total branches: 8
Branch coverage: 100%
Method coverage
100%
Covered methods: 4
Fully covered methods: 4
Total methods: 4
Method coverage: 100%
Full method coverage: 100%

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%22100%
GetAuthenticatedUserById(...)100%11100%
GetAuthenticatedUserByEmail(...)100%11100%
GetOrLoad(...)100%66100%

File(s)

/home/runner/work/dotnet-webapi-util/dotnet-webapi-util/src/Security/Providers/CachedAuthenticationProvider.cs

#LineLine coverage
 1using ArturRios.Util.WebApi.Security.Interfaces;
 2using Microsoft.Extensions.Caching.Memory;
 3
 4namespace 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>
 811public class CachedAuthenticationProvider(
 812    IAuthenticationProvider inner,
 813    IMemoryCache cache,
 814    CachedAuthenticationProviderOptions? options = null) : IAuthenticationProvider
 15{
 816    private readonly CachedAuthenticationProviderOptions _options = options ?? new CachedAuthenticationProviderOptions()
 17
 18    /// <inheritdoc />
 19    public IAuthenticatedUser? GetAuthenticatedUserById(Guid id) =>
 1920        GetOrLoad($"{_options.CacheKeyPrefix}{id}", () => inner.GetAuthenticatedUserById(id));
 21
 22    /// <inheritdoc />
 23    public IAuthenticatedUser? GetAuthenticatedUserByEmail(string email) =>
 824        GetOrLoad($"{_options.EmailCacheKeyPrefix}{email}", () => inner.GetAuthenticatedUserByEmail(email));
 25
 26    private IAuthenticatedUser? GetOrLoad(string key, Func<IAuthenticatedUser?> load)
 27    {
 1628        if (cache.TryGetValue(key, out IAuthenticatedUser? cachedUser))
 29        {
 530            return cachedUser;
 31        }
 32
 1133        var user = load();
 34
 1135        if (user is not null || _options.CacheMisses)
 36        {
 937            cache.Set(key, user, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = _options.Ttl });
 38        }
 39
 1140        return user;
 41    }
 42}