wabbajack/Wabbajack.Services.OSIntegrated/EncryptedJsonTokenProvider.cs

70 lines
1.8 KiB
C#
Raw Normal View History

2021-09-27 12:42:46 +00:00
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Wabbajack.DTOs.JsonConverters;
using Wabbajack.Networking.Http.Interfaces;
using Wabbajack.Paths;
using Wabbajack.Paths.IO;
2021-10-23 16:51:17 +00:00
namespace Wabbajack.Services.OSIntegrated;
public class EncryptedJsonTokenProvider<T> : ITokenProvider<T>
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
private readonly DTOSerializer _dtos;
private readonly string _key;
private readonly ILogger _logger;
public EncryptedJsonTokenProvider(ILogger logger, DTOSerializer dtos, string key)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
_logger = logger;
_key = key;
_dtos = dtos;
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
private string? EnvValue => Environment.GetEnvironmentVariable(_key.ToUpperInvariant().Replace("-", "_"));
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
private AbsolutePath KeyPath => KnownFolders.WabbajackAppLocal.Combine("encrypted", _key);
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async ValueTask SetToken(T token)
{
_logger.LogInformation("Setting token {token}", _key);
await token.AsEncryptedJsonFile(KeyPath);
}
2021-09-27 12:42:46 +00:00
public async ValueTask<bool> Delete()
2021-10-23 16:51:17 +00:00
{
if (!KeyPath.FileExists()) return false;
KeyPath.Delete();
return true;
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public async ValueTask<T?> Get()
{
var path = KeyPath;
if (path.FileExists())
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
return await path.FromEncryptedJsonFile<T>();
2021-09-27 12:42:46 +00:00
}
2021-10-23 16:51:17 +00:00
var value = EnvValue;
if (value == default)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
_logger.LogCritical("No login data for {key}", _key);
throw new Exception("No login data for {_key}");
2021-09-27 12:42:46 +00:00
}
2021-10-23 16:51:17 +00:00
return _dtos.Deserialize<T>(EnvValue!);
}
public bool HaveToken()
{
return KeyPath.FileExists() || EnvValue != null;
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public void DeleteToken()
{
_logger.LogInformation("Deleting token {token}", _key);
if (HaveToken())
KeyPath.Delete();
2021-09-27 12:42:46 +00:00
}
}