2023-08-13 18:03:08 +01:00
|
|
|
using System.Collections.Concurrent;
|
2023-08-12 20:13:47 +01:00
|
|
|
using System.Diagnostics.CodeAnalysis;
|
2024-02-25 17:21:29 +00:00
|
|
|
using System.Security.Cryptography;
|
2023-08-12 20:13:47 +01:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2024-02-24 14:52:43 +00:00
|
|
|
using OliverBooth.Data.Web;
|
2024-02-20 20:39:52 +00:00
|
|
|
using BC = BCrypt.Net.BCrypt;
|
2024-02-25 17:21:29 +00:00
|
|
|
using Timer = System.Timers.Timer;
|
2023-08-12 20:13:47 +01:00
|
|
|
|
2023-08-13 17:33:54 +01:00
|
|
|
namespace OliverBooth.Services;
|
2023-08-12 20:13:47 +01:00
|
|
|
|
|
|
|
/// <summary>
|
2024-02-24 14:52:43 +00:00
|
|
|
/// Represents an implementation of <see cref="IUserService" />.
|
2023-08-12 20:13:47 +01:00
|
|
|
/// </summary>
|
2024-02-25 17:21:29 +00:00
|
|
|
internal sealed class UserService : BackgroundService, IUserService
|
2023-08-12 20:13:47 +01:00
|
|
|
{
|
2024-02-25 17:21:29 +00:00
|
|
|
private static readonly RandomNumberGenerator RandomNumberGenerator = RandomNumberGenerator.Create();
|
2024-02-24 14:52:43 +00:00
|
|
|
private readonly IDbContextFactory<WebContext> _dbContextFactory;
|
2023-08-13 18:03:08 +01:00
|
|
|
private readonly ConcurrentDictionary<Guid, IUser> _userCache = new();
|
2024-02-25 17:21:29 +00:00
|
|
|
private readonly ConcurrentDictionary<string, MfaToken> _tokenCache = new();
|
|
|
|
private readonly Timer _tokenClearTimer = new();
|
2023-08-12 20:13:47 +01:00
|
|
|
|
|
|
|
/// <summary>
|
2024-02-24 14:52:43 +00:00
|
|
|
/// Initializes a new instance of the <see cref="UserService" /> class.
|
2023-08-12 20:13:47 +01:00
|
|
|
/// </summary>
|
|
|
|
/// <param name="dbContextFactory">
|
2024-02-24 14:52:43 +00:00
|
|
|
/// The <see cref="IDbContextFactory{TContext}" /> used to create a <see cref="WebContext" />.
|
2023-08-12 20:13:47 +01:00
|
|
|
/// </param>
|
2024-02-24 14:52:43 +00:00
|
|
|
public UserService(IDbContextFactory<WebContext> dbContextFactory)
|
2023-08-12 20:13:47 +01:00
|
|
|
{
|
|
|
|
_dbContextFactory = dbContextFactory;
|
2024-02-25 17:21:29 +00:00
|
|
|
|
|
|
|
_tokenClearTimer.Interval = TimeSpan.FromMinutes(5).TotalMilliseconds;
|
|
|
|
_tokenClearTimer.Elapsed += (_, _) => ClearExpiredTokens();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public void ClearExpiredTokens()
|
|
|
|
{
|
|
|
|
DateTimeOffset now = DateTimeOffset.UtcNow;
|
|
|
|
var keysToRemove = new string[_tokenCache.Count];
|
|
|
|
var insertionIndex = 0;
|
|
|
|
|
|
|
|
foreach (var (key, token) in _tokenCache)
|
|
|
|
{
|
|
|
|
if (token.Expires <= now)
|
|
|
|
{
|
|
|
|
keysToRemove[insertionIndex++] = key;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for (var index = 0; index < insertionIndex; index++)
|
|
|
|
{
|
|
|
|
_tokenCache.TryRemove(keysToRemove[index], out _);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public void ClearTokens()
|
|
|
|
{
|
|
|
|
_tokenCache.Clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public IMfaToken CreateMfaToken(IUser user)
|
|
|
|
{
|
|
|
|
if (user is null)
|
|
|
|
{
|
|
|
|
throw new ArgumentNullException(nameof(user));
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
DateTimeOffset now = DateTimeOffset.UtcNow;
|
|
|
|
var token = new MfaToken
|
|
|
|
{
|
|
|
|
Token = CreateToken(),
|
|
|
|
User = user,
|
|
|
|
Attempts = 0,
|
|
|
|
Created = now,
|
|
|
|
Expires = now + TimeSpan.FromMinutes(5)
|
|
|
|
};
|
|
|
|
|
|
|
|
_tokenCache[token.Token] = token;
|
|
|
|
return token;
|
|
|
|
|
|
|
|
// while we do want a string, BitConvert.ToString requires a heap byte array
|
|
|
|
// which is just very not pog. so this method behaves the same but uses a Span<byte>
|
|
|
|
// while still returning a string necessary for the IMfaToken model
|
|
|
|
static string CreateToken()
|
|
|
|
{
|
|
|
|
ReadOnlySpan<char> hexChars = "0123456789ABCDEF";
|
|
|
|
Span<char> chars = stackalloc char[128];
|
|
|
|
Span<byte> buffer = stackalloc byte[64];
|
|
|
|
RandomNumberGenerator.GetBytes(buffer);
|
|
|
|
|
|
|
|
for (var index = 0; index < buffer.Length; index++)
|
|
|
|
{
|
|
|
|
int byteValue = buffer[index];
|
|
|
|
chars[index * 2] = hexChars[byteValue >> 4];
|
|
|
|
chars[index * 2 + 1] = hexChars[byteValue & 0xF];
|
|
|
|
}
|
|
|
|
|
|
|
|
return chars.ToString();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public void DeleteToken(string token)
|
|
|
|
{
|
|
|
|
if (token is null)
|
|
|
|
{
|
|
|
|
throw new ArgumentNullException(nameof(token));
|
|
|
|
}
|
|
|
|
|
|
|
|
_tokenCache.TryRemove(token, out _);
|
2023-08-12 20:13:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public bool TryGetUser(Guid id, [NotNullWhen(true)] out IUser? user)
|
|
|
|
{
|
2024-02-25 14:11:33 +00:00
|
|
|
if (_userCache.TryGetValue(id, out user))
|
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|
2023-08-13 18:03:08 +01:00
|
|
|
|
2024-02-24 14:52:43 +00:00
|
|
|
using WebContext context = _dbContextFactory.CreateDbContext();
|
2023-08-12 20:13:47 +01:00
|
|
|
user = context.Users.Find(id);
|
2023-08-13 18:03:08 +01:00
|
|
|
|
2024-02-25 14:11:33 +00:00
|
|
|
if (user is not null)
|
|
|
|
{
|
|
|
|
_userCache.TryAdd(id, user);
|
|
|
|
}
|
|
|
|
|
2023-08-12 20:13:47 +01:00
|
|
|
return user is not null;
|
|
|
|
}
|
2024-02-20 20:39:52 +00:00
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public bool VerifyLogin(string email, string password, [NotNullWhen(true)] out IUser? user)
|
|
|
|
{
|
2024-02-24 14:52:43 +00:00
|
|
|
using WebContext context = _dbContextFactory.CreateDbContext();
|
2024-02-20 20:39:52 +00:00
|
|
|
user = context.Users.FirstOrDefault(u => u.EmailAddress == email);
|
|
|
|
return user is not null && BC.Verify(password, ((User)user).Password);
|
|
|
|
}
|
2024-02-25 17:21:29 +00:00
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public MfaRequestResult VerifyMfaRequest(string token, string totp, out IUser? user)
|
|
|
|
{
|
|
|
|
if (token is null)
|
|
|
|
{
|
|
|
|
throw new ArgumentNullException(nameof(token));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (totp is null)
|
|
|
|
{
|
|
|
|
throw new ArgumentNullException(nameof(totp));
|
|
|
|
}
|
|
|
|
|
|
|
|
user = null;
|
|
|
|
|
|
|
|
if (!_tokenCache.TryGetValue(token, out MfaToken? mfaToken))
|
|
|
|
{
|
|
|
|
return MfaRequestResult.TokenExpired;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!mfaToken.User.TestTotp(totp))
|
|
|
|
{
|
|
|
|
mfaToken.Attempts++;
|
|
|
|
if (mfaToken.Attempts == 4)
|
|
|
|
{
|
|
|
|
return MfaRequestResult.TooManyAttempts;
|
|
|
|
}
|
|
|
|
|
|
|
|
return MfaRequestResult.InvalidTotp;
|
|
|
|
}
|
|
|
|
|
|
|
|
user = mfaToken.User;
|
|
|
|
return MfaRequestResult.Success;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public override Task StopAsync(CancellationToken cancellationToken)
|
|
|
|
{
|
|
|
|
_tokenClearTimer.Stop();
|
|
|
|
return base.StopAsync(cancellationToken);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
|
|
|
{
|
|
|
|
ClearTokens();
|
|
|
|
_tokenClearTimer.Start();
|
|
|
|
return Task.CompletedTask;
|
|
|
|
}
|
2023-08-12 20:13:47 +01:00
|
|
|
}
|