Files
Akari.Prototype/Akari.Prototype.Server/Services/FingerprintManager.cs
2021-06-03 20:19:42 +02:00

72 lines
2.1 KiB
C#

using Akari.Prototype.Server.Options;
using Akari.Prototype.Server.Utils;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace Akari.Prototype.Server.Services
{
public class FingerprintManager : IFingerprintManager
{
public const string FingerprintsPath = "fingerprints.json";
private readonly ILogger<FingerprintManager> _logger;
private readonly IOptions<AkariOptions> _akariOptions;
private readonly IAuthManager _authManager;
/// <summary>
/// Map token hash to user-friendly name
/// </summary>
private IDictionary<string, string> _fingerprintNames;
public FingerprintManager(ILogger<FingerprintManager> logger, IOptions<AkariOptions> akariOptions,
IAuthManager authManager)
{
_logger = logger;
_akariOptions = akariOptions;
_authManager = authManager;
LoadFingerprints();
}
private void LoadFingerprints()
{
var path = AkariPath.GetPath(FingerprintsPath);
// Create new
if (!File.Exists(path))
{
_fingerprintNames = new Dictionary<string, string>();
File.WriteAllText(path, JsonSerializer.Serialize(_fingerprintNames));
}
// Load
else
{
_fingerprintNames = JsonSerializer.Deserialize<IDictionary<string, string>>(File.ReadAllText(path));
}
}
public async Task VerifyToken(byte[] token)
{
var hash = Security.Argon2idHash(token);
_logger.LogDebug($"Verifying hash: {hash}");
if (!_fingerprintNames.TryGetValue(hash, out var name))
{
_logger.LogDebug($"Unknown hash, aborting: {hash}");
return;
}
_authManager.Auth(token, name);
}
}
}