2021-09-27 12:42:46 +00:00
|
|
|
using System;
|
|
|
|
using System.Threading.Tasks;
|
2021-12-18 16:35:11 +00:00
|
|
|
using SharpCompress.Common;
|
2021-09-27 12:42:46 +00:00
|
|
|
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-10-23 16:51:17 +00:00
|
|
|
AuthorKey = AuthorKeyPath.FileExists() ? await AuthorKeyPath.ReadAllTextAsync() : null
|
|
|
|
};
|
|
|
|
}
|
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
|
|
|
}
|
|
|
|
}
|