Files
Akari.Prototype/Akari.Prototype.Server/Services/FingerprintManager.cs
Eveldee 2b81f3e5ba Add AuthLifetimeService
Refactor AuthManager
2021-06-04 18:32:47 +02:00

89 lines
2.4 KiB
C#

using Akari.Prototype.Server.Options;
using Akari.Prototype.Server.Utils;
using Isopoh.Cryptography.Argon2;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Threading;
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 IAuthManager _authManager;
private readonly AkariPath _akariPath;
private IDictionary<string, string> _tokensHash;
public FingerprintManager(ILogger<FingerprintManager> logger, IAuthManager authManager, AkariPath akariPath)
{
_logger = logger;
_authManager = authManager;
_akariPath = akariPath;
LoadFingerprints();
}
private void LoadFingerprints()
{
var path = _akariPath.GetPath(FingerprintsPath);
// Create new
if (!File.Exists(path))
{
_tokensHash = new Dictionary<string, string>();
File.WriteAllText(path, JsonSerializer.Serialize(_tokensHash));
}
// Load
else
{
_tokensHash = JsonSerializer.Deserialize<IDictionary<string, string>>(File.ReadAllText(path));
}
}
public void VerifyFingerprint(string name, string token)
{
_logger.LogDebug($"Verifying hash for {name}");
var handle = GCHandle.Alloc(token, GCHandleType.Pinned);
if (!_tokensHash.TryGetValue(name, out var hash))
{
_logger.LogDebug($"No fingerprint exist with the name: {name}");
handle.Free();
return;
}
if (!Argon2.Verify(hash, token))
{
_logger.LogDebug($"Token doesn't match stored hash: {name}");
handle.Free();
return;
}
try
{
_authManager.Auth(name, token);
}
finally
{
handle.Free();
}
}
}
}