2022-01-10 16:58:16 +01:00
|
|
|
|
using Microsoft.AspNetCore.DataProtection;
|
2022-09-26 21:22:02 +02:00
|
|
|
|
using Microsoft.Extensions.Logging;
|
2022-01-10 16:58:16 +01:00
|
|
|
|
|
2022-08-29 22:06:55 +02:00
|
|
|
|
namespace Bit.Core.Tokens;
|
|
|
|
|
|
|
|
|
|
public class Token
|
2022-01-10 16:58:16 +01:00
|
|
|
|
{
|
2022-08-29 22:06:55 +02:00
|
|
|
|
private readonly string _token;
|
|
|
|
|
|
|
|
|
|
public Token(string token)
|
2022-01-10 16:58:16 +01:00
|
|
|
|
{
|
2022-08-29 22:06:55 +02:00
|
|
|
|
_token = token;
|
|
|
|
|
}
|
2022-01-10 16:58:16 +01:00
|
|
|
|
|
2022-08-29 22:06:55 +02:00
|
|
|
|
public Token WithPrefix(string prefix)
|
|
|
|
|
{
|
|
|
|
|
return new Token($"{prefix}{_token}");
|
|
|
|
|
}
|
2022-01-10 16:58:16 +01:00
|
|
|
|
|
2022-08-29 22:06:55 +02:00
|
|
|
|
public Token RemovePrefix(string expectedPrefix)
|
|
|
|
|
{
|
|
|
|
|
if (!_token.StartsWith(expectedPrefix))
|
2022-01-10 16:58:16 +01:00
|
|
|
|
{
|
2022-08-29 22:06:55 +02:00
|
|
|
|
throw new BadTokenException($"Expected prefix, {expectedPrefix}, was not present.");
|
2022-01-10 16:58:16 +01:00
|
|
|
|
}
|
|
|
|
|
|
2022-08-29 22:06:55 +02:00
|
|
|
|
return new Token(_token[expectedPrefix.Length..]);
|
|
|
|
|
}
|
2022-08-29 21:53:48 +02:00
|
|
|
|
|
2022-01-10 16:58:16 +01:00
|
|
|
|
|
2022-09-26 21:22:02 +02:00
|
|
|
|
public Token ProtectWith(IDataProtector dataProtector, ILogger logger)
|
|
|
|
|
{
|
|
|
|
|
logger.LogDebug("Protecting token: {token}", this);
|
|
|
|
|
return new(dataProtector.Protect(ToString()));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Token UnprotectWith(IDataProtector dataProtector, ILogger logger)
|
|
|
|
|
{
|
|
|
|
|
var unprotected = "";
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
unprotected = dataProtector.Unprotect(ToString());
|
|
|
|
|
}
|
|
|
|
|
catch (Exception e)
|
|
|
|
|
{
|
|
|
|
|
logger.LogInformation(e, "Failed to unprotect token: {token}", this);
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
logger.LogDebug("Unprotected token: {token} to {decryptedToken}", this, unprotected);
|
|
|
|
|
return new(unprotected);
|
|
|
|
|
}
|
2022-01-10 16:58:16 +01:00
|
|
|
|
|
2022-08-29 22:06:55 +02:00
|
|
|
|
public override string ToString() => _token;
|
2022-01-10 16:58:16 +01:00
|
|
|
|
}
|