2021-09-27 12:42:46 +00:00
|
|
|
using System;
|
2021-12-18 16:39:08 +00:00
|
|
|
using System.Security.Cryptography;
|
2021-09-27 12:42:46 +00:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Wabbajack.DTOs.Logins;
|
|
|
|
using Wabbajack.Hashing.xxHash64;
|
|
|
|
using Wabbajack.Networking.Http.Interfaces;
|
|
|
|
using Wabbajack.Paths;
|
|
|
|
using Wabbajack.Paths.IO;
|
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
namespace Wabbajack.Services.OSIntegrated.TokenProviders;
|
|
|
|
|
|
|
|
public class WabbajackApiTokenProvider : ITokenProvider<WabbajackApiState>
|
2021-09-27 12:42:46 +00:00
|
|
|
{
|
2021-10-23 16:51:17 +00:00
|
|
|
private AbsolutePath MetricsPath => KnownFolders.WabbajackAppLocal.Combine("encrypted", "metrics-key");
|
|
|
|
private AbsolutePath AuthorKeyPath => KnownFolders.WabbajackAppLocal.Combine("author-api-key.txt");
|
|
|
|
|
|
|
|
public async ValueTask<WabbajackApiState?> Get()
|
2021-09-27 12:42:46 +00:00
|
|
|
{
|
2021-10-23 16:51:17 +00:00
|
|
|
if (!MetricsPath.FileExists())
|
|
|
|
await CreateMetricsKey();
|
|
|
|
|
2021-12-18 16:29:56 +00:00
|
|
|
string wjToken;
|
|
|
|
try
|
|
|
|
{
|
|
|
|
wjToken = (await MetricsPath.FromEncryptedJsonFile<string>())!;
|
|
|
|
}
|
2021-12-18 16:35:11 +00:00
|
|
|
catch (CryptographicException)
|
2021-12-18 16:29:56 +00:00
|
|
|
{
|
|
|
|
MetricsPath.Delete();
|
|
|
|
await CreateMetricsKey();
|
|
|
|
wjToken = (await MetricsPath.FromEncryptedJsonFile<string>())!;
|
|
|
|
}
|
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
return new WabbajackApiState
|
2021-09-27 12:42:46 +00:00
|
|
|
{
|
2021-12-18 16:29:56 +00:00
|
|
|
MetricsKey = wjToken,
|
2021-12-19 22:20:24 +00:00
|
|
|
AuthorKey = AuthorKeyPath.FileExists() ? (await AuthorKeyPath.ReadAllTextAsync()).Trim() : null
|
2021-10-23 16:51:17 +00:00
|
|
|
};
|
|
|
|
}
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
public ValueTask SetToken(WabbajackApiState val)
|
|
|
|
{
|
|
|
|
throw new NotImplementedException();
|
|
|
|
}
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
public ValueTask<bool> TryDelete(WabbajackApiState val)
|
|
|
|
{
|
|
|
|
throw new NotImplementedException();
|
|
|
|
}
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
private async Task CreateMetricsKey()
|
|
|
|
{
|
|
|
|
var key = MakeRandomKey();
|
|
|
|
await key.AsEncryptedJsonFile(MetricsPath);
|
|
|
|
}
|
2021-09-27 12:42:46 +00:00
|
|
|
|
2021-10-23 16:51:17 +00:00
|
|
|
public static string MakeRandomKey()
|
|
|
|
{
|
|
|
|
var random = new Random();
|
|
|
|
var bytes = new byte[32];
|
|
|
|
random.NextBytes(bytes);
|
|
|
|
return bytes.ToHex();
|
2021-09-27 12:42:46 +00:00
|
|
|
}
|
|
|
|
}
|