using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore; using OliverBooth.Data; using OliverBooth.Data.Blog; namespace OliverBooth.Services; /// /// Represents a service for managing blog users. /// public sealed class BlogUserService { private readonly IDbContextFactory _dbContextFactory; /// /// Initializes a new instance of the class. /// /// The database context factory. public BlogUserService(IDbContextFactory dbContextFactory) { _dbContextFactory = dbContextFactory; } /// /// Attempts to authenticate the user with the specified email address and password. /// /// The email address. /// The password. /// /// When this method returns, contains the user with the specified email address and password, if the user /// exists; otherwise, . /// /// /// if the authentication was successful; otherwise, . /// public bool TryAuthenticateUser(string? emailAddress, string? password, [NotNullWhen(true)] out User? user) { if (string.IsNullOrWhiteSpace(emailAddress) || string.IsNullOrWhiteSpace(password)) { user = null; return false; } using BlogContext context = _dbContextFactory.CreateDbContext(); user = context.Users.FirstOrDefault(u => u.EmailAddress == emailAddress); if (user is null) { return false; } string hashedPassword = BC.HashPassword(password, user.Salt); return hashedPassword == user.Password; } /// /// Attempts to retrieve the user with the specified user ID. /// /// The user ID. /// /// When this method returns, contains the user with the specified user ID, if the user exists; otherwise, /// . /// /// if the user exists; otherwise, . public bool TryGetUser(Guid userId, [NotNullWhen(true)] out User? user) { using BlogContext context = _dbContextFactory.CreateDbContext(); user = context.Users.FirstOrDefault(u => u.Id == userId); return user is not null; } /// /// Returns a value indicating whether the specified user requires a password reset. /// /// The user. /// /// if the specified user requires a password reset; otherwise, /// . /// public bool UserRequiresPasswordReset(User user) { return string.IsNullOrEmpty(user.Password) || string.IsNullOrEmpty(user.Salt); } }