Implements account login

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

No files matched your search

@@ -17,7 +17,7 @@ public class UserEntity : IStorageEntity
/// <summary>
/// Gets the Id of the user.
/// </summary>
public required Guid Id { get; init; }
public Guid Id { get; init; }
/// <summary>
/// Gets or sets the username of the user.
@@ -1,7 +1,10 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Users;
@@ -10,6 +13,14 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Users;
/// Interface for the repository for users.
/// </summary>
public interface IUserRepository : IRepository<UserEntity>,
IGetAllRepositoryAction<UserEntity>,
IInsertRepositoryAction<UserEntity>
{
/// <summary>
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
/// </summary>
/// <param name="username">The username of the user to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="UserEntity"/> if found, or an error.</returns>
Task<ErrorOr<UserEntity?>> GetByUsernameAsync(string username, CancellationToken cancellationToken);
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
#endregion
namespace Lumina.Application.Common.Errors;
/// <summary>
/// Application authentication related error types.
/// </summary>
public static partial class Errors
{
public static class Authentication
{
public static Error UsernameAlreadyExists => Error.Conflict(description: nameof(UsernameAlreadyExists));
public static Error UsernameCannotBeEmpty => Error.Validation(description: nameof(UsernameCannotBeEmpty));
public static Error PasswordCannotBeEmpty => Error.Validation(description: nameof(PasswordCannotBeEmpty));
public static Error PasswordConfirmCannotBeEmpty => Error.Validation(description: nameof(PasswordConfirmCannotBeEmpty));
public static Error InvalidPassword => Error.Validation(description: nameof(InvalidPassword));
public static Error PasswordsNotMatch => Error.Validation(description: nameof(PasswordsNotMatch));
public static Error InvalidTotpCode => Error.Validation(description: nameof(InvalidTotpCode));
public static Error InvalidUsernameOrPassword => Error.Failure(description: nameof(InvalidUsernameOrPassword));
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
using Lumina.Contracts.Requests.Authentication;
#endregion
namespace Lumina.Application.Common.Mapping.Authentication;
/// <summary>
/// Extension methods for converting <see cref="LoginRequest"/>.
/// </summary>
public static class LoginRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="LoginUserQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static LoginUserQuery ToQuery(this LoginRequest request)
{
return new LoginUserQuery(
request.Username,
request.Password,
request.TotpCode
);
}
}
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
/// <summary>
/// Query for authenticating an account.
/// </summary>
/// <param name="Username">The username of the account to authenticate.</param>
/// <param name="Password">The password of the account to authenticate.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account to authenticate.</param>
[DebuggerDisplay("Path: {Path}")]
public record LoginUserQuery(
string? Username,
string? Password,
string? TotpCode = null
) : IRequest<ErrorOr<LoginResponse>>;
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Contracts.Responses.Authentication;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
/// <summary>
/// Handler for the query to authenticate an account.
/// </summary>
public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<LoginResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IHashService _hashService;
private readonly IJwtTokenGenerator _jwtTokenGenerator;
private readonly ITotpTokenGenerator _totpTokenGenerator;
private readonly ICryptographyService _cryptographyService;
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="hashService">Injected service for password hashing functionality.</param>
/// <param name="jwtTokenGenerator">Injected service for generating JWT tokens.</param>
/// <param name="totpTokenGenerator">Injected service for generating and validating TOTP tokens.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
public LoginUserQueryHandler(
IUnitOfWork unitOfWork,
IHashService hashService,
IJwtTokenGenerator jwtTokenGenerator,
ITotpTokenGenerator totpTokenGenerator,
ICryptographyService cryptographyService)
{
_unitOfWork = unitOfWork;
_hashService = hashService;
_jwtTokenGenerator = jwtTokenGenerator;
_totpTokenGenerator = totpTokenGenerator;
_cryptographyService = cryptographyService;
}
/// <summary>
/// Handles the query to authenticate an account.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LoginResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LoginResponse>> Handle(LoginUserQuery request, CancellationToken cancellationToken)
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
return Errors.Authentication.InvalidUsernameOrPassword;
// validate the password is correct
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
return Errors.Authentication.InvalidUsernameOrPassword;
// create the JWT token
string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username);
// check if the user uses TOTP
bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret);
if (usesTotp && string.IsNullOrEmpty(request.TotpCode))
return Errors.Authentication.InvalidTotpCode;
else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode))
return Errors.Authentication.InvalidTotpCode;
return new LoginResponse(resultSelectUser.Value.Id, resultSelectUser.Value.Username, token, usesTotp);
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Errors;
using System.Linq;
#endregion
namespace Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser;
/// <summary>
/// Validates the needed validation rules for <see cref="LoginUserQuery"/>.
/// </summary>
public class LoginUserQueryValidator : AbstractValidator<LoginUserQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="LoginUserQueryValidator"/> class.
/// </summary>
public LoginUserQueryValidator()
{
RuleFor(x => x.Username).NotEmpty().WithMessage(Errors.Authentication.UsernameCannotBeEmpty.Description);
RuleFor(x => x.Password).NotEmpty().WithMessage(Errors.Authentication.PasswordCannotBeEmpty.Description)
.Matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$").WithMessage(Errors.Authentication.InvalidPassword.Description);
RuleFor(m => m!.TotpCode)
.Custom((code, context) =>
{
if (string.IsNullOrEmpty(code))
return;
if (code.Length != 6)
context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description);
if (!code.All(char.IsDigit))
context.AddFailure("TotpCode", Errors.Authentication.InvalidTotpCode.Description);
});
}
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.Authentication;
/// <summary>
/// Represents the request model for user authentication.
/// </summary>
/// <param name="Username">The username of the account to authenticate.</param>
/// <param name="Password">The password of the account to authenticate.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) of the account to authenticate.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginRequest(
string? Username,
string? Password,
string? TotpCode = null
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.Authentication;
/// <summary>
/// Represents the response model for user authentication.
/// </summary>
/// <param name="Id">The Id of the user to authenticate.</param>
/// <param name="Username">The username of the user to authenticate.</param>
/// <param name="Token">The authentication token used for subsequent requests.</param>
/// <param name="UsesTotp">Whether the user uses 2FA authentication, or not.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginResponse(
Guid Id,
string Username,
string Token,
bool UsesTotp
);
@@ -7,6 +7,7 @@ using Lumina.Domain.Common.Errors;
using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Users;
@@ -43,4 +44,24 @@ internal sealed class UserRepository : IUserRepository
return Result.Created;
}
/// <summary>
/// Gets all users.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="UserEntity"/>, or an error.</returns>
public async Task<ErrorOr<IEnumerable<UserEntity>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Users.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a username identified by <paramref name="username"/> from the repository, if it exists.
/// </summary>
/// <param name="username">The username of the user to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="UserEntity"/> if found, or an error.</returns>
public async Task<ErrorOr<UserEntity?>> GetByUsernameAsync(string username, CancellationToken cancellationToken)
{
return await _luminaDbContext.Users.FirstOrDefaultAsync(user => user.Username == username, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,16 @@
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 Authentication route.
/// </summary>
public static class Authentication
{
public const string REGISTER_ACCOUNT = "/auth/register";
public const string LOGIN_ACCOUNT = "/auth/login";
}
}
@@ -0,0 +1,55 @@
#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.Login;
/// <summary>
/// API endpoint for the <c>/auth/login</c> route.
/// </summary>
public class LoginEndpoint : BaseEndpoint<LoginRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="LoginEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public LoginEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Authentication.LOGIN_ACCOUNT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Authenticates an account.
/// </summary>
/// <param name="request">The request containing the account to be authenticated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(LoginRequest request, CancellationToken cancellationToken)
{
ErrorOr<LoginResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -1,7 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Models.Configuration;
using Lumina.Presentation.Web.Common.Utilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
#endregion
namespace Lumina.Presentation.Web.Common.DependencyInjection;
@@ -26,6 +28,12 @@ internal static class PresentationWebLayerConfiguration
.Bind(configuration.GetRequiredSection(ServerConfigurationModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
serviceCollection.AddOptions<EncryptionSettingsModel>()
.Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
return serviceCollection;
}
}
@@ -1,9 +1,13 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters;
using Lumina.Presentation.Web.Common.Security;
using Lumina.Presentation.Web.Common.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
@@ -34,7 +38,7 @@ public static class PresentationWebLayerServices
public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services)
{
services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter)))
.AddJsonOptions(options =>
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.MaxDepth = 256;
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
@@ -46,9 +50,9 @@ public static class PresentationWebLayerServices
.AddCookie(options =>
{
// basic path configuration
options.LoginPath = "/account/login";
options.LogoutPath = "/account/logout";
options.AccessDeniedPath = "/account/access-denied";
options.LoginPath = "/auth/login";
options.LogoutPath = "/auth/logout";
options.AccessDeniedPath = "/auth/access-denied";
// Cookie configuration
options.Cookie = new CookieBuilder
@@ -67,7 +71,7 @@ public static class PresentationWebLayerServices
// handle validation to support various deployment scenarios
options.Events = new CookieAuthenticationEvents
{
{
// handle redirects to work with different base paths
OnRedirectToLogin = context =>
{
@@ -81,6 +85,10 @@ public static class PresentationWebLayerServices
};
});
// add an authorization policy that ensures application is initialized with super admin account before allowing access
services.AddAuthorizationBuilder()
.AddPolicy("RequireInitialization", policy => policy.Requirements.Add(new InitializationRequirement()));
// add forwarded headers middleware to handle reverse proxy scenarios
services.Configure<ForwardedHeadersOptions>(options =>
{
@@ -126,6 +134,9 @@ public static class PresentationWebLayerServices
services.AddHttpContextAccessor();
services.AddScoped<ApiExceptionFilter>();
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddSingleton<ICryptographyService, CryptographyService>();
services.AddSingleton<IUrlService, UrlService>();
return services;
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.Configuration;
/// <summary>
/// Model for deserializing media settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class EncryptionSettingsModel
{
public const string SECTION_NAME = "EncryptionSettings";
/// <summary>
/// Gets or sets the root directory where media files are stored.
/// </summary>
public required string SecretKey { get; init; }
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the request model for user authentication.
/// </summary>
/// <param name="Username">The username used to authenticate.</param>
/// <param name="Password">The password used to authenticate.</param>
/// <param name="TotpCode">The TOTP (Time-Based One-Time Password) code used for two-factor authentication.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginRequestModel(
string? Username = null,
string? Password = null,
string? TotpCode = null
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Models.UsersManagement;
/// <summary>
/// Represents the response model for a user authentication.
/// </summary>
/// <param name="Id">The Id of the logged in user.</param>
/// <param name="Username">The username of the logged in user.</param>
/// <param name="Token">The JWT authentication token, <see langword="null"/> if authentication failed or TOTP is required.</param>
/// <param name="UsesTotp">Indicates whether the user has Two-Factor Authentication enabled, or not.</param>
[DebuggerDisplay("Username: {Username}")]
public record LoginResponseModel(
Guid Id,
string? Username,
string? Token,
bool UsesTotp
);
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Models.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Security.Cryptography;
using System.Text;
#endregion
namespace Lumina.Presentation.Web.Common.Security;
/// <summary>
/// Service for cryptographic concerns.
/// </summary>
public sealed class CryptographyService : ICryptographyService, IDisposable
{
private readonly byte[] _key;
/// <summary>
/// Initializes a new instance of the <see cref="CryptographyService"/> class.
/// </summary>
/// <param name="encryptionSettingsModelOptions">Injected service for retrieving <see cref="EncryptionSettingsModel"/>.</param>
public CryptographyService(IOptions<EncryptionSettingsModel> encryptionSettingsModelOptions)
{
_key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey);
}
/// <summary>
/// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
/// </summary>
/// <param name="plaintext">The plaintext string to encrypt.</param>
/// <returns>A Base64-encoded string of the combined IV and encrypted ciphertext.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="plaintext"/> is <see langword="null"/> or empty.</exception>
public string Encrypt(string plaintext)
{
if (string.IsNullOrEmpty(plaintext))
throw new ArgumentException("Value cannot be null or empty", nameof(plaintext));
// generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts
byte[] iv = new byte[16];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
rng.GetBytes(iv);
using Aes aes = Aes.Create();
aes.Key = _key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length);
// combine IV and ciphertext
byte[] combined = new byte[iv.Length + ciphertext.Length];
Buffer.BlockCopy(iv, 0, combined, 0, iv.Length);
Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length);
return Convert.ToBase64String(combined);
}
/// <summary>
/// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
/// </summary>
/// <param name="ciphertext">The Base64-encoded string containing both IV and ciphertext.</param>
/// <returns>The decrypted plaintext string.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="ciphertext"/> is <see langword="null"/>, empty, or invalid.</exception>
public string Decrypt(string ciphertext)
{
if (string.IsNullOrEmpty(ciphertext))
throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext));
// decode the combined data (IV + ciphertext) from Base64
byte[] combined = Convert.FromBase64String(ciphertext);
if (combined.Length < 16)
throw new ArgumentException("Invalid ciphertext");
// extract IV and ciphertext
byte[] iv = new byte[16];
byte[] encryptedData = new byte[combined.Length - 16];
Buffer.BlockCopy(combined, 0, iv, 0, 16);
Buffer.BlockCopy(combined, 16, encryptedData, 0, encryptedData.Length);
using Aes aes = Aes.Create();
aes.Key = _key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform decryptor = aes.CreateDecryptor();
byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(decrypted);
}
/// <summary>
/// Clears sensitive key data when the service is disposed.
/// </summary>
public void Dispose()
{
Array.Clear(_key, 0, _key.Length);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Security;
/// <summary>
/// Interface for the service for cryptographic concerns.
/// </summary>
public interface ICryptographyService
{
/// <summary>
/// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
/// </summary>
/// <param name="plaintext">The plaintext string to encrypt.</param>
/// <returns>A Base64-encoded string of the combined IV and encrypted ciphertext.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="plaintext"/> is <see langword="null"/> or empty.</exception>
string Encrypt(string plaintext);
/// <summary>
/// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
/// </summary>
/// <param name="ciphertext">The Base64-encoded string containing both IV and ciphertext.</param>
/// <returns>The decrypted plaintext string.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="ciphertext"/> is <see langword="null"/>, empty, or invalid.</exception>
string Decrypt(string ciphertext);
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Models.Configuration;
using System;
using System.Buffers.Text;
#endregion
namespace Lumina.Presentation.Web.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the EncryptionSettings application configuration settings section.
/// </summary>
public class EncryptionSettingsModelValidator : AbstractValidator<EncryptionSettingsModel>
{
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionSettingsModelValidator"/> class.
/// </summary>
public EncryptionSettingsModelValidator()
{
RuleFor(x => x.SecretKey)
.NotEmpty().WithMessage("Encryption secret key cannot be empty!")
.Must(value => Base64.IsValid(value.AsSpan())).WithMessage("Encryption secret key must be a base64 string!");
}
}
@@ -0,0 +1,170 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Models.UsersManagement;
using Lumina.Presentation.Web.Common.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Controllers.UsersManagement;
/// <summary>
/// Controller for authentication related operations.
/// </summary>
[Authorize]
[Route("/auth/")]
public class AuthController : Controller
{
private readonly IApiHttpClient _apiHttpClient;
private readonly ICryptographyService _cryptographyService;
/// <summary>
/// Initializes a new instance of the <see cref="AuthController"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
/// <param name="cryptographyService">Injected service for cryptographic functionality.</param>
public AuthController(IApiHttpClient apiHttpClient, ICryptographyService cryptographyService)
{
_apiHttpClient = apiHttpClient;
_cryptographyService = cryptographyService;
}
/// <summary>
/// Displays the view for registering a new account.
/// </summary>
[AllowAnonymous]
[InitializationCheck]
[HttpGet("register")]
public IActionResult Register()
{
// check if this is the initial super admin setup
string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
ViewData["RegistrationType"] = isPendingSuperAdminSetup == "true" ? "Admin" : "User";
return View(new RegisterRequestModel());
}
/// <summary>
/// Displays the view for logging in.
/// </summary>
/// <param name="returnUrl">The url to return to, after login (if any).</param>
[AllowAnonymous]
[InitializationCheck]
[HttpGet("login/{returnUrl?}")]
public IActionResult Login(string? returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
// if the user is already logged in, redirect them to the home page
if (User?.Identity?.IsAuthenticated == true)
return RedirectToAction("Index", "Home");
// check if the application is initialized (does contain at least the super user account); if it's not, redirect to registration view
string? isPendingSuperAdminSetup = HttpContext.Session.GetString(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP);
if (isPendingSuperAdminSetup == "true")
// TODO: should be:
// return View("~/Views/Auth/Register", new RegisterRequestDto());
// but doesn't work because of an ASP.NET bug: https://github.com/dotnet/AspNetCore.Docs/issues/25157
return RedirectToAction("Register", "Auth");
return View(new LoginRequestModel());
}
/// <summary>
/// Displays the view for recovering the password of an account.
/// </summary>
[AllowAnonymous]
[InitializationCheck]
[HttpGet("recover-password")]
public IActionResult RecoverPassword()
{
// if the user is already logged in, redirect them to the home page
if (User?.Identity?.IsAuthenticated == true)
return RedirectToAction("Index", "Home");
return View();
}
/// <summary>
/// Displays the view for registering a new account.
/// </summary>
[InitializationCheck]
[HttpGet("profile")]
public IActionResult Profile()
{
return View();
}
/// <summary>
/// Registers a new account.
/// </summary>
/// <param name="data">User credentials used for registration.</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequestModel data)
{
// call different endpoints based on the view hidden field - registration for normal users, or initial application admin account setup
string endpoint = data.RegistrationType == "Admin" ? "initialization" : "auth/register";
// attempt API registration
RegisterResponseModel response = await _apiHttpClient.PostAsync<RegisterResponseModel, RegisterRequestModel>(endpoint, data);
return Json(new { success = true, data = response });
}
/// <summary>
/// Logs in an new account.
/// </summary>
/// <param name="data">User credentials used for login.</param>
/// <param name="returnUrl">The url to return to, after login (if any).</param>
[AllowAnonymous]
[ValidateAntiForgeryToken]
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequestModel data, string? returnUrl = null)
{
try
{
// attempt API registration
LoginResponseModel response = await _apiHttpClient.PostAsync<LoginResponseModel, LoginRequestModel>("auth/login", data);
// store the received token in a secure cookie
Response.Cookies.Delete("Token");
Response.Cookies.Append("Token", _cryptographyService.Encrypt(response.Token!), new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddMonths(1),
Path = "/",
HttpOnly = true,
Secure = true
});
// tell asp.net we are logged in
List<Claim> claims =
[
new Claim(ClaimTypes.Name, response.Username!),
new Claim(ClaimTypes.NameIdentifier, response.Id.ToString()!),
new Claim("Token", response.Token!),
];
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
// return success status and redirect URL
return Json(new { success = true, data = string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl) ? Url.Content("~/") : Url.Content(returnUrl) });
}
catch (ApiException ex)
{
// in this particular case, we DO NOT want to let the ApiExceptionFilter take care of this exception, because when the user has 2FA enabled, the first auth step involves sending
// only the username and password, in which case the server API will respond with a validation error, that TOTP code is not valid (empty); it is then that we catch this error here
// and display the form that asks the user for the TOTP code
if (ex.ProblemDetails is not null && ex.ProblemDetails.Extensions?.Count > 0 && ex.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj))
if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
foreach (JsonProperty error in jsonElement.EnumerateObject())
if (error.Value.ValueKind == JsonValueKind.Array)
foreach (JsonElement errorValue in error.Value.EnumerateArray())
if (errorValue.ValueKind == JsonValueKind.String && errorValue.GetString() == "InvalidTotpCode" && string.IsNullOrEmpty(data.TotpCode))
return Json(new { success = true, data = new { isTotpRequired = true } }); // only get here when user did not enter a TOTP code at all, otherwise rethrow the validation error
throw;
}
}
}
@@ -0,0 +1,89 @@
@*
/auth/login/
*@
@using Lumina.Presentation.Web.Common.Models.UsersManagement
@using Lumina.Presentation.Web.Common.Services
@inject IUrlService _urlService
@model LoginRequestModel
<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="Login" method="post" id="login-form" class="inline">
@Html.AntiForgeryToken()
<input type="hidden" name="ReturnUrl" value="@ViewData["ReturnUrl"]" />
<div class="form-container">
<!-- Username -->
<div class="form-row">
<div class="form-label">
<label asp-for="Username">Username</label>:
</div>
<div class="form-field">
<input asp-for="Username" autocomplete="username" class="enlightenment-input" />
</div>
</div>
<!-- Password -->
<div class="form-row">
<div class="form-label">
<label asp-for="Password">Password</label>:
</div>
<div class="form-field">
<input type="password" asp-for="Password" autocomplete="current-password" class="enlightenment-input" />
</div>
</div>
<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="btnLogin" type="submit" class="confirm-button h-22px w-100px">Login</button>
</div>
<!-- 2FA -->
<div class="form-row mt-10 hidden" id="divTotpCode">
<div class="form-label">
<label asp-for="TotpCode">Totp Code</label>
</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 type="submit" id="btnValidateTotp" class="confirm-button h-22px w-100px hidden">Validate Code</button>
</div>
</div>
</form>
</div>
@section Scripts {
<script type="text/javascript" defer>
document.getElementById('login-form').addEventListener('submit', async (event) => {
event.preventDefault();
const form = event.target;
const txtUsername = form.querySelector('[name="Username"]');
const txtPassword = form.querySelector('[name="Password"]');
const txtTotpCode = form.querySelector('[name="TotpCode"]');
const divTotpCode = document.getElementById('divTotpCode');
const btnLogin = document.getElementById('btnLogin');
const btnRecoverPassword = document.getElementById('btnRecoverPassword');
const btnValidateTotp = document.getElementById('btnValidateTotp');
const formData = {
Username: txtUsername.value,
Password: txtPassword.value,
TotpCode: txtTotpCode.value
};
const data = await callApiPostAsync('/auth/login', formData);
if (data && data.isTotpRequired) {
txtUsername.disabled = true;
txtPassword.disabled = true;
btnLogin.disabled = true;
btnRecoverPassword.disabled = true;
divTotpCode.classList.replace('hidden', 'inline');
btnValidateTotp.classList.replace('hidden', 'block');
txtTotpCode.focus();
}
else if (data)
window.location.href = data;
});
document.getElementById('btnRecoverPassword').addEventListener('click', () => {
window.location.href = '@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")';
});
</script>
}
@@ -1,4 +1,7 @@
{
"EncryptionSettings": {
"SecretKey": "" // base64 string
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {