65 lines
2.3 KiB
C#
65 lines
2.3 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Flypaper.Storage.Settings;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Flypaper.Web.Auth;
|
|
|
|
public sealed class AdminAuthenticator(IOptions<AdminOptions> options, AdminCredentialStore store)
|
|
{
|
|
public const int MinimumPasswordLength = 12;
|
|
|
|
private static readonly PasswordHasher<AdminAccount> Hasher = new();
|
|
private static readonly AdminAccount Account = new();
|
|
|
|
public bool UsesEnvironmentPassword => !string.IsNullOrEmpty(options.Value.Password);
|
|
|
|
public async Task<bool> IsConfiguredAsync(CancellationToken ct = default) =>
|
|
UsesEnvironmentPassword || await store.GetPasswordHashAsync(ct) is not null;
|
|
|
|
public async Task<bool> VerifyAsync(string? candidate, CancellationToken ct = default)
|
|
{
|
|
if (string.IsNullOrEmpty(candidate))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (UsesEnvironmentPassword)
|
|
{
|
|
return CryptographicOperations.FixedTimeEquals(Sha256(candidate), Sha256(options.Value.Password!));
|
|
}
|
|
|
|
return await store.GetPasswordHashAsync(ct) is { } hash
|
|
&& Hasher.VerifyHashedPassword(Account, hash, candidate) != PasswordVerificationResult.Failed;
|
|
}
|
|
|
|
public async Task<bool> TrySetInitialPasswordAsync(string password, CancellationToken ct = default) =>
|
|
!UsesEnvironmentPassword && await store.TryCreatePasswordHashAsync(Hasher.HashPassword(Account, password), ct);
|
|
|
|
public async Task<bool> TryChangePasswordAsync(string currentPassword, string newPassword, CancellationToken ct = default)
|
|
{
|
|
if (UsesEnvironmentPassword || !await VerifyAsync(currentPassword, ct))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
await store.UpdatePasswordHashAsync(Hasher.HashPassword(Account, newPassword), ct);
|
|
return true;
|
|
}
|
|
|
|
public static string? ValidateNewPassword(string? password, string? confirmation)
|
|
{
|
|
if (string.IsNullOrEmpty(password) || password.Length < MinimumPasswordLength)
|
|
{
|
|
return $"Mindestens {MinimumPasswordLength} Zeichen.";
|
|
}
|
|
|
|
return password == confirmation ? null : "Die Passwörter stimmen nicht überein.";
|
|
}
|
|
|
|
private static byte[] Sha256(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value));
|
|
|
|
public sealed class AdminAccount;
|
|
}
|