< Summary

Information
Class: Elsa.SasTokens.Contracts.DataProtectorTokenService
Assembly: Elsa.SasTokens
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.SasTokens/Contracts/DataProtectorTokenService.cs
Line coverage
16%
Covered lines: 3
Uncovered lines: 15
Coverable lines: 18
Total lines: 66
Line coverage: 16.6%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
CreateToken(...)100%210%
CreateToken(...)100%210%
CreateToken(...)100%210%
TryDecryptToken(...)100%210%
DecryptToken(...)100%210%

File(s)

/home/runner/work/elsa-core/elsa-core/src/modules/Elsa.SasTokens/Contracts/DataProtectorTokenService.cs

#LineLine coverage
 1using System.Text.Json;
 2using Microsoft.AspNetCore.DataProtection;
 3
 4namespace Elsa.SasTokens.Contracts;
 5
 6/// <summary>
 7/// A service that can create and decrypt SAS (Shared Access Signature) tokens using the <see cref="Microsoft.AspNetCore
 8/// </summary>
 9public class DataProtectorTokenService : ITokenService
 10{
 11    private readonly IDataProtector _dataProtector;
 12
 13    /// <summary>
 14    /// Initializes a new instance of the <see cref="DataProtectorTokenService"/> class.
 15    /// </summary>
 116    public DataProtectorTokenService(IDataProtectionProvider dataProtector)
 17    {
 118        _dataProtector = dataProtector.CreateProtector("Elsa Tokens");
 119    }
 20
 21    /// <inheritdoc />
 22    public string CreateToken<T>(T payload, TimeSpan lifetime)
 23    {
 024        var json = JsonSerializer.Serialize(payload);
 025        return _dataProtector.ToTimeLimitedDataProtector().Protect(json, lifetime);
 26    }
 27
 28    /// <inheritdoc />
 29    public string CreateToken<T>(T payload, DateTimeOffset expiresAt)
 30    {
 031        var json = JsonSerializer.Serialize(payload);
 032        return _dataProtector.ToTimeLimitedDataProtector().Protect(json, expiresAt);
 33    }
 34
 35    /// <inheritdoc />
 36    public string CreateToken<T>(T payload)
 37    {
 038        var json = JsonSerializer.Serialize(payload);
 039        return _dataProtector.Protect(json);
 40    }
 41
 42    /// <inheritdoc />
 43    public bool TryDecryptToken<T>(string token, out T payload)
 44    {
 045        payload = default!;
 46
 47        try
 48        {
 049            payload = DecryptToken<T>(token);
 050            return true;
 51        }
 052        catch
 53        {
 54            // ignored.
 055        }
 56
 057        return false;
 058    }
 59
 60    /// <inheritdoc />
 61    public T DecryptToken<T>(string token)
 62    {
 063        var json = _dataProtector.Unprotect(token);
 064        return JsonSerializer.Deserialize<T>(json)!;
 65    }
 66}