mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 13:11:10 +00:00
Implements authentication system
This commit is contained in:
1 parent
38829d64ff
commit
a6dcf65d1c
103 files changed
+2967
-438
No files matched your search
@@ -29,6 +29,11 @@ public class UserEntity : IStorageEntity
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public required string Password { get; set; }
|
public required string Password { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the temporary hashed password used in password recovery.
|
||||||
|
/// </summary>
|
||||||
|
public string? TempPassword { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the optional Time-based One-Time Password (TOTP) secret for two-factor authentication.
|
/// Gets or sets the optional Time-based One-Time Password (TOTP) secret for two-factor authentication.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -44,6 +49,11 @@ public class UserEntity : IStorageEntity
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public DateTime? VerificationTokenCreated { get; set; }
|
public DateTime? VerificationTokenCreated { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets the date and time when the temporary password used in password recovery was created.
|
||||||
|
/// </summary>
|
||||||
|
public DateTime? TempPasswordCreated { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the collection of libraries owned by this user.
|
/// Gets the collection of libraries owned by this user.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Users;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IUserRepository : IRepository<UserEntity>,
|
public interface IUserRepository : IRepository<UserEntity>,
|
||||||
IGetAllRepositoryAction<UserEntity>,
|
IGetAllRepositoryAction<UserEntity>,
|
||||||
IInsertRepositoryAction<UserEntity>
|
IInsertRepositoryAction<UserEntity>,
|
||||||
|
IUpdateRepositoryAction<UserEntity>
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
|
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
|
||||||
|
|||||||
@@ -12,12 +12,20 @@ public static partial class Errors
|
|||||||
public static class Authentication
|
public static class Authentication
|
||||||
{
|
{
|
||||||
public static Error UsernameAlreadyExists => Error.Conflict(description: nameof(UsernameAlreadyExists));
|
public static Error UsernameAlreadyExists => Error.Conflict(description: nameof(UsernameAlreadyExists));
|
||||||
|
public static Error UsernameDoesNotExist => Error.NotFound(description: nameof(UsernameDoesNotExist));
|
||||||
public static Error UsernameCannotBeEmpty => Error.Validation(description: nameof(UsernameCannotBeEmpty));
|
public static Error UsernameCannotBeEmpty => Error.Validation(description: nameof(UsernameCannotBeEmpty));
|
||||||
|
public static Error TotpCannotBeEmpty => Error.Validation(description: nameof(TotpCannotBeEmpty));
|
||||||
public static Error PasswordCannotBeEmpty => Error.Validation(description: nameof(PasswordCannotBeEmpty));
|
public static Error PasswordCannotBeEmpty => Error.Validation(description: nameof(PasswordCannotBeEmpty));
|
||||||
|
public static Error NewPasswordCannotBeEmpty => Error.Validation(description: nameof(NewPasswordCannotBeEmpty));
|
||||||
|
public static Error CurrentPasswordCannotBeEmpty => Error.Validation(description: nameof(CurrentPasswordCannotBeEmpty));
|
||||||
public static Error PasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(PasswordConfirmCannotBeEmpty));
|
public static Error PasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(PasswordConfirmCannotBeEmpty));
|
||||||
|
public static Error NewPasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(NewPasswordConfirmCannotBeEmpty));
|
||||||
public static Error InvalidPassword => Error.Validation(description: nameof(InvalidPassword));
|
public static Error InvalidPassword => Error.Validation(description: nameof(InvalidPassword));
|
||||||
public static Error PasswordsNotMatch => Error.Validation(description: nameof(PasswordsNotMatch));
|
public static Error PasswordsNotMatch => Error.Validation(description: nameof(PasswordsNotMatch));
|
||||||
public static Error InvalidTotpCode => Error.Validation(description: nameof(InvalidTotpCode));
|
public static Error InvalidTotpCode => Error.Validation(description: nameof(InvalidTotpCode));
|
||||||
public static Error InvalidUsernameOrPassword => Error.Failure(description: nameof(InvalidUsernameOrPassword));
|
public static Error InvalidUsernameOrPassword => Error.Failure(description: nameof(InvalidUsernameOrPassword));
|
||||||
|
public static Error InvalidCurrentPassword => Error.Failure(description: nameof(InvalidCurrentPassword));
|
||||||
|
public static Error TempPasswordExpired => Error.Failure(description: nameof(TempPasswordExpired));
|
||||||
|
public static Error PasswordResetAlreadyRequested => Error.Failure(description: nameof(PasswordResetAlreadyRequested));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using ErrorOr;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Common.Errors;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Application authorization related error types.
|
||||||
|
/// </summary>
|
||||||
|
public static partial class Errors
|
||||||
|
{
|
||||||
|
public static class Authorization
|
||||||
|
{
|
||||||
|
public static Error AdminAccountAlreadyCreated => Error.Unauthorized(description: nameof(AdminAccountAlreadyCreated));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Interface for generating JWT tokens.
|
||||||
|
/// </summary>
|
||||||
|
public interface IJwtTokenGenerator
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a new JWT token.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id">The id of the user for which to generate the token.</param>
|
||||||
|
/// <param name="username">The username for which to generate the token.</param>
|
||||||
|
/// <returns>The generated JWT token.</returns>
|
||||||
|
string GenerateToken(string id, string username);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Interface for the service for generating QR codes for TOTP.
|
||||||
|
/// </summary>
|
||||||
|
public interface IQRCodeGenerator
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a QR code Data URI for the specified TOTP secret.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="username">User's username or unique identifier.</param>
|
||||||
|
/// <param name="secret">The TOTP secret for which the QR code should be generated.</param>
|
||||||
|
/// <returns>Data URI for the QR code.</returns>
|
||||||
|
string GenerateQrCodeDataUri(string username, byte[] secret);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
namespace Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Interface for the service for generating secure tokens for accounts confirmation or recovery.
|
||||||
|
/// </summary>
|
||||||
|
public interface ITokenGenerator
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a secure token.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A secure token.</returns>
|
||||||
|
string GenerateToken();
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Interface for the service for generating and validating TOTP tokens.
|
||||||
|
/// </summary>
|
||||||
|
public interface ITotpTokenGenerator
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a new TOTP secret for a user.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>The generated TOTP secret.</returns>
|
||||||
|
byte[] GenerateSecret();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Validates a TOTP token against the stored secret.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="secret">The user's TOTP secret.</param>
|
||||||
|
/// <param name="token">The token to validate.</param>
|
||||||
|
/// <returns><see langword="true"/> if valid, <see langword="false"/> otherwise.</returns>
|
||||||
|
bool ValidateToken(byte[] secret, string token);
|
||||||
|
}
|
||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
using System;
|
using System;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Application.Common.Infrastructure;
|
namespace Lumina.Application.Common.Infrastructure.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Interface for the service for cryptographic concerns.
|
/// Interface for the service for cryptographic concerns.
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace Lumina.Application.Common.Infrastructure;
|
namespace Lumina.Application.Common.Infrastructure.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Interface for the service for hashing passwords.
|
/// Interface for the service for hashing passwords.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Common.Infrastructure.Time;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Interface for time related concerns.
|
||||||
|
/// </summary>
|
||||||
|
public interface IDateTimeProvider
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The current UTC time.
|
||||||
|
/// </summary>
|
||||||
|
DateTime UtcNow { get; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
|
||||||
|
using Lumina.Contracts.Requests.Authentication;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Common.Mapping.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extension methods for converting <see cref="ChangePasswordRequest"/>.
|
||||||
|
/// </summary>
|
||||||
|
public static class ChangePasswordRequestMapping
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Converts <paramref name="request"/> to <see cref="ChangePasswordCommand"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The request to be converted.</param>
|
||||||
|
/// <returns>The converted command.</returns>
|
||||||
|
public static ChangePasswordCommand ToCommand(this ChangePasswordRequest request)
|
||||||
|
{
|
||||||
|
return new ChangePasswordCommand(
|
||||||
|
request.Username,
|
||||||
|
request.CurrentPassword,
|
||||||
|
request.NewPassword,
|
||||||
|
request.NewPasswordConfirm
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
|
||||||
|
using Lumina.Contracts.Requests.Authentication;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Common.Mapping.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extension methods for converting <see cref="RecoverPasswordRequest"/>.
|
||||||
|
/// </summary>
|
||||||
|
public static class RecoverPasswordRequestMapping
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Converts <paramref name="request"/> to <see cref="RecoverPasswordCommand"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The request to be converted.</param>
|
||||||
|
/// <returns>The converted command.</returns>
|
||||||
|
public static RecoverPasswordCommand ToCommand(this RecoverPasswordRequest request)
|
||||||
|
{
|
||||||
|
return new RecoverPasswordCommand(
|
||||||
|
request.Username,
|
||||||
|
request.TotpCode
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
||||||
using Lumina.Application.Core.UsersManagement.Register;
|
using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||||
using Lumina.Contracts.Requests.Authentication;
|
using Lumina.Contracts.Requests.Authentication;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -27,13 +27,13 @@ public static class RegistrationRequestMapping
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Converts <paramref name="request"/> to <see cref="RegisterCommand"/>.
|
/// Converts <paramref name="request"/> to <see cref="RegisterUserCommand"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="request">The request to be converted.</param>
|
/// <param name="request">The request to be converted.</param>
|
||||||
/// <returns>The converted command.</returns>
|
/// <returns>The converted command.</returns>
|
||||||
public static RegisterCommand ToCommand(this RegistrationRequest request)
|
public static RegisterUserCommand ToCommand(this RegistrationRequest request)
|
||||||
{
|
{
|
||||||
return new RegisterCommand(
|
return new RegisterUserCommand(
|
||||||
request.Username,
|
request.Username,
|
||||||
request.Password,
|
request.Password,
|
||||||
request.PasswordConfirm,
|
request.PasswordConfirm,
|
||||||
|
|||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using ErrorOr;
|
||||||
|
using Lumina.Contracts.Responses.Authentication;
|
||||||
|
using Mediator;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Command for the initial application setup.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Username">The username for the Admin account.</param>
|
||||||
|
/// <param name="Password">The password for the Admin account.</param>
|
||||||
|
/// <param name="PasswordConfirm">Confirmation of the password.</param>
|
||||||
|
/// <param name="Use2fa">Indicates whether to enable two-factor authentication for the Admin account.</param>
|
||||||
|
public record SetupApplicationCommand(
|
||||||
|
string? Username,
|
||||||
|
string? Password,
|
||||||
|
string? PasswordConfirm,
|
||||||
|
bool Use2fa
|
||||||
|
) : IRequest<ErrorOr<RegistrationResponse>>;
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
#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.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handler for the command to perform the initial application setup.
|
||||||
|
/// </summary>
|
||||||
|
public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCommand, ErrorOr<RegistrationResponse>>
|
||||||
|
{
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
|
private readonly IHashService _hashService;
|
||||||
|
private readonly ICryptographyService _cryptographyService;
|
||||||
|
private readonly ITotpTokenGenerator _totpTokenGenerator;
|
||||||
|
private readonly IQRCodeGenerator _qRCodeGenerator;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="SetupApplicationCommandHandler"/> 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="cryptographyService">Injected service for cryptographic functionality.</param>
|
||||||
|
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
|
||||||
|
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
|
||||||
|
public SetupApplicationCommandHandler(
|
||||||
|
IUnitOfWork unitOfWork,
|
||||||
|
IHashService hashService,
|
||||||
|
ICryptographyService cryptographyService,
|
||||||
|
ITotpTokenGenerator totpTokenGenerator,
|
||||||
|
IQRCodeGenerator qRCodeGenerator)
|
||||||
|
{
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_hashService = hashService;
|
||||||
|
_cryptographyService = cryptographyService;
|
||||||
|
_totpTokenGenerator = totpTokenGenerator;
|
||||||
|
_qRCodeGenerator = qRCodeGenerator;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles the command to perform the initial application setup.
|
||||||
|
/// </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="RegistrationResponse"/>, or an error message.
|
||||||
|
/// </returns>
|
||||||
|
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(SetupApplicationCommand request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
// check if any users already exists (admin account is only set once!)
|
||||||
|
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||||
|
ErrorOr<IEnumerable<UserEntity>> resultSelectUser = await userRepository.GetAllAsync(cancellationToken);
|
||||||
|
if (resultSelectUser.IsError)
|
||||||
|
return resultSelectUser.Errors;
|
||||||
|
else if (resultSelectUser.Value.Any())
|
||||||
|
return Errors.Authorization.AdminAccountAlreadyCreated;
|
||||||
|
// no users are present, register the admin one
|
||||||
|
string? totpSecret = null;
|
||||||
|
UserEntity user = new()
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Username = request.Username!,
|
||||||
|
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
|
||||||
|
Created = DateTime.UtcNow,
|
||||||
|
Libraries = []
|
||||||
|
};
|
||||||
|
// if the user enabled two factor auth, include a QR with the totp secret
|
||||||
|
if (request.Use2fa)
|
||||||
|
{
|
||||||
|
// generate a TOTP secret
|
||||||
|
byte[] secret = _totpTokenGenerator.GenerateSecret();
|
||||||
|
// convert the secret into a QR code for the user to scan
|
||||||
|
totpSecret = _qRCodeGenerator.GenerateQrCodeDataUri(request.Username!, secret);
|
||||||
|
// store the TOTP secret in the repository, encrypted
|
||||||
|
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
||||||
|
}
|
||||||
|
// insert the user
|
||||||
|
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken);
|
||||||
|
if (resultInsertUser.IsError)
|
||||||
|
return resultInsertUser.Errors;
|
||||||
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
// TODO: insert the default admin profile preferences when they are implemented
|
||||||
|
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
|
||||||
|
return new RegistrationResponse(user.Id, user.Username, totpSecret);
|
||||||
|
}
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using FluentValidation;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Validates the needed validation rules for <see cref="SetupApplicationCommand"/>.
|
||||||
|
/// </summary>
|
||||||
|
public class SetupApplicationCommandValidator : AbstractValidator<SetupApplicationCommand>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="SetupApplicationCommandValidator"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public SetupApplicationCommandValidator()
|
||||||
|
{
|
||||||
|
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(x => x.PasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
|
||||||
|
RuleFor(x => x.Password).Equal(x => x.PasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description);
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Contracts.Responses.UsersManagement;
|
||||||
|
using Mediator;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Query for checking the initialization of the application.
|
||||||
|
/// </summary>
|
||||||
|
public record CheckInitializationQuery() : IRequest<InitializationResponse>;
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
#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.Contracts.Responses.FileSystemManagement.Path;
|
||||||
|
using Lumina.Contracts.Responses.UsersManagement;
|
||||||
|
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||||
|
using Mediator;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.Maintenance.ApplicationSetup.Queries;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handler for the query to check the initialization of the application.
|
||||||
|
/// </summary>
|
||||||
|
public class CheckInitializationQueryHandler : IRequestHandler<CheckInitializationQuery, InitializationResponse>
|
||||||
|
{
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
|
|
||||||
|
public CheckInitializationQueryHandler(IUnitOfWork unitOfWork)
|
||||||
|
{
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks the initialization status of the application.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request">The query containing the request.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// <see langword="true"/> if the application is initialized (the admin account is created), <see langword="false"/> otherwise.
|
||||||
|
/// </returns>
|
||||||
|
public async ValueTask<InitializationResponse> Handle(CheckInitializationQuery request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||||
|
// if the repository reports an error, or there are no users, the application has not been initialized
|
||||||
|
ErrorOr<IEnumerable<UserEntity>> resultSelectUser = await userRepository.GetAllAsync(cancellationToken);
|
||||||
|
if (!resultSelectUser.IsError)
|
||||||
|
return new InitializationResponse(resultSelectUser.Value.Any());
|
||||||
|
return new InitializationResponse(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using ErrorOr;
|
||||||
|
using Lumina.Contracts.Responses.Authentication;
|
||||||
|
using Mediator;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the request model for account password change.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Username">The username of the account for which to change the password.</param>
|
||||||
|
/// <param name="CurrentPassword">The current password of the account for which to change the password.</param>
|
||||||
|
/// <param name="NewPassword">The new password of the account for which to change the password.</param>
|
||||||
|
/// <param name="NewPasswordConfirm">The confirmation of the new password of the account for which to change the password.</param>
|
||||||
|
public record ChangePasswordCommand(
|
||||||
|
string? Username,
|
||||||
|
string? CurrentPassword,
|
||||||
|
string? NewPassword,
|
||||||
|
string? NewPasswordConfirm
|
||||||
|
) : IRequest<ErrorOr<ChangePasswordResponse>>;
|
||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
#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.Security;
|
||||||
|
using Lumina.Contracts.Responses.Authentication;
|
||||||
|
using Mediator;
|
||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handler for the command to change the password of a user account.
|
||||||
|
/// </summary>
|
||||||
|
public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordCommand, ErrorOr<ChangePasswordResponse>>
|
||||||
|
{
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
|
private readonly IHashService _hashService;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="ChangePasswordCommandHandler"/> 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>
|
||||||
|
public ChangePasswordCommandHandler(
|
||||||
|
IUnitOfWork unitOfWork,
|
||||||
|
IHashService hashService)
|
||||||
|
{
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_hashService = hashService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles the command to change the password of 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="ChangePasswordResponse"/>, or an error message.
|
||||||
|
/// </returns>
|
||||||
|
public async ValueTask<ErrorOr<ChangePasswordResponse>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
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.UsernameDoesNotExist;
|
||||||
|
// validate if the current password is correct
|
||||||
|
if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
|
||||||
|
return Errors.Authentication.InvalidCurrentPassword;
|
||||||
|
resultSelectUser.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!));
|
||||||
|
// if the password change was initiated via a password reset, remote the temporary password that was generated in the process
|
||||||
|
resultSelectUser.Value.TempPassword = null;
|
||||||
|
resultSelectUser.Value.TempPasswordCreated = null;
|
||||||
|
// update the user
|
||||||
|
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
|
||||||
|
if (resultUpdateUser.IsError)
|
||||||
|
return resultUpdateUser.Errors;
|
||||||
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return new ChangePasswordResponse(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using FluentValidation;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Validates the needed validation rules for <see cref="ChangePasswordCommand"/>.
|
||||||
|
/// </summary>
|
||||||
|
public class ChangePasswordCommandValidator : AbstractValidator<ChangePasswordCommand>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="ChangePasswordCommandValidator"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public ChangePasswordCommandValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||||
|
RuleFor(x => x.CurrentPassword).NotEmpty().WithMessage(Errors.Authentication.CurrentPasswordCannotBeEmpty.Description)
|
||||||
|
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description);
|
||||||
|
RuleFor(x => x.NewPassword).NotEmpty().WithMessage(Errors.Authentication.NewPasswordCannotBeEmpty.Description)
|
||||||
|
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description);
|
||||||
|
RuleFor(x => x.NewPasswordConfirm).NotEmpty().WithMessage(Errors.Authentication.NewPasswordConfirmCannotBeEmpty.Description);
|
||||||
|
RuleFor(x => x.NewPassword).Equal(x => x.NewPasswordConfirm).WithMessage(Errors.Authentication.PasswordsNotMatch.Description);
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using ErrorOr;
|
||||||
|
using Lumina.Contracts.Responses.Authentication;
|
||||||
|
using Mediator;
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the request model for account password recovery.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Username">The username of the account for which to recover the password.</param>
|
||||||
|
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account for which to recover the password.</param>
|
||||||
|
[DebuggerDisplay("Username: {Username}")]
|
||||||
|
public record class RecoverPasswordCommand(
|
||||||
|
string? Username,
|
||||||
|
string? TotpCode
|
||||||
|
) : IRequest<ErrorOr<RecoverPasswordResponse>>;
|
||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
#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.Commands.RecoverPassword;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handler for the command to recover the password of an account.
|
||||||
|
/// </summary>
|
||||||
|
public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordCommand, ErrorOr<RecoverPasswordResponse>>
|
||||||
|
{
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
|
private readonly IHashService _hashService;
|
||||||
|
private readonly ITotpTokenGenerator _totpTokenGenerator;
|
||||||
|
private readonly ICryptographyService _cryptographyService;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="RecoverPasswordCommandHandler"/> 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="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
|
||||||
|
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
|
||||||
|
public RecoverPasswordCommandHandler(
|
||||||
|
IUnitOfWork unitOfWork,
|
||||||
|
IHashService hashService,
|
||||||
|
ITotpTokenGenerator totpTokenGenerator,
|
||||||
|
ICryptographyService cryptographyService)
|
||||||
|
{
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_hashService = hashService;
|
||||||
|
_totpTokenGenerator = totpTokenGenerator;
|
||||||
|
_cryptographyService = cryptographyService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles the command to recover the password of 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="RecoverPasswordResponse"/>, or an error message.
|
||||||
|
/// </returns>
|
||||||
|
public async ValueTask<ErrorOr<RecoverPasswordResponse>> Handle(RecoverPasswordCommand 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.UsernameDoesNotExist;
|
||||||
|
else if (resultSelectUser.Value.TempPassword is not null) // if a temp password is present, a password request was already requested
|
||||||
|
return Errors.Authentication.PasswordResetAlreadyRequested;
|
||||||
|
// check if the user uses TOTP
|
||||||
|
bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret);
|
||||||
|
if (!usesTotp)
|
||||||
|
return Errors.Authentication.InvalidTotpCode;
|
||||||
|
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;
|
||||||
|
// hash the new password and assign it to a temporary password that will be valid 15 minutes
|
||||||
|
resultSelectUser.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
|
||||||
|
resultSelectUser.Value.TempPasswordCreated = DateTime.UtcNow;
|
||||||
|
// update the user
|
||||||
|
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
|
||||||
|
if (resultUpdateUser.IsError)
|
||||||
|
return resultUpdateUser.Errors;
|
||||||
|
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return new RecoverPasswordResponse(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using FluentValidation;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Validates the needed validation rules for <see cref="RecoverPasswordCommand"/>.
|
||||||
|
/// </summary>
|
||||||
|
public class RecoverPasswordCommandValidator : AbstractValidator<RecoverPasswordCommand>
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="RecoverPasswordCommandValidator"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public RecoverPasswordCommandValidator()
|
||||||
|
{
|
||||||
|
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||||
|
RuleFor(x => x.TotpCode).NotEmpty().WithMessage(Errors.Authentication.TotpCannotBeEmpty.Description);
|
||||||
|
RuleFor(x => x.TotpCode).Length(6).WithMessage(Errors.Authentication.InvalidTotpCode.Description);
|
||||||
|
RuleFor(x => x.TotpCode).Matches(@"^[0-9]{6}$").WithMessage(Errors.Authentication.InvalidTotpCode.Description);
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -4,7 +4,7 @@ using Lumina.Contracts.Responses.Authentication;
|
|||||||
using Mediator;
|
using Mediator;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Application.Core.UsersManagement.Register;
|
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Command for registering a new account.
|
/// Command for registering a new account.
|
||||||
@@ -13,7 +13,7 @@ namespace Lumina.Application.Core.UsersManagement.Register;
|
|||||||
/// <param name="Password">The password for the new account.</param>
|
/// <param name="Password">The password for the new account.</param>
|
||||||
/// <param name="PasswordConfirm">Confirmation of the password.</param>
|
/// <param name="PasswordConfirm">Confirmation of the password.</param>
|
||||||
/// <param name="Use2fa">Indicates whether to enable two-factor authentication for the new account.</param>
|
/// <param name="Use2fa">Indicates whether to enable two-factor authentication for the new account.</param>
|
||||||
public record RegisterCommand(
|
public record RegisterUserCommand(
|
||||||
string? Username,
|
string? Username,
|
||||||
string? Password,
|
string? Password,
|
||||||
string? PasswordConfirm,
|
string? PasswordConfirm,
|
||||||
+5
-5
@@ -13,12 +13,12 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Application.Core.UsersManagement.Register;
|
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Handler for the command to register a new user account.
|
/// Handler for the command to register a new user account.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class RegisterCommandHandler : IRequestHandler<RegisterCommand, ErrorOr<RegistrationResponse>>
|
public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, ErrorOr<RegistrationResponse>>
|
||||||
{
|
{
|
||||||
private readonly IUnitOfWork _unitOfWork;
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
private readonly IHashService _hashService;
|
private readonly IHashService _hashService;
|
||||||
@@ -27,14 +27,14 @@ public class RegisterCommandHandler : IRequestHandler<RegisterCommand, ErrorOr<R
|
|||||||
private readonly IQRCodeGenerator _qRCodeGenerator;
|
private readonly IQRCodeGenerator _qRCodeGenerator;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="RegisterCommandHandler"/> class.
|
/// Initializes a new instance of the <see cref="RegisterUserCommandHandler"/> class.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
/// <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="hashService">Injected service for password hashing functionality.</param>
|
||||||
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
|
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
|
||||||
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
|
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
|
||||||
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
|
/// <param name="qRCodeGenerator">Injected service for generating QR codes.</param>
|
||||||
public RegisterCommandHandler(
|
public RegisterUserCommandHandler(
|
||||||
IUnitOfWork unitOfWork,
|
IUnitOfWork unitOfWork,
|
||||||
IHashService hashService,
|
IHashService hashService,
|
||||||
ICryptographyService cryptographyService,
|
ICryptographyService cryptographyService,
|
||||||
@@ -48,7 +48,7 @@ public class RegisterCommandHandler : IRequestHandler<RegisterCommand, ErrorOr<R
|
|||||||
_qRCodeGenerator = qRCodeGenerator;
|
_qRCodeGenerator = qRCodeGenerator;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(RegisterCommand request, CancellationToken cancellationToken)
|
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// check if any users already exists (admin account is only set once!)
|
// check if any users already exists (admin account is only set once!)
|
||||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||||
+5
-5
@@ -3,17 +3,17 @@ using FluentValidation;
|
|||||||
using Lumina.Application.Common.Errors;
|
using Lumina.Application.Common.Errors;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Application.Core.UsersManagement.Register;
|
namespace Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Validates the needed validation rules for <see cref="RegisterCommand"/>.
|
/// Validates the needed validation rules for <see cref="RegisterUserCommand"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class RegisterCommandValidator : AbstractValidator<RegisterCommand>
|
public class RegisterUserCommandValidator : AbstractValidator<RegisterUserCommand>
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="RegisterCommandValidator"/> class.
|
/// Initializes a new instance of the <see cref="RegisterUserCommandValidator"/> class.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public RegisterCommandValidator()
|
public RegisterUserCommandValidator()
|
||||||
{
|
{
|
||||||
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||||
RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description)
|
RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description)
|
||||||
+23
-2
@@ -65,9 +65,30 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
|
|||||||
return resultSelectUser.Errors;
|
return resultSelectUser.Errors;
|
||||||
else if (resultSelectUser.Value is null)
|
else if (resultSelectUser.Value is null)
|
||||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||||
// validate the password is correct
|
// validate that the password is correct
|
||||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
|
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
|
||||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
{
|
||||||
|
// if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too
|
||||||
|
if (resultSelectUser.Value.TempPassword is not null)
|
||||||
|
{
|
||||||
|
// the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error
|
||||||
|
if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) > DateTime.UtcNow)
|
||||||
|
{
|
||||||
|
resultSelectUser.Value.TempPassword = null;
|
||||||
|
resultSelectUser.Value.TempPasswordCreated = null;
|
||||||
|
await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
|
||||||
|
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
|
return Errors.Authentication.TempPasswordExpired;
|
||||||
|
}
|
||||||
|
else // temporary password is still valid, validate password against it
|
||||||
|
{
|
||||||
|
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.TempPassword!)))
|
||||||
|
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||||
|
}
|
||||||
// create the JWT token
|
// create the JWT token
|
||||||
string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username);
|
string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username);
|
||||||
// check if the user uses TOTP
|
// check if the user uses TOTP
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace Lumina.Contracts.Requests.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the request model for account password change.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="CurrentPassword">The username of the account.</param>
|
||||||
|
/// <param name="CurrentPassword">The current password of the account.</param>
|
||||||
|
/// <param name="NewPassword">The new password of the account.</param>
|
||||||
|
/// <param name="NewPasswordConfirm">The confirmation of the new password of the account.</param>
|
||||||
|
public record ChangePasswordRequest(
|
||||||
|
string? Username,
|
||||||
|
string? CurrentPassword,
|
||||||
|
string? NewPassword,
|
||||||
|
string? NewPasswordConfirm
|
||||||
|
);
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Contracts.Requests.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the request model for account password recovery.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Username">The username of the account for which to recover the password.</param>
|
||||||
|
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account for which to recover the password.</param>
|
||||||
|
[DebuggerDisplay("Username: {Username}")]
|
||||||
|
public record RecoverPasswordRequest(
|
||||||
|
string? Username,
|
||||||
|
string? TotpCode
|
||||||
|
);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Contracts.Responses.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the response model for an account password change request.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="IsPasswordChanged">Whether the password was changed or not.</param>
|
||||||
|
[DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")]
|
||||||
|
public record ChangePasswordResponse(
|
||||||
|
bool IsPasswordChanged
|
||||||
|
);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Contracts.Responses.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the response model for an account password reset request.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="IsPasswordReset">Whether the password was reset or not.</param>
|
||||||
|
[DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")]
|
||||||
|
public record RecoverPasswordResponse(
|
||||||
|
bool IsPasswordReset
|
||||||
|
);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Contracts.Responses.UsersManagement;
|
||||||
|
|
||||||
|
/// </summary>
|
||||||
|
/// Represents a response for verifying the initialization status of the application.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="IsInitialized">Indicates whether the application has been run before, and the super admin account has been created.</param>
|
||||||
|
[DebuggerDisplay("IsInitialized: {IsInitialized}")]
|
||||||
|
public record InitializationResponse(
|
||||||
|
bool IsInitialized
|
||||||
|
);
|
||||||
@@ -32,15 +32,21 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(2);
|
.HasColumnOrder(2);
|
||||||
|
|
||||||
builder.Property(user => user.TotpSecret)
|
builder.Property(user => user.TempPassword)
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
builder.Property(user => user.VerificationToken)
|
builder.Property(user => user.TotpSecret)
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|
||||||
builder.Property(user => user.VerificationTokenCreated)
|
builder.Property(user => user.VerificationToken)
|
||||||
.HasColumnOrder(5);
|
.HasColumnOrder(5);
|
||||||
|
|
||||||
|
builder.Property(user => user.VerificationTokenCreated)
|
||||||
|
.HasColumnOrder(6);
|
||||||
|
|
||||||
|
builder.Property(user => user.TempPasswordCreated)
|
||||||
|
.HasColumnOrder(7);
|
||||||
|
|
||||||
builder.HasMany(user => user.Libraries)
|
builder.HasMany(user => user.Libraries)
|
||||||
.WithOne(library => library.User)
|
.WithOne(library => library.User)
|
||||||
.HasForeignKey(library => library.UserId)
|
.HasForeignKey(library => library.UserId)
|
||||||
|
|||||||
Generated
+449
@@ -0,0 +1,449 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Lumina.DataAccess.Core.UoW;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Lumina.DataAccess.Common.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(LuminaDbContext))]
|
||||||
|
[Migration("20241111183421_AddUsersTempPasswordColumn")]
|
||||||
|
partial class AddUsersTempPasswordColumn
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "8.0.10");
|
||||||
|
|
||||||
|
modelBuilder.Entity("BookGenres", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("BookId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("GenreId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("BookId", "GenreId");
|
||||||
|
|
||||||
|
b.HasIndex("GenreId");
|
||||||
|
|
||||||
|
b.ToTable("BookGenres", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("BookTags", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("BookId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("TagId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("BookId", "TagId");
|
||||||
|
|
||||||
|
b.HasIndex("TagId");
|
||||||
|
|
||||||
|
b.ToTable("BookTags", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Name");
|
||||||
|
|
||||||
|
b.ToTable("Genres", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Name");
|
||||||
|
|
||||||
|
b.ToTable("Tags", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
|
b.Property<DateTime>("Created")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("LibraryType")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(2);
|
||||||
|
|
||||||
|
b.Property<string>("Title")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(255)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(1);
|
||||||
|
|
||||||
|
b.Property<DateTime?>("Updated")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("UserId");
|
||||||
|
|
||||||
|
b.ToTable("Libraries", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
|
b.Property<string>("ASIN")
|
||||||
|
.HasMaxLength(10)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(21);
|
||||||
|
|
||||||
|
b.Property<string>("AppleBooksId")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(29);
|
||||||
|
|
||||||
|
b.Property<string>("BarnesAndNobleId")
|
||||||
|
.HasMaxLength(10)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(28);
|
||||||
|
|
||||||
|
b.Property<DateTime>("Created")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(30);
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasMaxLength(2000)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
|
b.Property<string>("Edition")
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(19);
|
||||||
|
|
||||||
|
b.Property<string>("Format")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(18);
|
||||||
|
|
||||||
|
b.Property<string>("GoodreadsId")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(22);
|
||||||
|
|
||||||
|
b.Property<string>("GoogleBooksId")
|
||||||
|
.HasMaxLength(12)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(27);
|
||||||
|
|
||||||
|
b.Property<string>("LCCN")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(23);
|
||||||
|
|
||||||
|
b.Property<string>("LanguageCode")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(10);
|
||||||
|
|
||||||
|
b.Property<string>("LanguageName")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(11);
|
||||||
|
|
||||||
|
b.Property<string>("LanguageNativeName")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(12);
|
||||||
|
|
||||||
|
b.Property<string>("LibraryThingId")
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(26);
|
||||||
|
|
||||||
|
b.Property<string>("OCLCNumber")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(24);
|
||||||
|
|
||||||
|
b.Property<string>("OpenLibraryId")
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(25);
|
||||||
|
|
||||||
|
b.Property<string>("OriginalLanguageCode")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(13);
|
||||||
|
|
||||||
|
b.Property<string>("OriginalLanguageName")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(14);
|
||||||
|
|
||||||
|
b.Property<string>("OriginalLanguageNativeName")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(15);
|
||||||
|
|
||||||
|
b.Property<DateOnly?>("OriginalReleaseDate")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(4);
|
||||||
|
|
||||||
|
b.Property<int?>("OriginalReleaseYear")
|
||||||
|
.HasColumnType("INTEGER")
|
||||||
|
.HasColumnOrder(5);
|
||||||
|
|
||||||
|
b.Property<string>("OriginalTitle")
|
||||||
|
.HasMaxLength(255)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(2);
|
||||||
|
|
||||||
|
b.Property<int?>("PageCount")
|
||||||
|
.HasColumnType("INTEGER")
|
||||||
|
.HasColumnOrder(17);
|
||||||
|
|
||||||
|
b.Property<string>("Publisher")
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(16);
|
||||||
|
|
||||||
|
b.Property<DateOnly?>("ReReleaseDate")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(6);
|
||||||
|
|
||||||
|
b.Property<int?>("ReReleaseYear")
|
||||||
|
.HasColumnType("INTEGER")
|
||||||
|
.HasColumnOrder(7);
|
||||||
|
|
||||||
|
b.Property<string>("ReleaseCountry")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(8);
|
||||||
|
|
||||||
|
b.Property<string>("ReleaseVersion")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(9);
|
||||||
|
|
||||||
|
b.Property<string>("Title")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(255)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(1);
|
||||||
|
|
||||||
|
b.Property<DateTime?>("Updated")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(31);
|
||||||
|
|
||||||
|
b.Property<int?>("VolumeNumber")
|
||||||
|
.HasColumnType("INTEGER")
|
||||||
|
.HasColumnOrder(20);
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Books", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
|
b.Property<DateTime>("Created")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Password")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(2);
|
||||||
|
|
||||||
|
b.Property<string>("TempPassword")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
|
b.Property<DateTime?>("TempPasswordCreated")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(7);
|
||||||
|
|
||||||
|
b.Property<string>("TotpSecret")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(4);
|
||||||
|
|
||||||
|
b.Property<DateTime?>("Updated")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Username")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(255)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(1);
|
||||||
|
|
||||||
|
b.Property<string>("VerificationToken")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(5);
|
||||||
|
|
||||||
|
b.Property<DateTime?>("VerificationTokenCreated")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(6);
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("Users", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("BookGenres", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("BookId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("GenreId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("BookTags", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("BookId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null)
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("TagId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||||
|
.WithMany("Libraries")
|
||||||
|
.HasForeignKey("UserId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.Property<Guid>("LibraryId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.Property<string>("Path")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(260)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnName("Path");
|
||||||
|
|
||||||
|
b1.HasKey("Id");
|
||||||
|
|
||||||
|
b1.HasIndex("LibraryId");
|
||||||
|
|
||||||
|
b1.ToTable("LibraryContentLocations", (string)null);
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("LibraryId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("ContentLocations");
|
||||||
|
|
||||||
|
b.Navigation("User");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||||
|
{
|
||||||
|
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.Property<Guid>("BookId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.Property<decimal?>("MaxValue")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("decimal(3,2)");
|
||||||
|
|
||||||
|
b1.Property<string>("Source")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.Property<decimal?>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("decimal(3,2)");
|
||||||
|
|
||||||
|
b1.Property<int?>("VoteCount")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.HasKey("Id");
|
||||||
|
|
||||||
|
b1.HasIndex("BookId");
|
||||||
|
|
||||||
|
b1.ToTable("BookRatings", (string)null);
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("BookId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.Property<Guid>("BookId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.Property<string>("Format")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(6)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(13)
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnName("ISBN");
|
||||||
|
|
||||||
|
b1.HasKey("Id");
|
||||||
|
|
||||||
|
b1.HasIndex("BookId");
|
||||||
|
|
||||||
|
b1.ToTable("BookISBNs", (string)null);
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("BookId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("ISBNs");
|
||||||
|
|
||||||
|
b.Navigation("Ratings");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Libraries");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Lumina.DataAccess.Common.Migrations;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddUsersTempPasswordColumn : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AlterColumn<DateTime>(
|
||||||
|
name: "VerificationTokenCreated",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true,
|
||||||
|
oldClrType: typeof(DateTime),
|
||||||
|
oldType: "TEXT",
|
||||||
|
oldNullable: true)
|
||||||
|
.Annotation("Relational:ColumnOrder", 6)
|
||||||
|
.OldAnnotation("Relational:ColumnOrder", 5);
|
||||||
|
|
||||||
|
migrationBuilder.AlterColumn<string>(
|
||||||
|
name: "VerificationToken",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true,
|
||||||
|
oldClrType: typeof(string),
|
||||||
|
oldType: "TEXT",
|
||||||
|
oldNullable: true)
|
||||||
|
.Annotation("Relational:ColumnOrder", 5)
|
||||||
|
.OldAnnotation("Relational:ColumnOrder", 4);
|
||||||
|
|
||||||
|
migrationBuilder.AlterColumn<string>(
|
||||||
|
name: "TotpSecret",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true,
|
||||||
|
oldClrType: typeof(string),
|
||||||
|
oldType: "TEXT",
|
||||||
|
oldNullable: true)
|
||||||
|
.Annotation("Relational:ColumnOrder", 4)
|
||||||
|
.OldAnnotation("Relational:ColumnOrder", 3);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "TempPassword",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true)
|
||||||
|
.Annotation("Relational:ColumnOrder", 3);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<DateTime>(
|
||||||
|
name: "TempPasswordCreated",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true)
|
||||||
|
.Annotation("Relational:ColumnOrder", 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "TempPassword",
|
||||||
|
table: "Users");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "TempPasswordCreated",
|
||||||
|
table: "Users");
|
||||||
|
|
||||||
|
migrationBuilder.AlterColumn<DateTime>(
|
||||||
|
name: "VerificationTokenCreated",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true,
|
||||||
|
oldClrType: typeof(DateTime),
|
||||||
|
oldType: "TEXT",
|
||||||
|
oldNullable: true)
|
||||||
|
.Annotation("Relational:ColumnOrder", 5)
|
||||||
|
.OldAnnotation("Relational:ColumnOrder", 6);
|
||||||
|
|
||||||
|
migrationBuilder.AlterColumn<string>(
|
||||||
|
name: "VerificationToken",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true,
|
||||||
|
oldClrType: typeof(string),
|
||||||
|
oldType: "TEXT",
|
||||||
|
oldNullable: true)
|
||||||
|
.Annotation("Relational:ColumnOrder", 4)
|
||||||
|
.OldAnnotation("Relational:ColumnOrder", 5);
|
||||||
|
|
||||||
|
migrationBuilder.AlterColumn<string>(
|
||||||
|
name: "TotpSecret",
|
||||||
|
table: "Users",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true,
|
||||||
|
oldClrType: typeof(string),
|
||||||
|
oldType: "TEXT",
|
||||||
|
oldNullable: true)
|
||||||
|
.Annotation("Relational:ColumnOrder", 3)
|
||||||
|
.OldAnnotation("Relational:ColumnOrder", 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -262,10 +262,18 @@ namespace Lumina.DataAccess.Common.Migrations
|
|||||||
.HasColumnType("TEXT")
|
.HasColumnType("TEXT")
|
||||||
.HasColumnOrder(2);
|
.HasColumnOrder(2);
|
||||||
|
|
||||||
b.Property<string>("TotpSecret")
|
b.Property<string>("TempPassword")
|
||||||
.HasColumnType("TEXT")
|
.HasColumnType("TEXT")
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
|
b.Property<DateTime?>("TempPasswordCreated")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(7);
|
||||||
|
|
||||||
|
b.Property<string>("TotpSecret")
|
||||||
|
.HasColumnType("TEXT")
|
||||||
|
.HasColumnOrder(4);
|
||||||
|
|
||||||
b.Property<DateTime?>("Updated")
|
b.Property<DateTime?>("Updated")
|
||||||
.HasColumnType("TEXT");
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
@@ -277,11 +285,11 @@ namespace Lumina.DataAccess.Common.Migrations
|
|||||||
|
|
||||||
b.Property<string>("VerificationToken")
|
b.Property<string>("VerificationToken")
|
||||||
.HasColumnType("TEXT")
|
.HasColumnType("TEXT")
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(5);
|
||||||
|
|
||||||
b.Property<DateTime?>("VerificationTokenCreated")
|
b.Property<DateTime?>("VerificationTokenCreated")
|
||||||
.HasColumnType("TEXT")
|
.HasColumnType("TEXT")
|
||||||
.HasColumnOrder(5);
|
.HasColumnOrder(6);
|
||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
|||||||
@@ -64,4 +64,19 @@ internal sealed class UserRepository : IUserRepository
|
|||||||
{
|
{
|
||||||
return await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == username, cancellationToken).ConfigureAwait(false);
|
return await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == username, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Updates an user.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="data">Ther user to update.</param>
|
||||||
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
|
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
|
||||||
|
public async Task<ErrorOr<Updated>> UpdateAsync(UserEntity data, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
UserEntity? foundUser = await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == data.Username, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (foundUser is null)
|
||||||
|
return Errors.Users.UserDoesNotExist;
|
||||||
|
_luminaDbContext.Entry(foundUser).CurrentValues.SetValues(data);
|
||||||
|
return Result.Updated;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -12,5 +12,6 @@ public static partial class Errors
|
|||||||
public static class Users
|
public static class Users
|
||||||
{
|
{
|
||||||
public static Error UserAlreadyExists => Error.Conflict(description: nameof(UserAlreadyExists));
|
public static Error UserAlreadyExists => Error.Conflict(description: nameof(UserAlreadyExists));
|
||||||
|
public static Error UserDoesNotExist => Error.Conflict(description: nameof(UserDoesNotExist));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+11
-1
@@ -1,7 +1,11 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
using Lumina.Application.Common.Infrastructure;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Security;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Time;
|
||||||
|
using Lumina.Infrastructure.Core.Authentication;
|
||||||
using Lumina.Infrastructure.Core.Security;
|
using Lumina.Infrastructure.Core.Security;
|
||||||
|
using Lumina.Infrastructure.Core.Time;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -25,6 +29,12 @@ public static class InfrastructureLayerServices
|
|||||||
|
|
||||||
services.AddSingleton<IHashService, HashService>();
|
services.AddSingleton<IHashService, HashService>();
|
||||||
services.AddSingleton<ICryptographyService, CryptographyService>();
|
services.AddSingleton<ICryptographyService, CryptographyService>();
|
||||||
|
services.AddSingleton<IJwtTokenGenerator, JwtTokenGenerator>();
|
||||||
|
services.AddSingleton<IQRCodeGenerator, QRCodeGenerator>();
|
||||||
|
services.AddSingleton<ITokenGenerator, TokenGenerator>();
|
||||||
|
services.AddSingleton<ITotpTokenGenerator, TotpTokenGenerator>();
|
||||||
|
services.AddSingleton<IDateTimeProvider, DateTimeProvider>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Time;
|
||||||
|
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Infrastructure.Core.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Class for generating JWT tokens.
|
||||||
|
/// </summary>
|
||||||
|
public class JwtTokenGenerator : IJwtTokenGenerator
|
||||||
|
{
|
||||||
|
private readonly IDateTimeProvider _dateTimeProvider;
|
||||||
|
private readonly JwtSettingsModel _jwtSettingsModel;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="JwtTokenGenerator"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="dateTimeProvider">Injected service for time related functionality.</param>
|
||||||
|
/// <param name="jwtSettingsModelOptions">Injected service for retrieving <see cref="JwtSettingsModel"/>.</param>
|
||||||
|
public JwtTokenGenerator(IDateTimeProvider dateTimeProvider, IOptions<JwtSettingsModel> jwtSettingsModelOptions)
|
||||||
|
{
|
||||||
|
_dateTimeProvider = dateTimeProvider;
|
||||||
|
_jwtSettingsModel = jwtSettingsModelOptions.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a new JWT token.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id">The id of the user for which to generate the token.</param>
|
||||||
|
/// <param name="username">The username of the user for which to generate the token.</param>
|
||||||
|
/// <returns>The generated JWT token.</returns>
|
||||||
|
public string GenerateToken(string id, string username)
|
||||||
|
{
|
||||||
|
// use a symmetric key approach
|
||||||
|
SigningCredentials signingCredentials = new(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettingsModel.SecretKey)), SecurityAlgorithms.HmacSha256);
|
||||||
|
Claim[] claims =
|
||||||
|
[
|
||||||
|
new Claim(JwtRegisteredClaimNames.Sub, id),
|
||||||
|
new Claim(JwtRegisteredClaimNames.UniqueName, username),
|
||||||
|
new Claim(JwtRegisteredClaimNames.Jti, id.ToString())
|
||||||
|
];
|
||||||
|
JwtSecurityToken securityToken = new(
|
||||||
|
issuer: _jwtSettingsModel.Issuer,
|
||||||
|
audience: _jwtSettingsModel.Audience,
|
||||||
|
expires: _dateTimeProvider.UtcNow.AddMinutes(_jwtSettingsModel.ExpiryMinutes),
|
||||||
|
claims: claims,
|
||||||
|
signingCredentials: signingCredentials);
|
||||||
|
return new JwtSecurityTokenHandler().WriteToken(securityToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
using OtpNet;
|
||||||
|
using QRCoder;
|
||||||
|
using System;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Infrastructure.Core.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Service for generating QR codes for TOTP.
|
||||||
|
/// </summary>
|
||||||
|
public class QRCodeGenerator : IQRCodeGenerator
|
||||||
|
{
|
||||||
|
private const string ISSUER = "Lumina";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a QR code Data URI for the specified TOTP secret.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="username">User's username or unique identifier.</param>
|
||||||
|
/// <param name="secret">The TOTP secret for which the QR code should be generated.</param>
|
||||||
|
/// <returns>Data URI for the QR code.</returns>
|
||||||
|
public string GenerateQrCodeDataUri(string username, byte[] secret)
|
||||||
|
{
|
||||||
|
// convert secret to Base32
|
||||||
|
string base32Secret = Base32Encoding.ToString(secret);
|
||||||
|
// build the otpauth URI
|
||||||
|
string otpauthString = $"otpauth://totp/{ISSUER}:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer={ISSUER}";
|
||||||
|
// generate QR Code
|
||||||
|
QRCoder.QRCodeGenerator qrGenerator = new();
|
||||||
|
QRCodeData qrData = qrGenerator.CreateQrCode(otpauthString, QRCoder.QRCodeGenerator.ECCLevel.Q);
|
||||||
|
PngByteQRCode qrCode = new(qrData);
|
||||||
|
// convert QR Code to Data URI
|
||||||
|
byte[] pngBytes = qrCode.GetGraphic(20); // specify a pixel size if needed
|
||||||
|
string dataUri = "data:image/png;base64," + Convert.ToBase64String(pngBytes);
|
||||||
|
return dataUri;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Infrastructure.Core.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Service for the service for generating secure tokens for accounts confirmation or recovery.
|
||||||
|
/// </summary>
|
||||||
|
public class TokenGenerator : ITokenGenerator
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a secure token.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A secure token.</returns>
|
||||||
|
public string GenerateToken()
|
||||||
|
{
|
||||||
|
// allocate an array for the token data
|
||||||
|
byte[] tokenData = new byte[32];
|
||||||
|
// fill the array with a cryptographically strong sequence of random values
|
||||||
|
RandomNumberGenerator.Fill(tokenData);
|
||||||
|
// convert to a Base64 string, but replace URL-unsafe characters '+' and '/' with '-' and '_', and remove padding characters ('=')
|
||||||
|
return Convert.ToBase64String(tokenData).Replace('+', '-').Replace('/', '_').TrimEnd('=');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
|
using OtpNet;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Infrastructure.Core.Authentication;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Service for generating and validating TOTP tokens.
|
||||||
|
/// </summary>
|
||||||
|
public class TotpTokenGenerator : ITotpTokenGenerator
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a new TOTP secret for a user.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>The generated TOTP secret.</returns>
|
||||||
|
public byte[] GenerateSecret()
|
||||||
|
{
|
||||||
|
return KeyGeneration.GenerateRandomKey(); // generate a random key for TOTP
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Validates a TOTP token against the stored secret.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="secret">The user's TOTP secret.</param>
|
||||||
|
/// <param name="token">The token to validate.</param>
|
||||||
|
/// <returns><see langword="true"/> if valid, <see langword="false"/> otherwise.</returns>
|
||||||
|
public bool ValidateToken(byte[] secret, string token)
|
||||||
|
{
|
||||||
|
Totp totp = new(secret);
|
||||||
|
// verify the TOTP token, allowing for slight time drifts between server and client
|
||||||
|
return totp.VerifyTotp(token, out _, VerificationWindow.RfcSpecifiedNetworkDelay);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Application.Common.Infrastructure;
|
using Lumina.Application.Common.Infrastructure.Security;
|
||||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using System;
|
using System;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Konscious.Security.Cryptography;
|
using Konscious.Security.Cryptography;
|
||||||
using Lumina.Application.Common.Infrastructure;
|
using Lumina.Application.Common.Infrastructure.Security;
|
||||||
using System;
|
using System;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.Infrastructure.Time;
|
||||||
|
using System;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Infrastructure.Core.Time;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Service for time related concerns
|
||||||
|
/// </summary>
|
||||||
|
public class DateTimeProvider : IDateTimeProvider
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The current UTC time.
|
||||||
|
/// </summary>
|
||||||
|
public DateTime UtcNow => DateTime.UtcNow;
|
||||||
|
}
|
||||||
@@ -20,6 +20,9 @@
|
|||||||
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
|
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
|
||||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
|
||||||
|
<PackageReference Include="Otp.NET" Version="1.4.0" />
|
||||||
|
<PackageReference Include="QRCoder" Version="1.6.0" />
|
||||||
|
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
+80
-1
@@ -1,9 +1,20 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using FastEndpoints;
|
using FastEndpoints;
|
||||||
using FastEndpoints.Swagger;
|
using FastEndpoints.Swagger;
|
||||||
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Http.Json;
|
using Microsoft.AspNetCore.Http.Json;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Infrastructure;
|
||||||
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using System;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using System.Threading.RateLimiting;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Presentation.Api.Common.DependencyInjection;
|
namespace Lumina.Presentation.Api.Common.DependencyInjection;
|
||||||
@@ -17,9 +28,12 @@ public static class PresentationApiLayerServices
|
|||||||
/// Registers the services of the Presentation API layer into the dependency injection container.
|
/// Registers the services of the Presentation API layer into the dependency injection container.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="services">The service collection to add the services to.</param>
|
/// <param name="services">The service collection to add the services to.</param>
|
||||||
|
/// <param name="configuration">Application configuration properties.</param>
|
||||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||||
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
|
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
|
services.AddMemoryCache(); // used for the tracking involved in authentication rate limiting
|
||||||
|
services.AddProblemDetails();
|
||||||
|
|
||||||
services.Configure<JsonOptions>(jsonOptions =>
|
services.Configure<JsonOptions>(jsonOptions =>
|
||||||
{
|
{
|
||||||
@@ -28,6 +42,71 @@ public static class PresentationApiLayerServices
|
|||||||
jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
|
jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
|
||||||
});
|
});
|
||||||
|
|
||||||
|
services.AddRateLimiter(options =>
|
||||||
|
{
|
||||||
|
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
|
options.OnRejected = async (context, cancellationToken) =>
|
||||||
|
{
|
||||||
|
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
|
context.HttpContext.Response.ContentType = "application/problem+json";
|
||||||
|
|
||||||
|
var problem = new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc7231#section-6.5.29",
|
||||||
|
title = "TooManyRequests", // TODO: implement translation?
|
||||||
|
status = StatusCodes.Status429TooManyRequests,
|
||||||
|
detail = "Too many attempts. Please try again later.",
|
||||||
|
retryAfter = "15"
|
||||||
|
};
|
||||||
|
|
||||||
|
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
|
||||||
|
};
|
||||||
|
options.AddFixedWindowLimiter("authenticationPolicy", config =>
|
||||||
|
{
|
||||||
|
config.PermitLimit = 10; // allow 10 attempts
|
||||||
|
config.Window = TimeSpan.FromMinutes(15); // within 15 minute window
|
||||||
|
config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
|
||||||
|
config.QueueLimit = 0; // don't queue requests
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// add authentication and specify the JWT scheme to check tokens against
|
||||||
|
services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
|
||||||
|
.AddJwtBearer(options =>
|
||||||
|
{
|
||||||
|
options.TokenValidationParameters = new TokenValidationParameters()
|
||||||
|
{
|
||||||
|
ValidateIssuer = true,
|
||||||
|
ValidateAudience = true,
|
||||||
|
ValidateLifetime = true,
|
||||||
|
ValidateIssuerSigningKey = true,
|
||||||
|
ValidIssuer = configuration["JwtSettings:Issuer"],
|
||||||
|
ValidAudience = configuration["JwtSettings:Audience"],
|
||||||
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]!)),
|
||||||
|
};
|
||||||
|
|
||||||
|
options.Events = new JwtBearerEvents
|
||||||
|
{
|
||||||
|
OnChallenge = context => // event triggered when authentication is not successful for whatever reason
|
||||||
|
{
|
||||||
|
context.HandleResponse(); // prevent the default 401 response
|
||||||
|
// set the response status code to 401 Unauthorized
|
||||||
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||||
|
context.Response.ContentType = "application/problem+json";
|
||||||
|
|
||||||
|
IProblemDetailsService problemDetailsService = context.HttpContext.RequestServices.GetRequiredService<IProblemDetailsService>();
|
||||||
|
return context.Response.WriteAsJsonAsync(new
|
||||||
|
{
|
||||||
|
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||||
|
status = StatusCodes.Status401Unauthorized,
|
||||||
|
title = "Unauthorized",
|
||||||
|
detail = "You are not authorized",
|
||||||
|
instance = context.HttpContext.Request.Path
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
services.AddAuthorization();
|
services.AddAuthorization();
|
||||||
|
|
||||||
services.AddFastEndpoints(
|
services.AddFastEndpoints(
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
|
||||||
namespace Lumina.Presentation.Api.Common.Http;
|
namespace Lumina.Presentation.Api.Common.Http;
|
||||||
#endregion
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Constants shared by HttpContext across a HTTP request (avoid magic strings).
|
/// Constants shared by HttpContext across a HTTP request (avoid magic strings).
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
|
namespace Lumina.Presentation.Api.Common.Routes.Maintenance;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Class for the collection of routes defined in this API.
|
/// Class for the collection of routes defined in this API.
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
namespace Lumina.Presentation.Api.Common.Routes.Maintenance;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Class for the collection of routes defined in this API.
|
||||||
|
/// </summary>
|
||||||
|
public static partial class ApiRoutes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Routes for the Initialization route.
|
||||||
|
/// </summary>
|
||||||
|
public static class Initialization
|
||||||
|
{
|
||||||
|
public const string SETUP_APPLICATION = "/initialization";
|
||||||
|
public const string CHECK_INITIALIZATION = "/initialization";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,5 +12,7 @@ public static partial class ApiRoutes
|
|||||||
{
|
{
|
||||||
public const string REGISTER_ACCOUNT = "/auth/register";
|
public const string REGISTER_ACCOUNT = "/auth/register";
|
||||||
public const string LOGIN_ACCOUNT = "/auth/login";
|
public const string LOGIN_ACCOUNT = "/auth/login";
|
||||||
|
public const string RECOVER_PASSWORD = "/auth/recover-password";
|
||||||
|
public const string CHANGE_PASSWORD = "/auth/change-password";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace Lumina.Presentation.Api.Common.Routes.UsersManagement;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Class for the collection of routes defined in this API.
|
||||||
|
/// </summary>
|
||||||
|
public static partial class ApiRoutes
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Routes for the Users route.
|
||||||
|
/// </summary>
|
||||||
|
public static class Users
|
||||||
|
{
|
||||||
|
public const string GET_USER_BY_ID = "/users/{id}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -46,10 +46,12 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
|
|||||||
Dictionary<string, object?> extensionsDictionary = [];
|
Dictionary<string, object?> extensionsDictionary = [];
|
||||||
int statusCode = error.Type switch
|
int statusCode = error.Type switch
|
||||||
{
|
{
|
||||||
ErrorType.Conflict => StatusCodes.Status409Conflict,
|
|
||||||
ErrorType.NotFound => StatusCodes.Status404NotFound,
|
|
||||||
ErrorType.Validation => StatusCodes.Status400BadRequest,
|
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.Failure => StatusCodes.Status403Forbidden,
|
||||||
|
ErrorType.Forbidden => StatusCodes.Status403Forbidden,
|
||||||
|
ErrorType.NotFound => StatusCodes.Status404NotFound,
|
||||||
|
ErrorType.Conflict => StatusCodes.Status409Conflict,
|
||||||
_ => StatusCodes.Status500InternalServerError,
|
_ => 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 a validation problem result with the constructed error details
|
||||||
return Results.ValidationProblem(
|
return Results.ValidationProblem(
|
||||||
errorsDictionary,
|
errorsDictionary,
|
||||||
detail: "One or more validation errors occurred.",
|
detail: "One or more validation errors occurred.", // TODO: implement translation?
|
||||||
instance: HttpContext.Request.Path,
|
instance: HttpContext.Request.Path,
|
||||||
statusCode: 422,
|
statusCode: 422,
|
||||||
title: "Validation Error",
|
title: "Validation Error",
|
||||||
|
|||||||
+52
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
+55
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
@@ -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.Contracts.Requests.FileSystemManagement.Directories;
|
||||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
|
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
|
||||||
using Lumina.Contracts.Responses.FileSystemManagement;
|
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 Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||||
using Mediator;
|
using Mediator;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|||||||
+54
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
@@ -1,13 +1,17 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using ErrorOr;
|
using ErrorOr;
|
||||||
using FastEndpoints;
|
using FastEndpoints;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
using Lumina.Application.Common.Mapping.Authentication;
|
using Lumina.Application.Common.Mapping.Authentication;
|
||||||
using Lumina.Contracts.Requests.Authentication;
|
using Lumina.Contracts.Requests.Authentication;
|
||||||
using Lumina.Contracts.Responses.Authentication;
|
using Lumina.Contracts.Responses.Authentication;
|
||||||
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
|
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
|
||||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||||
using Mediator;
|
using Mediator;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using System;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -40,6 +44,7 @@ public class LoginEndpoint : BaseEndpoint<LoginRequest, IResult>
|
|||||||
Version(1);
|
Version(1);
|
||||||
AllowAnonymous();
|
AllowAnonymous();
|
||||||
DontCatchExceptions();
|
DontCatchExceptions();
|
||||||
|
Options(x => x.RequireRateLimiting("authenticationPolicy"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
+28
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -12,10 +12,10 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register;
|
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// API endpoint for the <c>/account/register</c> route.
|
/// API endpoint for the <c>/auth/register</c> route.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
|
public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
|
||||||
{
|
{
|
||||||
@@ -36,7 +36,7 @@ public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
|
|||||||
public override void Configure()
|
public override void Configure()
|
||||||
{
|
{
|
||||||
Verbs(Http.POST);
|
Verbs(Http.POST);
|
||||||
Routes(ApiRoutes.Account.REGISTER_ACCOUNT);
|
Routes(ApiRoutes.Authentication.REGISTER_ACCOUNT);
|
||||||
Version(1);
|
Version(1);
|
||||||
AllowAnonymous();
|
AllowAnonymous();
|
||||||
DontCatchExceptions();
|
DontCatchExceptions();
|
||||||
+1
-1
@@ -3,7 +3,7 @@ using FastEndpoints;
|
|||||||
using Lumina.Contracts.Requests.Authentication;
|
using Lumina.Contracts.Requests.Authentication;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Register;
|
namespace Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.Register;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for Swagger.
|
/// Class used for providing a textual description for the <see cref="RegisterEndpoint"/> API endpoint, for Swagger.
|
||||||
@@ -25,6 +25,7 @@
|
|||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.8">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.8">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ public class Program
|
|||||||
builder.Services.BindSharedConfiguration(builder.Configuration);
|
builder.Services.BindSharedConfiguration(builder.Configuration);
|
||||||
builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration);
|
builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration);
|
||||||
|
|
||||||
builder.Services.AddPresentationApiLayerServices();
|
builder.Services.AddPresentationApiLayerServices(builder.Configuration);
|
||||||
builder.Services.AddApplicationLayerServices();
|
builder.Services.AddApplicationLayerServices();
|
||||||
builder.Services.AddInfrastructureLayerServices();
|
builder.Services.AddInfrastructureLayerServices();
|
||||||
builder.Services.AddDataAccessLayerServices();
|
builder.Services.AddDataAccessLayerServices();
|
||||||
@@ -94,6 +94,7 @@ public class Program
|
|||||||
//app.UseHttpsRedirection();
|
//app.UseHttpsRedirection();
|
||||||
|
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
app.UseRateLimiter();
|
||||||
|
|
||||||
app.UseFastEndpoints(config =>
|
app.UseFastEndpoints(config =>
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -17,16 +17,6 @@
|
|||||||
},
|
},
|
||||||
"dotnetRunMessages": true,
|
"dotnetRunMessages": true,
|
||||||
"applicationUrl": "https://localhost:7057;http://localhost:5214"
|
"applicationUrl": "https://localhost:7057;http://localhost:5214"
|
||||||
},
|
|
||||||
"Container (Dockerfile)": {
|
|
||||||
"commandName": "Docker",
|
|
||||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_HTTPS_PORTS": "7057",
|
|
||||||
"ASPNETCORE_HTTP_PORTS": "5214"
|
|
||||||
},
|
|
||||||
"publishAllPorts": true,
|
|
||||||
"useSSL": true
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"$schema": "http://json.schemastore.org/launchsettings.json"
|
"$schema": "http://json.schemastore.org/launchsettings.json"
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.Exceptions;
|
|||||||
using Lumina.Presentation.Web.Common.Models.Common;
|
using Lumina.Presentation.Web.Common.Models.Common;
|
||||||
using Lumina.Presentation.Web.Common.Models.Configuration;
|
using Lumina.Presentation.Web.Common.Models.Configuration;
|
||||||
using Lumina.Presentation.Web.Common.Models.FileSystemManagement;
|
using Lumina.Presentation.Web.Common.Models.FileSystemManagement;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -25,16 +26,19 @@ namespace Lumina.Presentation.Web.Common.Api;
|
|||||||
public class ApiHttpClient : IApiHttpClient
|
public class ApiHttpClient : IApiHttpClient
|
||||||
{
|
{
|
||||||
private readonly HttpClient _httpClient;
|
private readonly HttpClient _httpClient;
|
||||||
|
private readonly HttpContext? _httpContext;
|
||||||
private readonly JsonSerializerOptions _jsonOptions;
|
private readonly JsonSerializerOptions _jsonOptions;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="ApiHttpClient"/> class.
|
/// Initializes a new instance of the <see cref="ApiHttpClient"/> class.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="httpClient">Injected HttpClient for interacting with the API.</param>
|
/// <param name="httpClient">Injected HttpClient for interacting with the API.</param>
|
||||||
|
/// <param name="httpContextAccessor">Injected service for providing the current HTTP context.</param>
|
||||||
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
|
/// <param name="serverConfigurationOptions">Injected server configuration application settings.</param>
|
||||||
public ApiHttpClient(HttpClient httpClient, IOptionsSnapshot<ServerConfigurationModel> serverConfigurationOptions)
|
public ApiHttpClient(HttpClient httpClient, IHttpContextAccessor httpContextAccessor, IOptionsSnapshot<ServerConfigurationModel> serverConfigurationOptions)
|
||||||
{
|
{
|
||||||
_httpClient = httpClient;
|
_httpClient = httpClient;
|
||||||
|
_httpContext = httpContextAccessor.HttpContext;
|
||||||
// read the API server configuration values from the configuration, and assign them to the injected client
|
// read the API server configuration values from the configuration, and assign them to the injected client
|
||||||
ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value;
|
ServerConfigurationModel serverConfigurationModel = serverConfigurationOptions.Value;
|
||||||
httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/");
|
httpClient.BaseAddress = new Uri($"{serverConfigurationModel.BaseAddress}:{serverConfigurationModel.Port}/api/v{serverConfigurationModel.ApiVersion}/");
|
||||||
@@ -52,14 +56,14 @@ public class ApiHttpClient : IApiHttpClient
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>The deserialized response containing the result of the GET request.</returns>
|
/// <returns>The deserialized response containing the result of the GET request.</returns>
|
||||||
public async Task<TResponse> GetAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default)
|
public async Task<TResponse> GetAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
|
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
|
||||||
if (!string.IsNullOrEmpty(token))
|
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
|
||||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
if (authenticationHeader is not null)
|
||||||
|
request.Headers.Authorization = authenticationHeader;
|
||||||
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,14 +72,14 @@ public class ApiHttpClient : IApiHttpClient
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
|
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
|
||||||
public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, string? token = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
public async IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
|
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
|
||||||
if (!string.IsNullOrEmpty(token))
|
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
|
||||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
if (authenticationHeader is not null)
|
||||||
|
request.Headers.Authorization = authenticationHeader;
|
||||||
// send the request and expect only headers initially - this prevents the client from buffering the entire response
|
// send the request and expect only headers initially - this prevents the client from buffering the entire response
|
||||||
using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
using HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||||
response.EnsureSuccessStatusCode();
|
response.EnsureSuccessStatusCode();
|
||||||
@@ -93,14 +97,14 @@ public class ApiHttpClient : IApiHttpClient
|
|||||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>A model containing the deserialized blob.</returns>
|
/// <returns>A model containing the deserialized blob.</returns>
|
||||||
public async Task<BlobDataModel> GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default)
|
public async Task<BlobDataModel> GetBlobAsync(string endpoint, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
|
using HttpRequestMessage request = new(HttpMethod.Get, endpoint);
|
||||||
if (!string.IsNullOrEmpty(token))
|
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
|
||||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
if (authenticationHeader is not null)
|
||||||
|
request.Headers.Authorization = authenticationHeader;
|
||||||
using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
using HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
@@ -125,14 +129,14 @@ public class ApiHttpClient : IApiHttpClient
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>The deserialized response containing the result of the DELETE request.</returns>
|
/// <returns>The deserialized response containing the result of the DELETE request.</returns>
|
||||||
public async Task<TResponse> DeleteAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default)
|
public async Task<TResponse> DeleteAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
using HttpRequestMessage request = new(HttpMethod.Delete, endpoint);
|
using HttpRequestMessage request = new(HttpMethod.Delete, endpoint);
|
||||||
if (!string.IsNullOrEmpty(token))
|
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
|
||||||
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
if (authenticationHeader is not null)
|
||||||
|
request.Headers.Authorization = authenticationHeader;
|
||||||
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,14 +147,14 @@ public class ApiHttpClient : IApiHttpClient
|
|||||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="data">The data to be serialized and send to the API.</param>
|
/// <param name="data">The data to be serialized and send to the API.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||||
public async Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default)
|
public async Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
using HttpRequestMessage request = new(HttpMethod.Put, endpoint);
|
using HttpRequestMessage request = new(HttpMethod.Put, endpoint);
|
||||||
if (!string.IsNullOrEmpty(token))
|
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
|
||||||
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
if (authenticationHeader is not null)
|
||||||
|
request.Headers.Authorization = authenticationHeader;
|
||||||
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
|
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
|
||||||
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
@@ -162,14 +166,14 @@ public class ApiHttpClient : IApiHttpClient
|
|||||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||||
public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default)
|
public async Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
using HttpRequestMessage request = new(HttpMethod.Post, endpoint);
|
using HttpRequestMessage request = new(HttpMethod.Post, endpoint);
|
||||||
if (!string.IsNullOrEmpty(token))
|
AuthenticationHeaderValue? authenticationHeader = GetAuthenticationHeader();
|
||||||
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
if (authenticationHeader is not null)
|
||||||
|
request.Headers.Authorization = authenticationHeader;
|
||||||
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
|
request.Content = new StringContent(JsonSerializer.Serialize(data, _jsonOptions), Encoding.UTF8, "application/json");
|
||||||
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
return await SendRequestAsync<TResponse>(request, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
@@ -203,4 +207,16 @@ public class ApiHttpClient : IApiHttpClient
|
|||||||
throw new ApiException(problemDetails, response.StatusCode);
|
throw new ApiException(problemDetails, response.StatusCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Retrieves the authentication header for the current user, if available.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>
|
||||||
|
/// An <see cref="AuthenticationHeaderValue"/> with a Bearer token if the user's token is found, <see langword="null"/> otherwise.
|
||||||
|
/// </returns>
|
||||||
|
private AuthenticationHeaderValue? GetAuthenticationHeader()
|
||||||
|
{
|
||||||
|
string? token = _httpContext?.User?.FindFirst("Token")?.Value;
|
||||||
|
return !string.IsNullOrEmpty(token) ? new AuthenticationHeaderValue("Bearer", token) : null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Presentation.Web.Common.Models.FileSystemManagement;
|
using Lumina.Presentation.Web.Common.Models.FileSystemManagement;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -17,39 +17,35 @@ public interface IApiHttpClient
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>The deserialized response containing the result of the GET request.</returns>
|
/// <returns>The deserialized response containing the result of the GET request.</returns>
|
||||||
Task<TResponse> GetAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default);
|
Task<TResponse> GetAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result as a streamable response.
|
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result as a streamable response.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
|
/// <returns>An <see cref="IAsyncEnumerable{T}"/> object, which allows for asynchronous iteration over the deserialized items.</returns>
|
||||||
IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default);
|
IAsyncEnumerable<TResponse?> GetAsyncEnumerable<TResponse>(string endpoint, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
/// Sends a GET request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>A model containing the deserialized blob.</returns>
|
/// <returns>A model containing the deserialized blob.</returns>
|
||||||
Task<BlobDataModel> GetBlobAsync(string endpoint, string? token = null, CancellationToken cancellationToken = default);
|
Task<BlobDataModel> GetBlobAsync(string endpoint, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
/// Sends a DELETE request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
/// <typeparam name="TResponse">The expected type of the response content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>The deserialized response containing the result of the DELETE request.</returns>
|
/// <returns>The deserialized response containing the result of the DELETE request.</returns>
|
||||||
Task<TResponse> DeleteAsync<TResponse>(string endpoint, string? token = null, CancellationToken cancellationToken = default);
|
Task<TResponse> DeleteAsync<TResponse>(string endpoint, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
/// Sends a PUT request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||||
@@ -58,10 +54,9 @@ public interface IApiHttpClient
|
|||||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="data">The data to be serialized and send to the API.</param>
|
/// <param name="data">The data to be serialized and send to the API.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
/// <returns>The deserialized response containing the result of the PUT request.</returns>
|
||||||
Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default);
|
Task<TResponse> PutAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
/// Sends a POST request to the specified <paramref name="endpoint"/> as an asynchronous operation and returns the result.
|
||||||
@@ -70,8 +65,7 @@ public interface IApiHttpClient
|
|||||||
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
/// <typeparam name="TModel">The expected type of the payload content.</typeparam>
|
||||||
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
/// <param name="endpoint">The API endpoint where the request is being sent.</param>
|
||||||
/// <param name="data">The data to be serialized and sent to the API.</param>
|
/// <param name="data">The data to be serialized and sent to the API.</param>
|
||||||
/// <param name="token">The token used for authentication with the API.</param>
|
|
||||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||||
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
/// <returns>The deserialized response containing the result of the POST request.</returns>
|
||||||
Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, string? token = null, CancellationToken cancellationToken = default);
|
Task<TResponse> PostAsync<TResponse, TModel>(string endpoint, TModel data, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Presentation.Web.Common.Api;
|
||||||
|
using Lumina.Presentation.Web.Common.Http;
|
||||||
|
using Lumina.Presentation.Web.Common.Models.UsersManagement;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Common.Authorization;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles the <see cref="InitializationRequirement"/> to ensure that the application is initialized before allowing authorization.
|
||||||
|
/// </summary>
|
||||||
|
public class InitializationHandler : AuthorizationHandler<InitializationRequirement>
|
||||||
|
{
|
||||||
|
private readonly IApiHttpClient _apiHttpClient;
|
||||||
|
private readonly IMemoryCache _cache;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="InitializationHandler"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="apiHttpClient">Injected HTTP typed client for interactions with the API.</param>
|
||||||
|
/// <param name="cache">Cache for storing the initialization status.</param>
|
||||||
|
public InitializationHandler(IApiHttpClient apiHttpClient, IMemoryCache cache)
|
||||||
|
{
|
||||||
|
_apiHttpClient = apiHttpClient;
|
||||||
|
_cache = cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks the application initialization status and authorizes the requirement if initialized.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context">The authorization context.</param>
|
||||||
|
/// <param name="requirement">The initialization requirement to be evaluated.</param>
|
||||||
|
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, InitializationRequirement requirement)
|
||||||
|
{
|
||||||
|
InitializationModel result = await _apiHttpClient.GetAsync<InitializationModel>("initialization/");
|
||||||
|
HttpContext? httpContext = context.Resource as HttpContext;
|
||||||
|
if (result.IsInitialized)
|
||||||
|
{
|
||||||
|
// admin account was registered, remove this requirement from the session
|
||||||
|
httpContext?.Session.Remove(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
|
||||||
|
context.Succeed(requirement);
|
||||||
|
}
|
||||||
|
else // store in session that super admin setup is needed
|
||||||
|
httpContext?.Session.SetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, "true");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Common.Authorization;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Defines a requirement for initialization status in the authorization process.
|
||||||
|
/// </summary>
|
||||||
|
public class InitializationRequirement : IAuthorizationRequirement
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the timeout duration, in minutes, for caching the initialization check.
|
||||||
|
/// </summary>
|
||||||
|
public int CacheTimeoutMinutes { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="InitializationRequirement"/> class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cacheTimeoutMinutes">The cache timeout in minutes for the initialization status.</param>
|
||||||
|
public InitializationRequirement(int cacheTimeoutMinutes = 5)
|
||||||
|
{
|
||||||
|
CacheTimeoutMinutes = cacheTimeoutMinutes;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,7 +31,7 @@ public class ApiExceptionFilter : IExceptionFilter
|
|||||||
if (context.Exception is ApiException apiException)
|
if (context.Exception is ApiException apiException)
|
||||||
{
|
{
|
||||||
// handle unauthorized errors by prompting the user to re-login
|
// handle unauthorized errors by prompting the user to re-login
|
||||||
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized)
|
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
|
||||||
{
|
{
|
||||||
SignOutSynchronously(context.HttpContext);
|
SignOutSynchronously(context.HttpContext);
|
||||||
string currentUrl = context.HttpContext.Request.GetDisplayUrl();
|
string currentUrl = context.HttpContext.Request.GetDisplayUrl();
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Common.Filters;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attribute that enforces application initialization checks on controller actions.
|
||||||
|
/// </summary>
|
||||||
|
public class InitializationCheckAttribute : ActionFilterAttribute
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Asynchronously executes the initialization check before the action executes.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context">The context for the action being executed.</param>
|
||||||
|
/// <param name="next">Delegate to execute the next action filter in the pipeline.</param>
|
||||||
|
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||||
|
{
|
||||||
|
IAuthorizationService authorizationService = context.HttpContext.RequestServices.GetRequiredService<IAuthorizationService>();
|
||||||
|
await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization");
|
||||||
|
await next();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace Lumina.Presentation.Web.Common.Http;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Constants shared by HttpContext across a HTTP request (avoid magic strings).
|
||||||
|
/// </summary>
|
||||||
|
public static class HttpContextItemKeys
|
||||||
|
{
|
||||||
|
public const string ERRORS = "errors";
|
||||||
|
public const string PENDING_SUPER_ADMIN_SETUP = "PendingSuperAdminSetup";
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
namespace Lumina.Presentation.Web.Common.Models.MediaContributors;
|
namespace Lumina.Presentation.Web.Common.Models.MediaContributors;
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
|
||||||
using System.Diagnostics;
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
namespace Lumina.Presentation.Web.Common.Models.UI;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Represents an item in a combobox.
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="TValue">The type used for the <see cref="Value"/> property of the item.</typeparam>
|
|
||||||
[DebuggerDisplay("{Text}")]
|
|
||||||
public class ComboboxItem<TValue>
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the text of the item, that is visible to the user.
|
|
||||||
/// </summary>
|
|
||||||
public string? Text { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the value of the item, that is used by the application.
|
|
||||||
/// </summary>
|
|
||||||
public TValue? Value { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the property indicating whether this element can be selected or not.
|
|
||||||
/// </summary>
|
|
||||||
public bool IsEnabled { get; set; } = true;
|
|
||||||
}
|
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the request model for account password change.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Username">The username of the account.</param>
|
||||||
|
/// <param name="CurrentPassword">The current password of the account.</param>
|
||||||
|
/// <param name="NewPassword">The new password of the account.</param>
|
||||||
|
/// <param name="NewPasswordConfirm">The confirmation of the new password of the account.</param>
|
||||||
|
public record ChangePasswordRequestModel(
|
||||||
|
string? Username,
|
||||||
|
string? CurrentPassword,
|
||||||
|
string? NewPassword,
|
||||||
|
string? NewPasswordConfirm
|
||||||
|
);
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the response model for an account password change request.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="IsPasswordChanged">Whether the password was changed or not.</param>
|
||||||
|
[DebuggerDisplay("IsPasswordChanged: {IsPasswordChanged}")]
|
||||||
|
public record ChangePasswordResponseModel(
|
||||||
|
bool IsPasswordChanged
|
||||||
|
);
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Model for verifying the initialization status of the application.
|
||||||
|
/// </summary>
|
||||||
|
[DebuggerDisplay("IsInitialized: {IsInitialized}")]
|
||||||
|
public class InitializationModel
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether the application has been run before, and the super admin account has been created.
|
||||||
|
/// </summary>
|
||||||
|
public bool IsInitialized { get; set; }
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the request model for account password recovery.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Username">The username of the account for which to recover the password.</param>
|
||||||
|
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) code used to recover the password.</param>
|
||||||
|
[DebuggerDisplay("Username: {Username}")]
|
||||||
|
public record RecoverPasswordRequestModel(
|
||||||
|
string? Username,
|
||||||
|
string? TotpCode
|
||||||
|
);
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using System.Diagnostics;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the response model for an account password reset request.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="IsPasswordReset">Whether the password was reset or not.</param>
|
||||||
|
[DebuggerDisplay("IsPasswordReset: {IsPasswordReset}")]
|
||||||
|
public record RecoverPasswordResponseModel(
|
||||||
|
bool IsPasswordReset
|
||||||
|
);
|
||||||
@@ -14,9 +14,9 @@ namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
|
|||||||
/// <param name="Use2fa">Indicates whether two-factor authentication (2FA) should be enabled for the new account.</param>
|
/// <param name="Use2fa">Indicates whether two-factor authentication (2FA) should be enabled for the new account.</param>
|
||||||
[DebuggerDisplay("Username: {Username}")]
|
[DebuggerDisplay("Username: {Username}")]
|
||||||
public record RegisterRequestModel(
|
public record RegisterRequestModel(
|
||||||
string? Username = null,
|
string? Username,
|
||||||
string? Password = null,
|
string? Password,
|
||||||
string? PasswordConfirm = null,
|
string? PasswordConfirm,
|
||||||
string? RegistrationType = null,
|
string? RegistrationType,
|
||||||
bool Use2fa = true
|
bool Use2fa = true
|
||||||
);
|
);
|
||||||
-100
@@ -1,100 +0,0 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
|
||||||
using Lumina.Presentation.Web.Common.Enums.BookLibrary;
|
|
||||||
using Lumina.Presentation.Web.Common.Models.MediaContributors;
|
|
||||||
using Lumina.Presentation.Web.Common.Models.WrittenContentLibrary;
|
|
||||||
using Lumina.Presentation.Web.Common.Models.WrittenContentLibrary.BookLibrary;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
namespace Lumina.Presentation.Web.Common.Requests.WrittenContentLibrary.BookLibrary;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Represents a request to add a book.
|
|
||||||
/// </summary>
|
|
||||||
public class AddBookRequest
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the written content metadata of the book.
|
|
||||||
/// </summary>
|
|
||||||
public WrittenContentMetadataModel? Metadata { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the format of the book (e.g., Hardcover, Paperback), if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public BookFormat? Format { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the edition of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? Edition { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the volume or book number in the series, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public int? VolumeNumber { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the series name, if the book is part of a series.
|
|
||||||
/// </summary>
|
|
||||||
public BookSeriesModel? Series { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the ASIN (Amazon Standard Identification Number) of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? ASIN { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the Goodreads ID of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? GoodreadsId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the Library of Congress Control Number (LCCN) of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? LCCN { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the OCLC Number (WorldCat identifier) of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? OCLCNumber { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the Open Library ID of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? OpenLibraryId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the LibraryThing ID of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? LibraryThingId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the Google Books ID of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? GoogleBooksId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the Barnes & Noble ID of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? BarnesAndNobleId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the Apple Books ID of the book, if applicable.
|
|
||||||
/// </summary>
|
|
||||||
public string? AppleBooksId { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the list of ISBN (International Standard Book Number) of the book.
|
|
||||||
/// </summary>
|
|
||||||
public List<IsbnModel>? ISBNs { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the list of media contributors (actors, directors, etc) starring in this book.
|
|
||||||
/// </summary>
|
|
||||||
public List<MediaContributorModel>? Contributors { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets the list of ratings for this book.
|
|
||||||
/// </summary>
|
|
||||||
public List<BookRatingModel>? Ratings { get; set; }
|
|
||||||
}
|
|
||||||
@@ -51,7 +51,7 @@ public class AuthController : Controller
|
|||||||
// check if this is the initial super admin setup
|
// check if this is the initial super admin setup
|
||||||
string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
|
string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
|
||||||
ViewData["RegistrationType"] = isPendingSuperAdminSetup == "true" ? "Admin" : "User";
|
ViewData["RegistrationType"] = isPendingSuperAdminSetup == "true" ? "Admin" : "User";
|
||||||
return View(new RegisterRequestModel());
|
return View();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -91,10 +91,18 @@ public class AuthController : Controller
|
|||||||
return View();
|
return View();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Displays the view for changing the password of an account.
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("change-password")]
|
||||||
|
public IActionResult ChangePassword()
|
||||||
|
{
|
||||||
|
return View();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Displays the view for registering a new account.
|
/// Displays the view for registering a new account.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[InitializationCheck]
|
|
||||||
[HttpGet("profile")]
|
[HttpGet("profile")]
|
||||||
public IActionResult Profile()
|
public IActionResult Profile()
|
||||||
{
|
{
|
||||||
@@ -118,7 +126,7 @@ public class AuthController : Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Logs in an new account.
|
/// Logs in an account.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="data">User credentials used for login.</param>
|
/// <param name="data">User credentials used for login.</param>
|
||||||
/// <param name="returnUrl">The url to return to, after login (if any).</param>
|
/// <param name="returnUrl">The url to return to, after login (if any).</param>
|
||||||
@@ -167,4 +175,44 @@ public class AuthController : Controller
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Logs out an account and redirects to the login page.
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("logout")]
|
||||||
|
public async Task<IActionResult> Logout()
|
||||||
|
{
|
||||||
|
// if the user is not logged in, redirect them to the home page
|
||||||
|
if (User?.Identity?.IsAuthenticated == false)
|
||||||
|
return RedirectToAction("Index", "Home");
|
||||||
|
Response.Cookies.Delete("Token");
|
||||||
|
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||||
|
return RedirectToAction("Login", "Auth");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Recovers the password of an account.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="data">User credentials used for password recovery.</param>
|
||||||
|
[AllowAnonymous]
|
||||||
|
[ValidateAntiForgeryToken]
|
||||||
|
[HttpPost("recover-password")]
|
||||||
|
public async Task<IActionResult> RecoverPassword([FromBody] RecoverPasswordRequestModel data)
|
||||||
|
{
|
||||||
|
RecoverPasswordResponseModel response = await _apiHttpClient.PostAsync<RecoverPasswordResponseModel, RecoverPasswordRequestModel>("auth/recover-password", data);
|
||||||
|
return Json(new { success = true, data = response });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Changes the password of an account.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="data">User credentials used for password change.</param>
|
||||||
|
[ValidateAntiForgeryToken]
|
||||||
|
[HttpPost("change-password")]
|
||||||
|
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequestModel data)
|
||||||
|
{
|
||||||
|
data = data with { Username = User?.Identity?.Name }; // assign the currently logged in user as the user for which to change the password
|
||||||
|
ChangePasswordResponseModel response = await _apiHttpClient.PostAsync<ChangePasswordResponseModel, ChangePasswordRequestModel>("auth/change-password", data);
|
||||||
|
return Json(new { success = true, data = response });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,31 +1,21 @@
|
|||||||
{
|
{
|
||||||
"profiles": {
|
"profiles": {
|
||||||
"http": {
|
"http": {
|
||||||
"commandName": "Project",
|
"commandName": "Project",
|
||||||
"environmentVariables": {
|
"environmentVariables": {
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
},
|
},
|
||||||
"dotnetRunMessages": true,
|
"dotnetRunMessages": true,
|
||||||
"applicationUrl": "http://localhost:5012"
|
"applicationUrl": "http://localhost:5012"
|
||||||
|
},
|
||||||
|
"https": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
},
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"applicationUrl": "http://localhost:5012;https://localhost:7112"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"https": {
|
"$schema": "http://json.schemastore.org/launchsettings.json"
|
||||||
"commandName": "Project",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
|
||||||
},
|
|
||||||
"dotnetRunMessages": true,
|
|
||||||
"applicationUrl": "http://localhost:5012;https://localhost:7112"
|
|
||||||
},
|
|
||||||
"Container (Dockerfile)": {
|
|
||||||
"commandName": "Docker",
|
|
||||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_HTTPS_PORTS": "8081",
|
|
||||||
"ASPNETCORE_HTTP_PORTS": "8080"
|
|
||||||
},
|
|
||||||
"publishAllPorts": true,
|
|
||||||
"useSSL": true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"$schema": "http://json.schemastore.org/launchsettings.json"
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
@*
|
||||||
|
/auth/change-password/
|
||||||
|
*@
|
||||||
|
|
||||||
|
@using Lumina.Presentation.Web.Common.Models.UsersManagement
|
||||||
|
@using Lumina.Presentation.Web.Common.Services
|
||||||
|
|
||||||
|
@inject IUrlService _urlService
|
||||||
|
|
||||||
|
@model ChangePasswordRequestModel
|
||||||
|
|
||||||
|
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
|
||||||
|
<div class="shine-effect"></div>
|
||||||
|
<form asp-controller="Auth" asp-action="ChangePassword" method="post" id="change-password-form" class="inline">
|
||||||
|
@Html.AntiForgeryToken()
|
||||||
|
<input type="text" name="username" autocomplete="username" value="@User.Identity!.Name" hidden />
|
||||||
|
<div class="form-container">
|
||||||
|
<!-- Current Password -->
|
||||||
|
<div class="form-row" id="div-current-password">
|
||||||
|
<div class="form-label">
|
||||||
|
<label asp-for="CurrentPassword">Current Password</label>
|
||||||
|
<span class="mandatory-field">*</span>:
|
||||||
|
</div>
|
||||||
|
<div class="form-field">
|
||||||
|
<input type="password" asp-for="CurrentPassword" autocomplete="new-password" class="enlightenment-input" />
|
||||||
|
</div>
|
||||||
|
<small class="form-label text-disabled form-description">DescriptionCurrentPassword</small>
|
||||||
|
</div>
|
||||||
|
<!-- New Password -->
|
||||||
|
<div class="form-row" id="div-new-password">
|
||||||
|
<div class="form-label">
|
||||||
|
<label asp-for="NewPassword">New Password</label>
|
||||||
|
<span class="mandatory-field">*</span>:
|
||||||
|
</div>
|
||||||
|
<div class="form-field">
|
||||||
|
<input type="password" asp-for="NewPassword" autocomplete="new-password" class="enlightenment-input" />
|
||||||
|
</div>
|
||||||
|
<small class="form-label text-disabled form-description">DescriptionNewPassword</small>
|
||||||
|
</div>
|
||||||
|
<!-- New Password Confirm-->
|
||||||
|
<div class="form-row" id="div-new-password-confirm">
|
||||||
|
<div class="form-label">
|
||||||
|
<label asp-for="NewPasswordConfirm">New Password Confirm</label>
|
||||||
|
<span class="mandatory-field">*</span>:
|
||||||
|
</div>
|
||||||
|
<div class="form-field">
|
||||||
|
<input type="password" asp-for="NewPasswordConfirm" autocomplete="new-password" class="enlightenment-input" />
|
||||||
|
</div>
|
||||||
|
<small class="form-label text-disabled form-description">DescriptionNewPasswordConfirm</small>
|
||||||
|
</div>
|
||||||
|
<div class="form-row" id="div-change-password-submit" style="justify-content: center;">
|
||||||
|
<button type="submit" class="confirm-button h-22px w-150px">Change Password</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<!-- section registration success -->
|
||||||
|
<div class="text-center w-100">
|
||||||
|
<p id="change-password-success" class="text-light-one w-100 hidden">Password Changed</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@section Scripts {
|
||||||
|
<script type="text/javascript" defer>
|
||||||
|
document.getElementById('change-password-form').addEventListener('submit', async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const form = event.target;
|
||||||
|
const txtCurrentPassword = form.querySelector('[name="CurrentPassword"]');
|
||||||
|
const txtNewPassword = form.querySelector('[name="NewPassword"]');
|
||||||
|
const txtNewPasswordConfirm = form.querySelector('[name="NewPasswordConfirm"]');
|
||||||
|
|
||||||
|
const changePasswordSuccess = document.getElementById('change-password-success');
|
||||||
|
const divCurrentPassword = document.getElementById('div-current-password');
|
||||||
|
const divNewPassword = document.getElementById('div-new-password');
|
||||||
|
const divNewPasswordConfirm = document.getElementById('div-new-password-confirm');
|
||||||
|
const divChangePasswordSubmit = document.getElementById('div-change-password-submit');
|
||||||
|
|
||||||
|
const formData = {
|
||||||
|
CurrentPassword: txtCurrentPassword.value,
|
||||||
|
NewPassword: txtNewPassword.value,
|
||||||
|
NewPasswordConfirm: txtNewPasswordConfirm.value
|
||||||
|
};
|
||||||
|
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")', formData);
|
||||||
|
if (data && data.isPasswordChanged === true) {
|
||||||
|
changePasswordSuccess.classList.replace('hidden', 'block');
|
||||||
|
divCurrentPassword.classList.add('hidden');
|
||||||
|
divNewPassword.classList.add('hidden');
|
||||||
|
divNewPasswordConfirm.classList.add('hidden');
|
||||||
|
divChangePasswordSubmit.classList.add('hidden');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
}
|
||||||
@@ -34,11 +34,11 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<button id="btnRecoverPassword" type="button" class="abort-button h-22px w-150px" data-link="@Url.Action("RecoverPassword", "Auth")">Recover Password</button>
|
<button id="btn-recover-password" type="button" class="abort-button h-22px w-150px" data-link="@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")">Recover Password</button>
|
||||||
<button id="btnLogin" type="submit" class="confirm-button h-22px w-100px">Login</button>
|
<button id="btn-login" type="submit" class="confirm-button h-22px w-100px">Login</button>
|
||||||
</div>
|
</div>
|
||||||
<!-- 2FA -->
|
<!-- 2FA -->
|
||||||
<div class="form-row mt-10 hidden" id="divTotpCode">
|
<div class="form-row mt-10 hidden" id="div-totp-code">
|
||||||
<div class="form-label">
|
<div class="form-label">
|
||||||
<label asp-for="TotpCode">Totp Code</label>
|
<label asp-for="TotpCode">Totp Code</label>
|
||||||
</div>
|
</div>
|
||||||
@@ -47,7 +47,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<button type="submit" id="btnValidateTotp" class="confirm-button h-22px w-100px hidden">Validate Code</button>
|
<button type="submit" id="btn-validate-totp" class="confirm-button h-22px w-100px hidden">Validate Code</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
@@ -60,17 +60,17 @@
|
|||||||
const txtUsername = form.querySelector('[name="Username"]');
|
const txtUsername = form.querySelector('[name="Username"]');
|
||||||
const txtPassword = form.querySelector('[name="Password"]');
|
const txtPassword = form.querySelector('[name="Password"]');
|
||||||
const txtTotpCode = form.querySelector('[name="TotpCode"]');
|
const txtTotpCode = form.querySelector('[name="TotpCode"]');
|
||||||
const divTotpCode = document.getElementById('divTotpCode');
|
const divTotpCode = document.getElementById('div-totp-code');
|
||||||
const btnLogin = document.getElementById('btnLogin');
|
const btnLogin = document.getElementById('btn-login');
|
||||||
const btnRecoverPassword = document.getElementById('btnRecoverPassword');
|
const btnRecoverPassword = document.getElementById('btn-recover-password');
|
||||||
const btnValidateTotp = document.getElementById('btnValidateTotp');
|
const btnValidateTotp = document.getElementById('btn-validate-totp');
|
||||||
const formData = {
|
const formData = {
|
||||||
Username: txtUsername.value,
|
Username: txtUsername.value,
|
||||||
Password: txtPassword.value,
|
Password: txtPassword.value,
|
||||||
TotpCode: txtTotpCode.value
|
TotpCode: txtTotpCode.value
|
||||||
};
|
};
|
||||||
const data = await callApiPostAsync('/auth/login', formData);
|
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("Login", "Auth")', formData);
|
||||||
if (data && data.isTotpRequired) {
|
if (data && data.isTotpRequired === true) {
|
||||||
txtUsername.disabled = true;
|
txtUsername.disabled = true;
|
||||||
txtPassword.disabled = true;
|
txtPassword.disabled = true;
|
||||||
btnLogin.disabled = true;
|
btnLogin.disabled = true;
|
||||||
@@ -82,7 +82,7 @@
|
|||||||
else if (data)
|
else if (data)
|
||||||
window.location.href = data;
|
window.location.href = data;
|
||||||
});
|
});
|
||||||
document.getElementById('btnRecoverPassword').addEventListener('click', () => {
|
document.getElementById('btn-recover-password').addEventListener('click', () => {
|
||||||
window.location.href = '@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")';
|
window.location.href = '@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")';
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
@*
|
||||||
|
/auth/recover-password/
|
||||||
|
*@
|
||||||
|
|
||||||
|
@using Lumina.Presentation.Web.Common.Models.UsersManagement
|
||||||
|
@using Lumina.Presentation.Web.Common.Services
|
||||||
|
|
||||||
|
@inject IUrlService _urlService
|
||||||
|
|
||||||
|
@model RecoverPasswordRequestModel
|
||||||
|
|
||||||
|
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
|
||||||
|
<div class="shine-effect"></div>
|
||||||
|
<form asp-controller="Auth" asp-action="RecoverPassword" method="post" id="recover-password-form" class="inline">
|
||||||
|
@Html.AntiForgeryToken()
|
||||||
|
<div class="form-container">
|
||||||
|
<!-- Username -->
|
||||||
|
<div class="form-row" id="div-username">
|
||||||
|
<div class="form-label">
|
||||||
|
<label asp-for="Username">Username</label>
|
||||||
|
<span class="mandatory-field">*</span>:
|
||||||
|
</div>
|
||||||
|
<div class="form-field">
|
||||||
|
<input asp-for="Username" autocomplete="username" class="enlightenment-input" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- 2FA -->
|
||||||
|
<div class="form-row" id="div-totp-code">
|
||||||
|
<div class="form-label">
|
||||||
|
<label asp-for="TotpCode">Totp Code</label>
|
||||||
|
<span class="mandatory-field">*</span>:
|
||||||
|
</div>
|
||||||
|
<div class="form-field">
|
||||||
|
<input type="number" asp-for="TotpCode" autocomplete="one-time-code" class="enlightenment-input" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<button id="btn-login" type="button" class="abort-button h-22px w-100px">Back To Login</button>
|
||||||
|
<button type="submit" id="btn-validate-totp" class="confirm-button h-22px w-100px">Validate Code</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<!-- section registration success -->
|
||||||
|
<div class="text-center w-100">
|
||||||
|
<p id="recover-password-success" class="text-light-one w-100 hidden">Password Temporarily Reset</p>
|
||||||
|
<button id="btn-redirect-login" type="submit" class="confirm-button h-22px w-80px hidden" data-link="@_urlService.GetAbsoluteUrl("Login", "Auth")">Login</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@section Scripts {
|
||||||
|
<script type="text/javascript" defer>
|
||||||
|
document.getElementById('recover-password-form').addEventListener('submit', async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const form = event.target;
|
||||||
|
const txtUsername = form.querySelector('[name="Username"]');
|
||||||
|
const txtTotpCode = form.querySelector('[name="TotpCode"]');
|
||||||
|
const recoverPasswordSuccess = document.getElementById('recover-password-success');
|
||||||
|
const btnRedirectLogin = document.getElementById('btn-redirect-login');
|
||||||
|
const btnLogin = document.getElementById('btn-login');
|
||||||
|
const btnValidateTotp = document.getElementById('btn-validate-totp');
|
||||||
|
const divUsername = document.getElementById('div-username');
|
||||||
|
const divTotpCode = document.getElementById('div-totp-code');
|
||||||
|
|
||||||
|
const formData = {
|
||||||
|
Username: txtUsername.value,
|
||||||
|
TotpCode: txtTotpCode.value
|
||||||
|
};
|
||||||
|
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")', formData);
|
||||||
|
if (data && data.isPasswordReset === true) {
|
||||||
|
divUsername.classList.add('hidden');
|
||||||
|
btnValidateTotp.classList.add('hidden');
|
||||||
|
btnLogin.classList.add('hidden');
|
||||||
|
divTotpCode.classList.add('hidden');
|
||||||
|
btnRedirectLogin.classList.replace('hidden', 'inline');
|
||||||
|
recoverPasswordSuccess.classList.replace('hidden', 'block');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.getElementById('btn-login').addEventListener('click', () => {
|
||||||
|
window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")';
|
||||||
|
});
|
||||||
|
document.getElementById('btn-redirect-login').addEventListener('click', () => {
|
||||||
|
window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")';
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
}
|
||||||
+19
-16
@@ -1,18 +1,21 @@
|
|||||||
@*
|
@*
|
||||||
/account/register/
|
/auth/register/
|
||||||
*@
|
*@
|
||||||
|
|
||||||
@using Lumina.Presentation.Web.Common.Models.UsersManagement
|
@using Lumina.Presentation.Web.Common.Models.UsersManagement
|
||||||
|
@using Lumina.Presentation.Web.Common.Services
|
||||||
|
|
||||||
@{
|
@{
|
||||||
string? registrationType = ViewData["RegistrationType"] as string;
|
string? registrationType = ViewData["RegistrationType"] as string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@inject IUrlService _urlService
|
||||||
|
|
||||||
@model RegisterRequestModel
|
@model RegisterRequestModel
|
||||||
|
|
||||||
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
|
<div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-50 mb-10" style="min-width: 320px; margin-top: 1rem;">
|
||||||
<div class="shine-effect"></div>
|
<div class="shine-effect"></div>
|
||||||
<form asp-controller="Account" asp-action="Register" method="post" id="register-account-form" class="inline">
|
<form asp-controller="Auth" asp-action="Register" method="post" id="register-account-form" class="inline">
|
||||||
@Html.AntiForgeryToken()
|
@Html.AntiForgeryToken()
|
||||||
<!-- section for determining registration type (regular user/admin) -->
|
<!-- section for determining registration type (regular user/admin) -->
|
||||||
<input type="hidden" name="RegistrationType" value="@registrationType" />
|
<input type="hidden" name="RegistrationType" value="@registrationType" />
|
||||||
@@ -57,7 +60,7 @@
|
|||||||
<small class="form-label text-disabled form-description">DescriptionPasswordConfirm</small>
|
<small class="form-label text-disabled form-description">DescriptionPasswordConfirm</small>
|
||||||
</div>
|
</div>
|
||||||
<!-- 2FA -->
|
<!-- 2FA -->
|
||||||
<input type="hidden" id="hiddenUseTwoFa" name="use2fa" value="true">
|
<input type="hidden" id="hidden-use-two-fa" name="use2fa" value="true">
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-field">
|
<div class="form-field">
|
||||||
<label class="enlightenment-checkbox-label">
|
<label class="enlightenment-checkbox-label">
|
||||||
@@ -69,7 +72,7 @@
|
|||||||
<small class="form-label text-disabled form-description">Description2Fa</small>
|
<small class="form-label text-disabled form-description">Description2Fa</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<span id="register2FaAttention" class="invalid-feedback w-95 text-center hidden">Password recovery is allowed only if two factor authentication is enabled!</span>
|
<span id="register-two-fa-attention" class="invalid-feedback w-95 text-center hidden">Password recovery is allowed only if two factor authentication is enabled!</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-row" style="justify-content: center;">
|
<div class="form-row" style="justify-content: center;">
|
||||||
<button type="submit" class="confirm-button h-22px w-100px">Register</button>
|
<button type="submit" class="confirm-button h-22px w-100px">Register</button>
|
||||||
@@ -78,10 +81,10 @@
|
|||||||
</form>
|
</form>
|
||||||
<!-- section registration success -->
|
<!-- section registration success -->
|
||||||
<div class="text-center w-100">
|
<div class="text-center w-100">
|
||||||
<p id="registerSuccess" class="text-light-one w-100 hidden">Account Created</p>
|
<p id="register-success" class="text-light-one w-100 hidden">Account Created</p>
|
||||||
<img id="totpImage" class="w-200px h-200px h-align-m mx-auto mt-10 hidden" />
|
<img id="totp-image" class="w-200px h-200px h-align-m mx-auto mt-10 hidden" />
|
||||||
<p id="totpMessage" class="text-light-one w-100 hidden">Scan Totp Code</p>
|
<p id="totp-message" class="text-light-one w-100 hidden">Scan Totp Code</p>
|
||||||
<a id="redirectButton" asp-controller="Account" asp-action="Login" class="confirm-button f-14 pt-0 pb-0 h-22px w-80px mt-10 mb-10 mx-auto hidden">Login</a>
|
<button id="btn-login" type="button" class="confirm-button h-22px w-80px hidden" data-link="@_urlService.GetAbsoluteUrl("Login", "Auth")">Login</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@section Scripts {
|
@section Scripts {
|
||||||
@@ -93,10 +96,10 @@
|
|||||||
const txtPassword = form.querySelector('[name="Password"]');
|
const txtPassword = form.querySelector('[name="Password"]');
|
||||||
const txtPasswordConfirm = form.querySelector('[name="PasswordConfirm"]');
|
const txtPasswordConfirm = form.querySelector('[name="PasswordConfirm"]');
|
||||||
const chkUse2FA = form.querySelector('[name="Use2fa"]');
|
const chkUse2FA = form.querySelector('[name="Use2fa"]');
|
||||||
const registerSuccess = document.getElementById('registerSuccess');
|
const registerSuccess = document.getElementById('register-success');
|
||||||
const redirectButton = document.getElementById('redirectButton');
|
const btnLogin = document.getElementById('btn-login');
|
||||||
const totpMessage = document.querySelector('#totpMessage');
|
const totpMessage = document.querySelector('#totp-message');
|
||||||
const totpImage = document.querySelector('#totpImage');
|
const totpImage = document.querySelector('#totp-image');
|
||||||
const formData = {
|
const formData = {
|
||||||
Username: txtUsername.value,
|
Username: txtUsername.value,
|
||||||
Password: txtPassword.value,
|
Password: txtPassword.value,
|
||||||
@@ -104,14 +107,14 @@
|
|||||||
Use2fa: chkUse2FA.checked,
|
Use2fa: chkUse2FA.checked,
|
||||||
RegistrationType: form.querySelector('[name="RegistrationType"]').value
|
RegistrationType: form.querySelector('[name="RegistrationType"]').value
|
||||||
};
|
};
|
||||||
const data = await callApiPostAsync('/account/register', formData);
|
const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("Register", "Auth")', formData);
|
||||||
if (data) {
|
if (data) {
|
||||||
txtUsername.value = '';
|
txtUsername.value = '';
|
||||||
txtPassword.value = '';
|
txtPassword.value = '';
|
||||||
txtPasswordConfirm.value = '';
|
txtPasswordConfirm.value = '';
|
||||||
form.classList.replace('inline', 'hidden');
|
form.classList.replace('inline', 'hidden');
|
||||||
registerSuccess.classList.replace('hidden', 'inline');
|
registerSuccess.classList.replace('hidden', 'inline');
|
||||||
redirectButton.classList.replace('hidden', 'block');
|
btnLogin.classList.replace('hidden', 'block');
|
||||||
if (chkUse2FA.checked) {
|
if (chkUse2FA.checked) {
|
||||||
totpMessage.classList.remove('hidden');
|
totpMessage.classList.remove('hidden');
|
||||||
totpMessage.classList.add('block');
|
totpMessage.classList.add('block');
|
||||||
@@ -124,11 +127,11 @@
|
|||||||
});
|
});
|
||||||
document.querySelector('[name="Use2fa"]').addEventListener('change', function () {
|
document.querySelector('[name="Use2fa"]').addEventListener('change', function () {
|
||||||
const isChecked = this.checked;
|
const isChecked = this.checked;
|
||||||
document.querySelector('#register2FaAttention').classList.replace(
|
document.getElementById('#register-two-fa-attention').classList.replace(
|
||||||
isChecked ? 'inline' : 'hidden',
|
isChecked ? 'inline' : 'hidden',
|
||||||
isChecked ? 'hidden' : 'inline'
|
isChecked ? 'hidden' : 'inline'
|
||||||
);
|
);
|
||||||
document.querySelector('#hiddenUseTwoFa').value = isChecked.toString();
|
document.getElementById('#hidden-use-two-fa').value = isChecked.toString();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,6 @@
|
|||||||
@using Lumina.Presentation.Web.Common.Enums.Notifications
|
@using Lumina.Presentation.Web.Common.Enums.Notifications
|
||||||
@using Lumina.Presentation.Web.Common.Exceptions
|
@using Lumina.Presentation.Web.Common.Exceptions
|
||||||
@using Lumina.Presentation.Web.Common.Models.FileSystemManagement
|
@using Lumina.Presentation.Web.Common.Models.FileSystemManagement
|
||||||
@using Lumina.Presentation.Web.Common.Models.UI
|
|
||||||
@using Microsoft.AspNetCore.Components
|
@using Microsoft.AspNetCore.Components
|
||||||
@using System.Text.Json
|
@using System.Text.Json
|
||||||
@using System.Text
|
@using System.Text
|
||||||
|
|||||||
@@ -1,31 +1,34 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>@ViewData["Title"] - Lumina</title>
|
<title>@ViewData["Title"] - Lumina</title>
|
||||||
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/button.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/button.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/checkbox.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/checkbox.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/combobox.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/combobox.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/file-system-browser.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/file-system-browser.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/file-system-tree-view-node.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/file-system-tree-view-node.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/navigation-menu.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/navigation-menu.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/notification.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/notification.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/css/textbox.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/css/textbox.css" asp-append-version="true" />
|
||||||
<link rel="stylesheet" href="~/Lumina.Presentation.Web.styles.css" asp-append-version="true" />
|
<link rel="stylesheet" href="~/Lumina.Presentation.Web.styles.css" asp-append-version="true" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="page">
|
<div id="page">
|
||||||
<header>
|
<header>
|
||||||
@await Html.PartialAsync("_NavMenu")
|
@await Html.PartialAsync("_NavMenu")
|
||||||
</header>
|
</header>
|
||||||
<main role="main">
|
<main role="main" style="@(User?.Identity?.IsAuthenticated == false ? "bottom: 0px;" : string.Empty)">
|
||||||
<article>
|
<article>
|
||||||
@RenderBody()
|
@RenderBody()
|
||||||
<div id="modal-background-article"></div>
|
<div id="modal-background-article"></div>
|
||||||
</article>
|
</article>
|
||||||
</main>
|
</main>
|
||||||
|
@if (User?.Identity?.IsAuthenticated == true)
|
||||||
|
|
||||||
|
{
|
||||||
<!--Audio player-->
|
<!--Audio player-->
|
||||||
<div class="audio-player-container">
|
<div class="audio-player-container">
|
||||||
<video controls
|
<video controls
|
||||||
@@ -33,15 +36,16 @@
|
|||||||
height="50" width="600">
|
height="50" width="600">
|
||||||
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
|
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
|
||||||
</video>
|
</video>
|
||||||
<a id="audio-player-full-height-toggle">Toggle Full Height</a>
|
<a id="audio-player-full-height-toggle">Toggle Full Height</a>
|
||||||
<a id="audio-player-close">Toggle Visibility</a>
|
<a id="audio-player-close">Toggle Visibility</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
}
|
||||||
<!--Modal grid background-->
|
</div>
|
||||||
<div id="modal-background-menu"></div>
|
<!--Modal grid background-->
|
||||||
|
<div id="modal-background-menu"></div>
|
||||||
|
|
||||||
<script defer src="~/js/notifications.js" asp-append-version="true"></script>
|
<script defer src="~/js/notifications.js" asp-append-version="true"></script>
|
||||||
<script defer src="~/js/site.js" asp-append-version="true"></script>
|
<script defer src="~/js/site.js" asp-append-version="true"></script>
|
||||||
@await RenderSectionAsync("Scripts", required: false)
|
@await RenderSectionAsync("Scripts", required: false)
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
@using Lumina.Presentation.Web.Common.Services
|
||||||
|
|
||||||
|
@inject IUrlService _urlService
|
||||||
|
|
||||||
<input type="checkbox" id="hamburger-input" class="burger-shower" />
|
<input type="checkbox" id="hamburger-input" class="burger-shower" />
|
||||||
<label id="hamburger-menu" for="hamburger-input">
|
<label id="hamburger-menu" for="hamburger-input">
|
||||||
<span></span>
|
<span></span>
|
||||||
@@ -9,45 +13,59 @@
|
|||||||
Account
|
Account
|
||||||
</div>
|
</div>
|
||||||
<ul>
|
<ul>
|
||||||
<li><a href="account/login"><span>Login</span></a></li>
|
@if (User?.Identity?.IsAuthenticated == false)
|
||||||
<li><a href="account/logout"><span>Logout</span></a></li>
|
{
|
||||||
<li><a href="account/register"><span>Register</span></a></li>
|
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Login</span></a></li>
|
||||||
<li><a href="account"><span>My Account</span></a></li>
|
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Recover Password</span></a></li>
|
||||||
</ul>
|
}
|
||||||
<div class="mobile-menu-heading">
|
else
|
||||||
Tools
|
{
|
||||||
</div>
|
<li><a href="@_urlService.GetAbsoluteUrl("Logout", "Auth")"><span>Logout</span></a></li>
|
||||||
<ul>
|
}
|
||||||
<li><a href="tools/options"><span>Options</span></a></li>
|
@if (User?.Identity?.IsAuthenticated == true)
|
||||||
</ul>
|
{
|
||||||
<div class="mobile-menu-heading">
|
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Register</span></a></li>
|
||||||
Library
|
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Change Password</span></a></li>
|
||||||
</div>
|
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")"><span>Profile</span></a></li>
|
||||||
<ul>
|
}
|
||||||
<li><a href="library/manage"><span>Manage libraries</span></a></li>
|
|
||||||
<li><a href="library/manage/item"><span>Add media library</span></a></li>
|
|
||||||
</ul>
|
|
||||||
<div class="mobile-menu-heading">
|
|
||||||
Written Content
|
|
||||||
</div>
|
|
||||||
<ul>
|
|
||||||
<li><a href="library/written-content-library/books-library/books" class="nav-link"><span>Books</span></a></li>
|
|
||||||
<li><a href="library/written-content/magazines"><span>Magazines</span></a></li>
|
|
||||||
</ul>
|
|
||||||
<div class="mobile-menu-heading">
|
|
||||||
Audio
|
|
||||||
</div>
|
|
||||||
<ul>
|
|
||||||
<li><a href="library/audio/music"><span>Music</span></a></li>
|
|
||||||
<li><a href="library/audio/interviews"><span>Interviews</span></a></li>
|
|
||||||
</ul>
|
|
||||||
<div class="mobile-menu-heading">
|
|
||||||
Video
|
|
||||||
</div>
|
|
||||||
<ul>
|
|
||||||
<li><a href="library/video/movies"><span>Movies</span></a></li>
|
|
||||||
<li><a href="library/video/tvshows"><span>TV Shows</span></a></li>
|
|
||||||
</ul>
|
</ul>
|
||||||
|
@if (User?.Identity?.IsAuthenticated == true)
|
||||||
|
{
|
||||||
|
<div class="mobile-menu-heading">
|
||||||
|
Tools
|
||||||
|
</div>
|
||||||
|
<ul>
|
||||||
|
<li><a href="tools/options"><span>Options</span></a></li>
|
||||||
|
</ul>
|
||||||
|
<div class="mobile-menu-heading">
|
||||||
|
Library
|
||||||
|
</div>
|
||||||
|
<ul>
|
||||||
|
<li><a href="library/manage"><span>Manage libraries</span></a></li>
|
||||||
|
<li><a href="library/manage/item"><span>Add media library</span></a></li>
|
||||||
|
</ul>
|
||||||
|
<div class="mobile-menu-heading">
|
||||||
|
Written Content
|
||||||
|
</div>
|
||||||
|
<ul>
|
||||||
|
<li><a href="library/written-content-library/books-library/books" class="nav-link"><span>Books</span></a></li>
|
||||||
|
<li><a href="library/written-content/magazines"><span>Magazines</span></a></li>
|
||||||
|
</ul>
|
||||||
|
<div class="mobile-menu-heading">
|
||||||
|
Audio
|
||||||
|
</div>
|
||||||
|
<ul>
|
||||||
|
<li><a href="library/audio/music"><span>Music</span></a></li>
|
||||||
|
<li><a href="library/audio/interviews"><span>Interviews</span></a></li>
|
||||||
|
</ul>
|
||||||
|
<div class="mobile-menu-heading">
|
||||||
|
Video
|
||||||
|
</div>
|
||||||
|
<ul>
|
||||||
|
<li><a href="library/video/movies"><span>Movies</span></a></li>
|
||||||
|
<li><a href="library/video/tvshows"><span>TV Shows</span></a></li>
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
<div class="mobile-menu-heading">
|
<div class="mobile-menu-heading">
|
||||||
Help
|
Help
|
||||||
</div>
|
</div>
|
||||||
@@ -64,48 +82,62 @@
|
|||||||
<input type="radio" id="account-menu" name="menu">
|
<input type="radio" id="account-menu" name="menu">
|
||||||
<label for="account-menu">Account</label>
|
<label for="account-menu">Account</label>
|
||||||
<ul>
|
<ul>
|
||||||
<li><a href="account/login">Login</a></li>
|
@if (User?.Identity?.IsAuthenticated == false)
|
||||||
<li><a href="account/logout">Logout</a></li>
|
{
|
||||||
<li><a href="account/register">Register</a></li>
|
<li><a href="@_urlService.GetAbsoluteUrl("Login", "Auth")">Login</a></li>
|
||||||
<li><a href="account">My Account</a></li>
|
<li><a href="@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")">Recover Password</a></li>
|
||||||
</ul>
|
}
|
||||||
</li>
|
else
|
||||||
<li tabindex="0">
|
{
|
||||||
<input type="radio" id="tools-menu" name="menu">
|
<li><a href="@_urlService.GetAbsoluteUrl("Logout", "Auth")">Logout</a></li>
|
||||||
<label for="tools-menu">Tools</label>
|
}
|
||||||
<ul>
|
@if (User?.Identity?.IsAuthenticated == true)
|
||||||
<li><a href="tools/options">Options</a></li>
|
{
|
||||||
</ul>
|
<li><a href="@_urlService.GetAbsoluteUrl("Register", "Auth")">Register</a></li>
|
||||||
</li>
|
<li><a href="@_urlService.GetAbsoluteUrl("ChangePassword", "Auth")">Change Password</a></li>
|
||||||
<li tabindex="0">
|
<li><a href="@_urlService.GetAbsoluteUrl("Profile", "Auth")">Profile</a></li>
|
||||||
<input type="radio" id="library-menu" name="menu">
|
}
|
||||||
<label for="library-menu">Library</label>
|
|
||||||
<ul>
|
|
||||||
<li tabindex="0"><a href="library/manage">Manage libraries</a></li>
|
|
||||||
<li tabindex="0"><a href="library/manage/item">Add new library</a></li>
|
|
||||||
<li class="has-submenu" tabindex="0">
|
|
||||||
<label>Written Content</label>
|
|
||||||
<ul>
|
|
||||||
<li><a href="library/written-content-library/books-library/books" class="nav-link">Books</a></li>
|
|
||||||
<li><a href="library/written-content/magazines">Magazines</a></li>
|
|
||||||
</ul>
|
|
||||||
</li>
|
|
||||||
<li class="has-submenu" tabindex="0">
|
|
||||||
<label>Audio</label>
|
|
||||||
<ul>
|
|
||||||
<li><a href="library/audio/music">Music</a></li>
|
|
||||||
<li><a href="library/audio/interviews">Interviews</a></li>
|
|
||||||
</ul>
|
|
||||||
</li>
|
|
||||||
<li class="has-submenu" tabindex="0">
|
|
||||||
<label>Video</label>
|
|
||||||
<ul>
|
|
||||||
<li><a href="library/video/movies">Movies</a></li>
|
|
||||||
<li><a href="library/video/tvshows">TV Shows</a></li>
|
|
||||||
</ul>
|
|
||||||
</li>
|
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
|
@if (User?.Identity?.IsAuthenticated == true)
|
||||||
|
{
|
||||||
|
<li tabindex="0">
|
||||||
|
<input type="radio" id="tools-menu" name="menu">
|
||||||
|
<label for="tools-menu">Tools</label>
|
||||||
|
<ul>
|
||||||
|
<li><a href="tools/options">Options</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li tabindex="0">
|
||||||
|
<input type="radio" id="library-menu" name="menu">
|
||||||
|
<label for="library-menu">Library</label>
|
||||||
|
<ul>
|
||||||
|
<li tabindex="0"><a href="library/manage">Manage libraries</a></li>
|
||||||
|
<li tabindex="0"><a href="library/manage/item">Add new library</a></li>
|
||||||
|
<li class="has-submenu" tabindex="0">
|
||||||
|
<label>Written Content</label>
|
||||||
|
<ul>
|
||||||
|
<li><a href="library/written-content-library/books-library/books" class="nav-link">Books</a></li>
|
||||||
|
<li><a href="library/written-content/magazines">Magazines</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="has-submenu" tabindex="0">
|
||||||
|
<label>Audio</label>
|
||||||
|
<ul>
|
||||||
|
<li><a href="library/audio/music">Music</a></li>
|
||||||
|
<li><a href="library/audio/interviews">Interviews</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li class="has-submenu" tabindex="0">
|
||||||
|
<label>Video</label>
|
||||||
|
<ul>
|
||||||
|
<li><a href="library/video/movies">Movies</a></li>
|
||||||
|
<li><a href="library/video/tvshows">TV Shows</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
<li tabindex="0">
|
<li tabindex="0">
|
||||||
<input type="radio" id="help-menu" name="menu">
|
<input type="radio" id="help-menu" name="menu">
|
||||||
<label for="help-menu">Help</label>
|
<label for="help-menu">Help</label>
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ async function callApiGetAsync(url) {
|
|||||||
try {
|
try {
|
||||||
// create the URL for the API endpoint
|
// create the URL for the API endpoint
|
||||||
const response = await fetch(url); // call the API
|
const response = await fetch(url); // call the API
|
||||||
|
if (response.redirected) // if a redirect is requested, perform it
|
||||||
|
window.location.href = response.url;
|
||||||
if (!response.ok)
|
if (!response.ok)
|
||||||
throw new Error('Network response was not ok');
|
throw new Error('Network response was not ok');
|
||||||
const jsonResponse = await response.json();
|
const jsonResponse = await response.json();
|
||||||
@@ -63,7 +65,7 @@ async function callApiPostAsync(url, data, options = {}) {
|
|||||||
if (finalOptions.useAntiForgery) {
|
if (finalOptions.useAntiForgery) {
|
||||||
const token = document.querySelector('input[name="__RequestVerificationToken"]')?.value;
|
const token = document.querySelector('input[name="__RequestVerificationToken"]')?.value;
|
||||||
if (token)
|
if (token)
|
||||||
headers['X-CSRF-TOKEN'] = token;
|
headers['RequestVerificationToken'] = token;
|
||||||
}
|
}
|
||||||
// make the request
|
// make the request
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
@@ -71,6 +73,8 @@ async function callApiPostAsync(url, data, options = {}) {
|
|||||||
headers: headers,
|
headers: headers,
|
||||||
body: JSON.stringify(data)
|
body: JSON.stringify(data)
|
||||||
});
|
});
|
||||||
|
if (response.redirected) // if a redirect is requested, perform it
|
||||||
|
window.location.href = response.url;
|
||||||
if (!response.ok)
|
if (!response.ok)
|
||||||
throw new Error(`HTTP error! status: ${response.status}`);
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
const jsonResponse = await response.json();
|
const jsonResponse = await response.json();
|
||||||
@@ -196,7 +200,7 @@ async function updateContent(url, addToHistory) {
|
|||||||
*/
|
*/
|
||||||
function showBusyIndicator() {
|
function showBusyIndicator() {
|
||||||
//if (ajaxCallCounter === 0)
|
//if (ajaxCallCounter === 0)
|
||||||
//progressIndicator.classList.remove('hidden');
|
//progressIndicator.classList.remove('hidden');
|
||||||
ajaxCallCounter++;
|
ajaxCallCounter++;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,7 +210,7 @@ function showBusyIndicator() {
|
|||||||
function hideBusyIndicator() {
|
function hideBusyIndicator() {
|
||||||
ajaxCallCounter--;
|
ajaxCallCounter--;
|
||||||
//if (ajaxCallCounter === 0)
|
//if (ajaxCallCounter === 0)
|
||||||
//progressIndicator.classList.add('hidden');
|
//progressIndicator.classList.add('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -413,8 +417,10 @@ function toggleAudioPlayerFullHeight() {
|
|||||||
contentContainer.classList.toggle('audio-player-full-height');
|
contentContainer.classList.toggle('audio-player-full-height');
|
||||||
}
|
}
|
||||||
|
|
||||||
audioPlayerFullHeightToggle.addEventListener('click', toggleAudioPlayerFullHeight);
|
if (audioPlayerFullHeightToggle)
|
||||||
audioPlayerClose.addEventListener('click', toggleAudioPlayerVisibility);
|
audioPlayerFullHeightToggle.addEventListener('click', toggleAudioPlayerFullHeight);
|
||||||
|
if (audioPlayerClose)
|
||||||
|
audioPlayerClose.addEventListener('click', toggleAudioPlayerVisibility);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Bogus;
|
||||||
|
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.Fixtures;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fixture class for the <see cref="SetupApplicationCommand"/> class.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class SetupApplicationCommandFixture
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a random valid command for the application setup.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>The created command.</returns>
|
||||||
|
public static SetupApplicationCommand CreateSetupApplicationCommand()
|
||||||
|
{
|
||||||
|
string password = "Abcd123$";
|
||||||
|
return new Faker<SetupApplicationCommand>()
|
||||||
|
.CustomInstantiator(f => new SetupApplicationCommand(
|
||||||
|
default!,
|
||||||
|
default!,
|
||||||
|
default!,
|
||||||
|
true
|
||||||
|
))
|
||||||
|
.RuleFor(x => x.Username, f => f.Person.UserName)
|
||||||
|
.RuleFor(x => x.Password, password)
|
||||||
|
.RuleFor(x => x.PasswordConfirm, password);
|
||||||
|
}
|
||||||
|
}
|
||||||
+233
@@ -0,0 +1,233 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using FluentValidation.TestHelper;
|
||||||
|
using Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
|
||||||
|
using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands;
|
||||||
|
using Lumina.Application.UnitTests.Core.FileSystemManagement.Pahs.Commands.CombinePath.Fixtures;
|
||||||
|
using Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands.Fixtures;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.UnitTests.Core.Maintenance.ApplicationSetup.Commands;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains unit tests for the <see cref="SetupApplicationCommandValidator"/> class.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class SetupApplicationCommandValidatorTests
|
||||||
|
{
|
||||||
|
private readonly SetupApplicationCommandValidator _validator;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="SetupApplicationCommandValidatorTests"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public SetupApplicationCommandValidatorTests()
|
||||||
|
{
|
||||||
|
_validator = new SetupApplicationCommandValidator();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenUsernameIsNull_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Username = null! };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||||
|
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenUsernameIsEmpty_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Username = string.Empty };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||||
|
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenUsernameIsWhiteSpace_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Username = " " };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.Username)
|
||||||
|
.WithErrorMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenPasswordIsNull_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Password = null! };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||||
|
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenPasswordIsEmpty_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Password = string.Empty };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||||
|
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenPasswordIsWhiteSpace_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Password = " " };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||||
|
.WithErrorMessage(Errors.Authentication.PasswordCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenPasswordConfirmIsNull_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { PasswordConfirm = null! };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
|
||||||
|
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenPasswordConfirmIsEmpty_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { PasswordConfirm = string.Empty };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
|
||||||
|
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenPasswordConfirmIsWhiteSpace_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { PasswordConfirm = " " };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.PasswordConfirm)
|
||||||
|
.WithErrorMessage(Errors.Authentication.PasswordConfirmCannotBeEmpty.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenPasswordAndPasswordConfirmDontMatch_ShouldHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { PasswordConfirm = "$321Bcda" };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||||
|
.WithErrorMessage(Errors.Authentication.PasswordsNotMatch.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("password123")] // Missing uppercase and special character
|
||||||
|
[InlineData("PASSWORD123")] // Missing special character
|
||||||
|
[InlineData("Password123")] // Missing special character
|
||||||
|
[InlineData("Password!@#")] // Missing number
|
||||||
|
[InlineData("Pass1!")] // Too short
|
||||||
|
[InlineData("password")] // Missing uppercase, number, and special character
|
||||||
|
public void Validate_WhenPasswordDoesNotMatchPattern_ShouldHaveValidationError(string password)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Password = password, PasswordConfirm = password };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldHaveValidationErrorFor(x => x.Password)
|
||||||
|
.WithErrorMessage(Errors.Authentication.InvalidPassword.Description);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Password1!")] // Valid password
|
||||||
|
[InlineData("Complex1@Password")] // Valid password
|
||||||
|
[InlineData("MyP@ssw0rd")] // Valid password
|
||||||
|
[InlineData("Abcd123!@#")] // Valid password
|
||||||
|
public void Validate_WhenPasswordMatchesPattern_ShouldNotHaveValidationError(string password)
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Password = password, PasswordConfirm = password };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldNotHaveValidationErrorFor(x => x.Password);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
SetupApplicationCommand command = SetupApplicationCommandFixture.CreateSetupApplicationCommand();
|
||||||
|
command = command with { Password = "$321Bcda", PasswordConfirm = "$321Bcda" };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
TestValidationResult<SetupApplicationCommand> result = _validator.TestValidate(command);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.ShouldNotHaveValidationErrorFor(x => x.Username);
|
||||||
|
result.ShouldNotHaveValidationErrorFor(x => x.Password);
|
||||||
|
result.ShouldNotHaveValidationErrorFor(x => x.PasswordConfirm);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user