Implements authentication system

This commit is contained in:
BinaryAlley committed 2024-11-11 22:57:33 +02:00
1 parent 38829d64ff
commit a6dcf65d1c
103 files changed
+2983 -454

No files matched your search

@@ -46,10 +46,12 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
Dictionary<string, object?> extensionsDictionary = [];
int statusCode = error.Type switch
{
ErrorType.Conflict => StatusCodes.Status409Conflict,
ErrorType.NotFound => StatusCodes.Status404NotFound,
ErrorType.Validation => StatusCodes.Status400BadRequest,
ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in)
ErrorType.Failure => StatusCodes.Status403Forbidden,
ErrorType.Forbidden => StatusCodes.Status403Forbidden,
ErrorType.NotFound => StatusCodes.Status404NotFound,
ErrorType.Conflict => StatusCodes.Status409Conflict,
_ => StatusCodes.Status500InternalServerError,
};
@@ -92,7 +94,7 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
// return a validation problem result with the constructed error details
return Results.ValidationProblem(
errorsDictionary,
detail: "One or more validation errors occurred.",
detail: "One or more validation errors occurred.", // TODO: implement translation?
instance: HttpContext.Request.Path,
statusCode: 422,
title: "Validation Error",
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries;
using Lumina.Contracts.Responses.UsersManagement;
using Lumina.Presentation.Api.Common.Routes.Maintenance;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// API endpoint for the <c>/initialization</c> route.
/// </summary>
public class CheckInitializationEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CheckInitializationEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Initialization.CHECK_INITIALIZATION);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Checks the initialization status of the application (if the Admin account exists).
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
InitializationResponse result = await _sender.Send(new CheckInitializationQuery(), cancellationToken).ConfigureAwait(false);
return await Task.FromResult(TypedResults.Ok(result));
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.UsersManagement;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Class used for providing a textual description for the <see cref="CheckInitializationEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class CheckInitializationEndpointSummary : Summary<CheckInitializationEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="CheckInitializationEndpointSummary"/> class.
/// </summary>
public CheckInitializationEndpointSummary()
{
Summary = "Checks the initialization status of the application.";
Description = "Checks the initialization status of the application (if the Admin account exists).";
Response<InitializationResponse>(200, "The application initialization status is returned.");
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Presentation.Api.Common.Routes.Maintenance;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// API endpoint for the <c>/initialization</c> route.
/// </summary>
public class SetupApplicationEndpoint : BaseEndpoint<RegistrationRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public SetupApplicationEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Initialization.SETUP_APPLICATION);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Performs the initial application setup, including creating the Admin account.
/// </summary>
/// <param name="request">The request containing the Admin user to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RegistrationRequest request, CancellationToken cancellationToken)
{
ErrorOr<RegistrationResponse> result = await _sender.Send(request.ToSetupCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{Api.Common.Routes.UsersManagement.ApiRoutes.Users.GET_USER_BY_ID}/{result.Value.Id}", result.Value), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetupApplicationEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class SetupApplicationEndpointSummary : Summary<SetupApplicationEndpoint, RegistrationRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetupApplicationEndpointSummary"/> class.
/// </summary>
public SetupApplicationEndpointSummary()
{
Summary = "Performs the initial application setup.";
Description = "Performs the initial application setup, including creating the Admin account.";
RequestParam(r => r.Username, "The desired username for the new account.");
RequestParam(r => r.Password, "The password for the new account.");
RequestParam(r => r.PasswordConfirm, "The confirmation of the entered password, used to ensure consistency.");
RequestParam(r => r.Use2fa, "Indicates whether two-factor authentication (2FA) should be enabled for the new account.");
Response(200, "The Admin account of the application is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -5,7 +5,7 @@ using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Common.Routes.Maintenance;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword;
/// <summary>
/// API endpoint for the <c>/auth/change-password</c> route.
/// </summary>
public class ChangePasswordEndpoint : BaseEndpoint<ChangePasswordRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public ChangePasswordEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.CHANGE_PASSWORD);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Changes the password of an account.
/// </summary>
/// <param name="request">The request containing the account for which to change the password.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ChangePasswordRequest request, CancellationToken cancellationToken)
{
ErrorOr<ChangePasswordResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.ChangePassword;
/// <summary>
/// Class used for providing a textual description for the <see cref="ChangePasswordEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class ChangePasswordEndpointSummary : Summary<ChangePasswordEndpoint, ChangePasswordRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ChangePasswordEndpointSummary"/> class.
/// </summary>
public ChangePasswordEndpointSummary()
{
Summary = "Changes the password of an account.";
Description = "Changes the password of an account by reseting its password, after verifying TOTP code associated with the account.";
RequestParam(r => r.CurrentPassword, "The current password of the account for which to change the password.");
RequestParam(r => r.NewPassword, "The new password of the account for which to change the password.");
RequestParam(r => r.NewPasswordConfirm, "The confirmation of the new password of the account for which to change the password.");
Response(200, "The password of the account is changed.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -1,13 +1,17 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -40,6 +44,7 @@ public class LoginEndpoint : BaseEndpoint<LoginRequest, IResult>
Version(1);
AllowAnonymous();
DontCatchExceptions();
Options(x => x.RequireRateLimiting("authenticationPolicy"));
}
/// <summary>
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Login;
/// <summary>
/// Class used for providing a textual description for the <see cref="LoginEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class LoginEndpointSummary : Summary<LoginEndpoint, LoginRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpointSummary"/> class.
/// </summary>
public LoginEndpointSummary()
{
Summary = "Authenticates an account.";
Description = "Authenticates an application account.";
RequestParam(r => r.Username, "The username of the account to authenticate.");
RequestParam(r => r.Password, "The password of the account to authenticate.");
RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) of the account to authenticate.");
Response(200, "The JWT authentication token is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.Authentication;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword;
/// <summary>
/// API endpoint for the <c>/auth/recover-password</c> route.
/// </summary>
public class RecoverPasswordEndpoint : BaseEndpoint<RecoverPasswordRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public RecoverPasswordEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.RECOVER_PASSWORD);
Version(1);
AllowAnonymous();
DontCatchExceptions();
Options(x => x.RequireRateLimiting("authenticationPolicy"));
}
/// <summary>
/// Recovers the password of an account.
/// </summary>
/// <param name="request">The request containing the account for which to recover the password.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(RecoverPasswordRequest request, CancellationToken cancellationToken)
{
ErrorOr<RecoverPasswordResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.RecoverPassword;
/// <summary>
/// Class used for providing a textual description for the <see cref="RecoverPasswordEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class RecoverPasswordEndpointSummary : Summary<RecoverPasswordEndpoint, RecoverPasswordRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="RecoverPasswordEndpointSummary"/> class.
/// </summary>
public RecoverPasswordEndpointSummary()
{
Summary = "Recovers the password of an account.";
Description = "Recovers the password of an account by reseting its password, after verifying TOTP code associated with the account.";
RequestParam(r => r.Username, "The username of the account for which to recover the password.");
RequestParam(r => r.TotpCode, "The TOTP (Time-Based One-Time Password) of the account for which to recover the password.");
Response(200, "The password of the account is reset.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -12,10 +12,10 @@ using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register;
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register;
/// <summary>
/// API endpoint for the <c>/account/register</c> route.
/// API endpoint for the <c>/auth/register</c> route.
/// </summary>
public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
{
@@ -36,7 +36,7 @@ public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Account.REGISTER_ACCOUNT);
Routes(ApiRoutes.Authentication.REGISTER_ACCOUNT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
@@ -3,7 +3,7 @@ using FastEndpoints;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register;
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register;
/// <summary>
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for Swagger.