Implements account login

This commit is contained in:
BinaryAlley committed 2024-11-11 15:19:50 +02:00
1 parent abc2777357
commit 38829d64ff
23 files changed
+826 -7

No files matched your search

@@ -17,7 +17,7 @@ public class UserEntity : IStorageEntity
/// <summary>
/// Gets the Id of the user.
/// </summary>
public required Guid Id { get; init; }
public Guid Id { get; init; }
/// <summary>
/// Gets or sets the username of the user.
@@ -1,7 +1,10 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Users;
@@ -10,6 +13,14 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Users;
/// Interface for the repository for users.
/// </summary>
public interface IUserRepository : IRepository<UserEntity>,
IGetAllRepositoryAction<UserEntity>,
IInsertRepositoryAction<UserEntity>
{
/// <summary>
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
/// </summary>
/// <param name="username">The username of the user to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="UserEntity"/> if found, or an error.</returns>
Task<ErrorOr<UserEntity?>> GetByUsernameAsync(string username, CancellationToken cancellationToken);
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
#endregion
namespace Lumina.Application.Common.Errors;
/// <summary>
/// Application authentication related error types.
/// </summary>
public static partial class Errors
{
public static class Authentication
{
public static Error UsernameAlreadyExists => Error.Conflict(description: nameof(UsernameAlreadyExists));
public static Error UsernameCannotBeEmpty => Error.Validation(description: nameof(UsernameCannotBeEmpty));
public static Error PasswordCannotBeEmpty => Error.Validation(description: nameof(PasswordCannotBeEmpty));
public static Error PasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(PasswordConfirmCannotBeEmpty));
public static Error InvalidPassword => Error.Validation(description: nameof(InvalidPassword));
public static Error PasswordsNotMatch => Error.Validation(description: nameof(PasswordsNotMatch));
public static Error InvalidTotpCode => Error.Validation(description: nameof(InvalidTotpCode));
public static Error InvalidUsernameOrPassword => Error.Failure(description: nameof(InvalidUsernameOrPassword));
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Application.Common.Mapping.Authentication;
/// <summary>
/// Extension methods for converting <see cref="LoginRequest"/>.
/// </summary>
public static class LoginRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="LoginUserQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static LoginUserQuery ToQuery(this LoginRequest request)
{
return new LoginUserQuery(
request.Username,
request.Password,
request.TotpCode
);
}
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
/// <summary>
/// Query for authenticating an account.
/// </summary>
/// <param name="Username">The username of the account to authenticate.</param>
/// <param name="Password">The password of the account to authenticate.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account to authenticate.</param>
[DebuggerDisplay("Path: {Path}")]
public record LoginUserQuery(
string? Username,
string? Password,
string? TotpCode = null
) : IRequest<ErrorOr<LoginResponse>>;
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
/// <summary>
/// Handler for the query to authenticate an account.
/// </summary>
public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<LoginResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
private readonly IJwtTokenGenerator _jwtTokenGenerator;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly ICryptographyService _cryptographyService;
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="hashService">Injected service for password hashing functionality.</param>
/// <param name="jwtTokenGenerator">Injected service for generating JWT tokens.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
public LoginUserQueryHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
IJwtTokenGenerator jwtTokenGenerator,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_jwtTokenGenerator = jwtTokenGenerator;
_totpTokenGenerator = totpTokenGenerator;
_cryptographyService = cryptographyService;
}
/// <summary>
/// Handles the query to authenticate an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LoginResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LoginResponse>> Handle(LoginUserQuery request, CancellationToken cancellationToken)
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
return Errors.Authentication.InvalidUsernameOrPassword;
// validate the password is correct
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
return Errors.Authentication.InvalidUsernameOrPassword;
// create the JWT token
string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username);
// check if the user uses TOTP
bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret);
if (usesTotp && string.IsNullOrEmpty(request.TotpCode))
return Errors.Authentication.InvalidTotpCode;
else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode))
return Errors.Authentication.InvalidTotpCode;
return new LoginResponse(resultSelectUser.Value.Id, resultSelectUser.Value.Username, token, usesTotp);
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using System.Linq;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
/// <summary>
/// Validates the needed validation rules for <see cref="LoginUserQuery"/>.
/// </summary>
public class LoginUserQueryValidator : AbstractValidator<LoginUserQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryValidator"/> class.
/// </summary>
public LoginUserQueryValidator()
{
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description);
RuleFor(m => m!.TotpCode)
.Custom((code, context) =>
{
if (string.IsNullOrEmpty(code))
return;
if (code.Length != 6)
context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description);
if (!code.All(char.IsDigit))
context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description);
});
}
}