2023-08-13 18:03:08 +01:00
|
|
|
using System.Collections.Concurrent;
|
2023-08-12 20:13:47 +01:00
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
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;
|
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-24 14:52:43 +00:00
|
|
|
internal sealed class UserService : IUserService
|
2023-08-12 20:13:47 +01:00
|
|
|
{
|
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();
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <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);
|
|
|
|
}
|
2023-08-12 20:13:47 +01:00
|
|
|
}
|