fix(identity): harden user lifecycle and permissions
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m8s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Failing after 6m10s
Heimdall Gitea / Build and scan server image (pull_request) Failing after 8m2s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m8s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Failing after 6m10s
Heimdall Gitea / Build and scan server image (pull_request) Failing after 8m2s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s
This commit is contained in:
1 parent
ea5f0b7589
commit
2bf3dbc95b
80 files changed
+1208
-507
No files matched your search
@@ -13,10 +13,11 @@ internal static class AuthHelper
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
UserManager<AppUser> userManager,
|
||||
DateTime? sessionStarted = null)
|
||||
DateTime? sessionStarted = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
|
||||
var permissions = rolePermissionService.GetPermissionsForRoles(roles);
|
||||
var permissions = await rolePermissionService.GetPermissionsForRolesAsync(roles, ct).ConfigureAwait(false);
|
||||
|
||||
var (accessToken, expiresAt) = sessionStarted is null
|
||||
? jwtService.GenerateAccessToken(user, roles, permissions)
|
||||
@@ -30,12 +31,14 @@ internal static class AuthHelper
|
||||
refreshToken,
|
||||
expiresAt,
|
||||
false,
|
||||
new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles])));
|
||||
new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles], [.. permissions])));
|
||||
}
|
||||
|
||||
internal static async Task<UserInfo> MapUserInfoAsync(AppUser user, UserManager<AppUser> userManager)
|
||||
internal static async Task<UserInfo> MapUserInfoAsync(AppUser user, UserManager<AppUser> userManager,
|
||||
IRolePermissionService rolePermissionService, CancellationToken ct)
|
||||
{
|
||||
var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
|
||||
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles]);
|
||||
var permissions = await rolePermissionService.GetPermissionsForRolesAsync(roles, ct).ConfigureAwait(false);
|
||||
return new UserInfo(user.Id, user.Email ?? "", user.DisplayName, [.. roles], [.. permissions]);
|
||||
}
|
||||
}
|
||||
@@ -48,16 +48,23 @@ public sealed class BootstrapAdminHandler : IRequestHandler<BootstrapAdminComman
|
||||
};
|
||||
var created = await _users.CreateAsync(user, request.Password).ConfigureAwait(false);
|
||||
if (!created.Succeeded)
|
||||
return ServiceResult<AuthResponse>.Failure(string.Join(", ", created.Errors.Select(e => e.Description)));
|
||||
{
|
||||
_logger.LogWarning("Identity rejected initial administrator creation with codes {Codes}", string.Join(',', created.Errors.Select(e => e.Code)));
|
||||
return ServiceResult<AuthResponse>.Failure("Initial administrator creation failed");
|
||||
}
|
||||
|
||||
var role = await _users.AddToRoleAsync(user, "Admin").ConfigureAwait(false);
|
||||
if (!role.Succeeded)
|
||||
return ServiceResult<AuthResponse>.Failure(string.Join(", ", role.Errors.Select(e => e.Description)));
|
||||
{
|
||||
await _users.DeleteAsync(user).ConfigureAwait(false);
|
||||
_logger.LogWarning("Identity rejected initial administrator role assignment with codes {Codes}", string.Join(',', role.Errors.Select(e => e.Code)));
|
||||
return ServiceResult<AuthResponse>.Failure("Initial administrator creation failed");
|
||||
}
|
||||
|
||||
await _authData.SetSettingValueAsync("auth.public-registration.enabled", "false", "auth",
|
||||
"Public registration is disabled; accounts are created by administrators.", token).ConfigureAwait(false);
|
||||
_logger.LogInformation("Initial administrator account created for {Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwt, _permissions, _users).ConfigureAwait(false);
|
||||
_logger.LogInformation("Initial administrator account created");
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwt, _permissions, _users, ct: token).ConfigureAwait(false);
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -45,9 +45,15 @@ public class ChangePasswordHandler : IRequestHandler<ChangePasswordCommand, Serv
|
||||
var result = await _userManager.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||
_logger.LogError("ChangePassword: Failed UserId={UserId}: {Errors}", request.UserId, errors);
|
||||
return ServiceResult.Failure(errors);
|
||||
_logger.LogWarning("Identity rejected password change with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
|
||||
return ServiceResult.Failure("Password change failed");
|
||||
}
|
||||
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded)
|
||||
{
|
||||
_logger.LogError("Identity could not revoke sessions after password change for user {UserId}", request.UserId);
|
||||
return ServiceResult.Failure("Password changed but active sessions could not be revoked", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("ChangePassword: Success UserId={UserId}", request.UserId);
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
|
||||
|
||||
public sealed record Complete2faSetupCommand(Guid UserId, string Code) : IRequest<ServiceResult<Complete2faSetupResponse>>;
|
||||
@@ -0,0 +1,69 @@
|
||||
using Heimdall.Application.Auth.Services;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
|
||||
|
||||
public sealed class Complete2faSetupHandler : IRequestHandler<Complete2faSetupCommand, ServiceResult<Complete2faSetupResponse>>
|
||||
{
|
||||
private readonly UserManager<AppUser> _users;
|
||||
private readonly IApplicationDbContext _db;
|
||||
private readonly ILogger<Complete2faSetupHandler> _logger;
|
||||
|
||||
public Complete2faSetupHandler(UserManager<AppUser> users, IApplicationDbContext db, ILogger<Complete2faSetupHandler> logger)
|
||||
{
|
||||
_users = users;
|
||||
_db = db;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<Complete2faSetupResponse>> Handle(Complete2faSetupCommand request, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.Code) || request.Code.Trim().Length != 6)
|
||||
return ServiceResult<Complete2faSetupResponse>.Failure("Invalid authenticator code", 400);
|
||||
var user = await _users.FindByIdAsync(request.UserId.ToString()).ConfigureAwait(false);
|
||||
if (user is null) return ServiceResult<Complete2faSetupResponse>.NotFound("User not found");
|
||||
if (await _users.GetTwoFactorEnabledAsync(user).ConfigureAwait(false))
|
||||
return ServiceResult<Complete2faSetupResponse>.Conflict("Two-factor authentication is already enabled");
|
||||
|
||||
var valid = await _users.VerifyTwoFactorTokenAsync(user, TokenOptions.DefaultAuthenticatorProvider, request.Code.Trim()).ConfigureAwait(false);
|
||||
if (!valid) return ServiceResult<Complete2faSetupResponse>.Failure("Invalid authenticator code", 400);
|
||||
|
||||
var oldCodes = await _db.UserRecoveryCodes.Where(x => x.UserId == user.Id).ToListAsync(ct).ConfigureAwait(false);
|
||||
if (oldCodes.Count > 0) _db.UserRecoveryCodes.RemoveRange(oldCodes);
|
||||
var codes = RecoveryCodeService.Generate(10);
|
||||
foreach (var code in codes) _db.UserRecoveryCodes.Add(new UserRecoveryCode(user.Id, RecoveryCodeService.Hash(code)));
|
||||
|
||||
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
var result = await _users.SetTwoFactorEnabledAsync(user, true).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
_logger.LogWarning("Identity rejected enabling two-factor authentication for user {UserId}", request.UserId);
|
||||
await RemoveRecoveryCodesAsync(user.Id, ct).ConfigureAwait(false);
|
||||
return ServiceResult<Complete2faSetupResponse>.Failure("Unable to enable two-factor authentication");
|
||||
}
|
||||
|
||||
var stamp = await _users.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded)
|
||||
{
|
||||
await _users.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);
|
||||
await RemoveRecoveryCodesAsync(user.Id, ct).ConfigureAwait(false);
|
||||
_logger.LogError("Identity could not revoke existing sessions after enabling two-factor authentication for user {UserId}", user.Id);
|
||||
return ServiceResult<Complete2faSetupResponse>.Failure("Unable to complete two-factor setup");
|
||||
}
|
||||
return ServiceResult<Complete2faSetupResponse>.Success(new Complete2faSetupResponse(codes, codes.Count));
|
||||
}
|
||||
|
||||
private async Task RemoveRecoveryCodesAsync(Guid userId, CancellationToken ct)
|
||||
{
|
||||
var codes = await _db.UserRecoveryCodes.Where(x => x.UserId == userId).ToListAsync(ct).ConfigureAwait(false);
|
||||
if (codes.Count == 0) return;
|
||||
_db.UserRecoveryCodes.RemoveRange(codes);
|
||||
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Complete2faSetup;
|
||||
|
||||
public sealed class Complete2faSetupValidator : AbstractValidator<Complete2faSetupCommand>
|
||||
{
|
||||
public Complete2faSetupValidator() => RuleFor(x => x.Code).NotEmpty().Length(6);
|
||||
}
|
||||
@@ -44,9 +44,8 @@ public class ConfirmEmailHandler : IRequestHandler<ConfirmEmailCommand, ServiceR
|
||||
var result = await _userManager.ConfirmEmailAsync(user, decodedToken).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||
_logger.LogWarning("ConfirmEmail: Failed UserId={UserId}: {Errors}", request.UserId, errors);
|
||||
return ServiceResult.Failure(errors);
|
||||
_logger.LogWarning("Identity rejected email confirmation with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
|
||||
return ServiceResult.Failure("Email confirmation failed");
|
||||
}
|
||||
|
||||
_logger.LogInformation("ConfirmEmail: Confirmed successfully UserId={UserId}", request.UserId);
|
||||
|
||||
@@ -3,4 +3,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Disable2fa;
|
||||
|
||||
public record Disable2faCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
public record Disable2faCommand(Guid UserId, string CurrentPassword) : IRequest<ServiceResult>;
|
||||
@@ -31,6 +31,10 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
|
||||
return ServiceResult.NotFound("User not found");
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(request.CurrentPassword)
|
||||
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword).ConfigureAwait(false))
|
||||
return ServiceResult.Failure("Current password is incorrect", 400);
|
||||
|
||||
var result = await _userManager.SetTwoFactorEnabledAsync(user, false).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
@@ -38,6 +42,9 @@ public class Disable2faHandler : IRequestHandler<Disable2faCommand, ServiceResul
|
||||
return ServiceResult.Failure("Failed to disable 2FA");
|
||||
}
|
||||
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
|
||||
|
||||
// Purger les codes de récupération — ils ne sont plus valables
|
||||
var codes = await _db.UserRecoveryCodes
|
||||
.Where(r => r.UserId == request.UserId)
|
||||
|
||||
@@ -4,4 +4,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.Enable2fa;
|
||||
|
||||
public record Enable2faCommand(Guid UserId) : IRequest<ServiceResult<Enable2faResponse>>;
|
||||
public record Enable2faCommand(Guid UserId, string CurrentPassword) : IRequest<ServiceResult<Enable2faResponse>>;
|
||||
@@ -33,16 +33,18 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
|
||||
return ServiceResult<Enable2faResponse>.NotFound("User not found");
|
||||
}
|
||||
|
||||
var result = await _userManager.SetTwoFactorEnabledAsync(user, true).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
_logger.LogError("Enable2fa: Failed UserId={UserId}", request.UserId);
|
||||
return ServiceResult<Enable2faResponse>.Failure("Failed to enable 2FA");
|
||||
}
|
||||
if (string.IsNullOrEmpty(request.CurrentPassword)
|
||||
|| !await _userManager.CheckPasswordAsync(user, request.CurrentPassword).ConfigureAwait(false))
|
||||
return ServiceResult<Enable2faResponse>.Failure("Current password is incorrect", 400);
|
||||
|
||||
if (await _userManager.GetTwoFactorEnabledAsync(user).ConfigureAwait(false))
|
||||
return ServiceResult<Enable2faResponse>.Conflict("Two-factor authentication is already enabled");
|
||||
|
||||
// Generate authenticator key for the QR code setup (l'utilisateur doit scanner le code avec son app)
|
||||
// Note: key is generated AFTER enabling 2FA so it's available immediately
|
||||
await _userManager.ResetAuthenticatorKeyAsync(user).ConfigureAwait(false);
|
||||
var reset = await _userManager.ResetAuthenticatorKeyAsync(user).ConfigureAwait(false);
|
||||
if (!reset.Succeeded)
|
||||
return ServiceResult<Enable2faResponse>.Failure("Unable to initialize authenticator setup");
|
||||
var key = await _userManager.GetAuthenticatorKeyAsync(user).ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
@@ -50,16 +52,8 @@ public class Enable2faHandler : IRequestHandler<Enable2faCommand, ServiceResult<
|
||||
return ServiceResult<Enable2faResponse>.Failure("Failed to generate 2FA key");
|
||||
}
|
||||
|
||||
// Générer 10 codes de récupération (P0 spec 4.3) — affichés UNE seule fois, stockés hashés
|
||||
var recoveryCodes = RecoveryCodeService.Generate(10);
|
||||
foreach (var code in recoveryCodes)
|
||||
{
|
||||
_db.UserRecoveryCodes.Add(new UserRecoveryCode(request.UserId, RecoveryCodeService.Hash(code)));
|
||||
}
|
||||
await _db.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
|
||||
var qrCodeUri = $"otpauth://totp/Heimdall:{user.Email}?secret={key}&issuer=Heimdall&algorithm=SHA1&digits=6&period=30";
|
||||
_logger.LogInformation("Enable2fa: Enabled UserId={UserId} with {Count} recovery codes", request.UserId, recoveryCodes.Count);
|
||||
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri, recoveryCodes, recoveryCodes.Count));
|
||||
_logger.LogInformation("Authenticator setup initialized for user {UserId}; confirmation is still required", request.UserId);
|
||||
return ServiceResult<Enable2faResponse>.Success(new Enable2faResponse(key, qrCodeUri));
|
||||
}
|
||||
}
|
||||
@@ -27,13 +27,13 @@ public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, Serv
|
||||
|
||||
public async Task<ServiceResult> Handle(ForgotPasswordCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("ForgotPassword: Email={Email}", request.Email);
|
||||
_logger.LogInformation("Password reset request received");
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
// Ne pas divulguer si l'email existe ou pas
|
||||
if (user is null || !await _userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false))
|
||||
{
|
||||
_logger.LogInformation("ForgotPassword: No action for Email={Email} (not found or unconfirmed)", request.Email);
|
||||
_logger.LogInformation("Password reset request completed without an eligible account");
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, Serv
|
||||
await _emailService.SendEmailAsync(request.Email,
|
||||
ServerText.Get("Auth.ForgotPassword.Subject", language), body, ct).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation("ForgotPassword: Reset link sent to Email={Email}", request.Email);
|
||||
_logger.LogInformation("Password reset message sent");
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -43,30 +43,30 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(LoginCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Login attempt: Email={Email}", request.Email);
|
||||
_logger.LogInformation("Login attempt received");
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("Login: User not found Email={Email}", request.Email);
|
||||
await _userRepository.AddAuditLogAsync(null, "LoginFailed", "User", request.Email, null, "User not found", ct).ConfigureAwait(false);
|
||||
_logger.LogWarning("Login rejected: account unavailable");
|
||||
await _userRepository.AddAuditLogAsync(null, "LoginFailed", "User", null, null, "Authentication failed", ct).ConfigureAwait(false);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
if (await _userManager.IsLockedOutAsync(user))
|
||||
{
|
||||
_logger.LogWarning("Login: Account locked Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
|
||||
_logger.LogWarning("Login rejected: account unavailable");
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
var result = await _signInService.PasswordSignInAsync(user, request.Password, true).ConfigureAwait(false);
|
||||
var twoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
|
||||
if (result.ResultType == SignInResultType.LockedOut)
|
||||
return ServiceResult<AuthResponse>.Failure("Account locked. Try again later.", 429);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
if (result.ResultType != SignInResultType.Success
|
||||
&& !(result.ResultType == SignInResultType.RequiresTwoFactor && twoFactorEnabled))
|
||||
{
|
||||
_logger.LogWarning("Login: Password mismatch Email={Email}", request.Email);
|
||||
_logger.LogWarning("Login rejected: credentials invalid");
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
@@ -74,8 +74,8 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
|
||||
var emailConfirmRequired = await _authData.GetSettingValueAsync("email.confirmation.required", ct).ConfigureAwait(false);
|
||||
if (string.Equals(emailConfirmRequired, "true", StringComparison.OrdinalIgnoreCase) && !user.EmailConfirmed)
|
||||
{
|
||||
_logger.LogWarning("Login: Email not confirmed Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure("Email not confirmed. Check your inbox for the confirmation link.", 403);
|
||||
_logger.LogWarning("Login rejected: account does not meet current sign-in policy");
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid email or password");
|
||||
}
|
||||
|
||||
if (twoFactorEnabled)
|
||||
@@ -83,10 +83,10 @@ public class LoginHandler : IRequestHandler<LoginCommand, ServiceResult<AuthResp
|
||||
var challengeId = await LoginChallengeService.CreateAsync(_db, user, ct);
|
||||
return ServiceResult<AuthResponse>.Success(new AuthResponse(
|
||||
string.Empty, string.Empty, DateTime.UtcNow, true,
|
||||
await AuthHelper.MapUserInfoAsync(user, _userManager), challengeId));
|
||||
await AuthHelper.MapUserInfoAsync(user, _userManager, _rolePermissionService, ct), challengeId));
|
||||
}
|
||||
|
||||
_logger.LogInformation("Login: Success Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
||||
_logger.LogInformation("Login succeeded");
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,6 @@ public class RefreshTokenHandler : IRequestHandler<RefreshTokenCommand, ServiceR
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Refresh token already consumed");
|
||||
}
|
||||
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, started).ConfigureAwait(false);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, started, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
|
||||
|
||||
public record RegisterAdminCommand(string Email, string Password, string DisplayName) : IRequest<ServiceResult<AuthResponse>>;
|
||||
@@ -1,86 +0,0 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Heimdall.Application.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
|
||||
|
||||
public class RegisterAdminHandler : IRequestHandler<RegisterAdminCommand, ServiceResult<AuthResponse>>
|
||||
{
|
||||
private readonly IAuthDataService _authData;
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IRolePermissionService _rolePermissionService;
|
||||
private readonly IPasswordBreachChecker _breachChecker;
|
||||
private readonly ILogger<RegisterAdminHandler> _logger;
|
||||
|
||||
public RegisterAdminHandler(
|
||||
IAuthDataService authData,
|
||||
UserManager<AppUser> userManager,
|
||||
IJwtService jwtService,
|
||||
IRolePermissionService rolePermissionService,
|
||||
IPasswordBreachChecker breachChecker,
|
||||
ILogger<RegisterAdminHandler> logger)
|
||||
{
|
||||
_authData = authData;
|
||||
_userManager = userManager;
|
||||
_jwtService = jwtService;
|
||||
_rolePermissionService = rolePermissionService;
|
||||
_breachChecker = breachChecker;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<AuthResponse>> Handle(RegisterAdminCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("RegisterAdmin: Email={Email}, DisplayName={DisplayName}", request.Email, request.DisplayName);
|
||||
|
||||
// Vérifier le feature flag auth.admin-registration.enabled
|
||||
var flag = await _authData.GetSettingValueAsync("auth.admin-registration.enabled", ct).ConfigureAwait(false);
|
||||
if (!string.Equals(flag, "true", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_logger.LogWarning("RegisterAdmin: Disabled by feature flag Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure("Admin registration is disabled", 403);
|
||||
}
|
||||
|
||||
var existing = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
if (existing is not null)
|
||||
{
|
||||
_logger.LogWarning("RegisterAdmin: Already exists Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Conflict("Email already registered");
|
||||
}
|
||||
|
||||
// HaveIBeenPwned check (spec §4.3)
|
||||
if (await _breachChecker.IsPasswordBreachedAsync(request.Password, ct).ConfigureAwait(false))
|
||||
{
|
||||
_logger.LogWarning("RegisterAdmin: password has been breached (HIBP) for Email={Email}", request.Email);
|
||||
return ServiceResult<AuthResponse>.Failure(
|
||||
"This password has appeared in a data breach. Please choose a different password.");
|
||||
}
|
||||
|
||||
var user = new AppUser
|
||||
{
|
||||
UserName = request.Email,
|
||||
Email = request.Email,
|
||||
DisplayName = request.DisplayName
|
||||
};
|
||||
|
||||
var createResult = await _userManager.CreateAsync(user, request.Password).ConfigureAwait(false);
|
||||
if (!createResult.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", createResult.Errors.Select(e => e.Description));
|
||||
_logger.LogWarning("RegisterAdmin: Creation failed: {Errors}", errors);
|
||||
return ServiceResult<AuthResponse>.Failure(errors);
|
||||
}
|
||||
|
||||
// Assign Admin role
|
||||
await _userManager.AddToRoleAsync(user, "Admin").ConfigureAwait(false);
|
||||
user.EmailConfirmed = true;
|
||||
await _userManager.UpdateAsync(user).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation("RegisterAdmin: Admin user created Email={Email}", request.Email);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Heimdall.Application.Auth.Commands.RegisterAdmin;
|
||||
|
||||
public class RegisterAdminValidator : AbstractValidator<RegisterAdminCommand>
|
||||
{
|
||||
public RegisterAdminValidator()
|
||||
{
|
||||
RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256);
|
||||
RuleFor(x => x.DisplayName).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.Password).NotEmpty().MinimumLength(12)
|
||||
.WithMessage("Password must be at least 12 characters");
|
||||
}
|
||||
}
|
||||
@@ -19,25 +19,31 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
|
||||
|
||||
public async Task<ServiceResult> Handle(ResetPasswordCommand request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("ResetPassword: Email={Email}", request.Email);
|
||||
_logger.LogInformation("Password reset completion requested");
|
||||
|
||||
var user = await _userManager.FindByEmailAsync(request.Email).ConfigureAwait(false);
|
||||
if (user is null)
|
||||
{
|
||||
_logger.LogWarning("ResetPassword: User not found Email={Email}", request.Email);
|
||||
return ServiceResult.NotFound("User not found");
|
||||
_logger.LogWarning("Password reset completion rejected");
|
||||
return ServiceResult.Failure("Invalid or expired reset request", 400);
|
||||
}
|
||||
|
||||
var decodedToken = Uri.UnescapeDataString(request.Token);
|
||||
var result = await _userManager.ResetPasswordAsync(user, decodedToken, request.NewPassword).ConfigureAwait(false);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = string.Join(", ", result.Errors.Select(e => e.Description));
|
||||
_logger.LogWarning("ResetPassword: Failed Email={Email}: {Errors}", request.Email, errors);
|
||||
return ServiceResult.Failure(errors);
|
||||
_logger.LogWarning("Identity rejected password reset with codes {Codes}", string.Join(',', result.Errors.Select(e => e.Code)));
|
||||
return ServiceResult.Failure("Invalid or expired reset request", 400);
|
||||
}
|
||||
|
||||
_logger.LogInformation("ResetPassword: Success Email={Email}", request.Email);
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded)
|
||||
{
|
||||
_logger.LogError("Identity could not revoke sessions after password reset");
|
||||
return ServiceResult.Failure("Password reset failed", 500);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Password reset completed successfully");
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,12 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
|
||||
await LoginChallengeService.ReleaseAttemptAsync(_db, challenge, ct);
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Invalid 2FA code");
|
||||
}
|
||||
var stampUpdate = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stampUpdate.Succeeded)
|
||||
{
|
||||
_logger.LogError("Unable to rotate security stamp after recovery code use for user {UserId}", user.Id);
|
||||
return ServiceResult<AuthResponse>.Failure("Unable to complete sign-in");
|
||||
}
|
||||
_logger.LogInformation("Verify2fa: Recovery code redeemed UserId={UserId}", challenge.UserId);
|
||||
}
|
||||
|
||||
@@ -71,7 +77,7 @@ public class Verify2faHandler : IRequestHandler<Verify2faCommand, ServiceResult<
|
||||
return ServiceResult<AuthResponse>.Unauthorized("Challenge already used");
|
||||
await _userManager.ResetAccessFailedCountAsync(user);
|
||||
_logger.LogInformation("Verify2fa: Success UserId={UserId}", challenge.UserId);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager).ConfigureAwait(false);
|
||||
return await AuthHelper.CreateAuthResponseAsync(user, _jwtService, _rolePermissionService, _userManager, ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<bool> TryRedeemRecoveryCodeAsync(AppUser user, string code, CancellationToken ct)
|
||||
|
||||
@@ -20,7 +20,8 @@ public record UserInfo(
|
||||
Guid Id,
|
||||
string Email,
|
||||
string DisplayName,
|
||||
IList<string> Roles);
|
||||
IList<string> Roles,
|
||||
IList<string>? Permissions = null);
|
||||
|
||||
public record ApiKeyResponse(
|
||||
Guid Id,
|
||||
@@ -44,9 +45,15 @@ public record LogoutRequest(string RefreshToken);
|
||||
|
||||
public record Enable2faResponse(
|
||||
string SharedKey,
|
||||
string QrCodeUri,
|
||||
IReadOnlyList<string>? RecoveryCodes = null,
|
||||
int RecoveryCodesRemaining = 0);
|
||||
string QrCodeUri);
|
||||
|
||||
public record Complete2faSetupRequest(string Code);
|
||||
|
||||
public record Complete2faSetupResponse(IReadOnlyList<string> RecoveryCodes, int RecoveryCodesRemaining);
|
||||
|
||||
public record Disable2faRequest(string CurrentPassword);
|
||||
|
||||
public record Enable2faRequest(string CurrentPassword);
|
||||
|
||||
public record ConfirmEmailRequest(string UserId, string Token);
|
||||
public record ForgotPasswordRequest(string Email);
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
using Heimdall.Application.Common;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public interface IRolePermissionService
|
||||
{
|
||||
IList<string> GetPermissionsForRoles(IList<string> roles);
|
||||
Task<IList<string>> GetPermissionsForRolesAsync(IList<string> roles, CancellationToken ct);
|
||||
Task<IReadOnlyList<RolePermissionInfo>> GetAllAsync(CancellationToken ct);
|
||||
Task<ServiceResult> SetPermissionsAsync(string role, IReadOnlyCollection<string> permissions,
|
||||
Guid actorId, CancellationToken ct);
|
||||
Task EnsureDefaultsAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed record RolePermissionInfo(string Name, IReadOnlyList<string> Permissions);
|
||||
@@ -5,4 +5,5 @@ namespace Heimdall.Application.Users.Commands.AssignRoles;
|
||||
|
||||
public record AssignRolesCommand(
|
||||
Guid UserId,
|
||||
IList<string> Roles) : IRequest<ServiceResult>;
|
||||
IList<string> Roles,
|
||||
Guid? ActorId = null) : IRequest<ServiceResult>;
|
||||
@@ -35,11 +35,34 @@ public class AssignRolesHandler : IRequestHandler<AssignRolesCommand, ServiceRes
|
||||
"Promote another user to Admin first.", 400);
|
||||
}
|
||||
|
||||
await _userManager.RemoveFromRolesAsync(user, currentRoles).ConfigureAwait(false);
|
||||
await _userManager.AddToRolesAsync(user, command.Roles).ConfigureAwait(false);
|
||||
await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
var rolesToAdd = command.Roles.Except(currentRoles, StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
var rolesToRemove = currentRoles.Except(command.Roles, StringComparer.OrdinalIgnoreCase).ToArray();
|
||||
if (rolesToAdd.Length > 0)
|
||||
{
|
||||
var added = await _userManager.AddToRolesAsync(user, rolesToAdd).ConfigureAwait(false);
|
||||
if (!added.Succeeded) return ServiceResult.Failure("Unable to update user roles");
|
||||
}
|
||||
if (rolesToRemove.Length > 0)
|
||||
{
|
||||
var removed = await _userManager.RemoveFromRolesAsync(user, rolesToRemove).ConfigureAwait(false);
|
||||
if (!removed.Succeeded)
|
||||
{
|
||||
if (rolesToAdd.Length > 0)
|
||||
await _userManager.RemoveFromRolesAsync(user, rolesToAdd).ConfigureAwait(false);
|
||||
return ServiceResult.Failure("Unable to update user roles");
|
||||
}
|
||||
}
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded)
|
||||
{
|
||||
if (rolesToRemove.Length > 0)
|
||||
await _userManager.AddToRolesAsync(user, rolesToRemove).ConfigureAwait(false);
|
||||
if (rolesToAdd.Length > 0)
|
||||
await _userManager.RemoveFromRolesAsync(user, rolesToAdd).ConfigureAwait(false);
|
||||
return ServiceResult.Failure("Unable to revoke existing sessions");
|
||||
}
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserRolesUpdated", "User",
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserRolesUpdated", "User",
|
||||
command.UserId.ToString(),
|
||||
string.Join(",", currentRoles),
|
||||
string.Join(",", command.Roles),
|
||||
|
||||
@@ -5,4 +5,5 @@ namespace Heimdall.Application.Users.Commands.AssignSites;
|
||||
|
||||
public record AssignSitesCommand(
|
||||
Guid UserId,
|
||||
IList<Guid> SiteIds) : IRequest<ServiceResult>;
|
||||
IList<Guid> SiteIds,
|
||||
Guid? ActorId = null) : IRequest<ServiceResult>;
|
||||
@@ -24,6 +24,8 @@ public class AssignSitesHandler : IRequestHandler<AssignSitesCommand, ServiceRes
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _repository.SetUserSitesAsync(command.UserId, command.SiteIds, ct).ConfigureAwait(false);
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserSitesUpdated", "User", command.UserId.ToString(),
|
||||
null, string.Join(',', command.SiteIds), ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
@@ -8,4 +8,5 @@ public record CreateUserCommand(
|
||||
string Email,
|
||||
string Password,
|
||||
string DisplayName,
|
||||
IList<string>? Roles) : IRequest<ServiceResult<UserResponse>>;
|
||||
IList<string>? Roles,
|
||||
Guid? ActorId = null) : IRequest<ServiceResult<UserResponse>>;
|
||||
@@ -37,9 +37,14 @@ public class CreateUserHandler : IRequestHandler<CreateUserCommand, ServiceResul
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
var roles = command.Roles is { Count: > 0 } ? command.Roles : new List<string> { "Viewer" };
|
||||
await _userManager.AddToRolesAsync(user, roles).ConfigureAwait(false);
|
||||
var assignment = await _userManager.AddToRolesAsync(user, roles).ConfigureAwait(false);
|
||||
if (!assignment.Succeeded)
|
||||
{
|
||||
await _userManager.DeleteAsync(user).ConfigureAwait(false);
|
||||
return ServiceResult<UserResponse>.Failure("Unable to assign requested account roles");
|
||||
}
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserCreated", "User", user.Id.ToString(),
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserCreated", "User", user.Id.ToString(),
|
||||
null, null, ct);
|
||||
|
||||
var response = await _repository.GetByIdAsync(user.Id, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -3,4 +3,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.LockUser;
|
||||
|
||||
public record LockUserCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
public record LockUserCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult>;
|
||||
@@ -23,10 +23,17 @@ public class LockUserHandler : IRequestHandler<LockUserCommand, ServiceResult>
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false);
|
||||
await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false);
|
||||
if (roles.Contains("Admin", StringComparer.OrdinalIgnoreCase)
|
||||
&& await _repository.CountAdminUsersAsync(ct).ConfigureAwait(false) <= 1)
|
||||
return ServiceResult.Failure("Cannot lock the last administrator account.", 400);
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserLocked", "User",
|
||||
var lockout = await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue).ConfigureAwait(false);
|
||||
if (!lockout.Succeeded) return ServiceResult.Failure("Unable to lock account");
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
|
||||
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserLocked", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
|
||||
@@ -4,4 +4,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.ResetPassword;
|
||||
|
||||
public record ResetPasswordCommand(Guid UserId) : IRequest<ServiceResult<ResetPasswordResponse>>;
|
||||
public record ResetPasswordCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult<ResetPasswordResponse>>;
|
||||
@@ -30,13 +30,15 @@ public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, Servic
|
||||
var result = await _userManager.ResetPasswordAsync(user, token, temporaryPassword).ConfigureAwait(false);
|
||||
|
||||
if (!result.Succeeded)
|
||||
return ServiceResult<ResetPasswordResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
|
||||
|
||||
user.MustChangePassword = true;
|
||||
await _userManager.UpdateAsync(user).ConfigureAwait(false);
|
||||
var updated = await _userManager.UpdateAsync(user).ConfigureAwait(false);
|
||||
if (!updated.Succeeded) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded) return ServiceResult<ResetPasswordResponse>.Failure("Password reset failed");
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserPasswordReset", "User",
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserPasswordReset", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult<ResetPasswordResponse>.Success(
|
||||
|
||||
@@ -3,4 +3,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Users.Commands.UnlockUser;
|
||||
|
||||
public record UnlockUserCommand(Guid UserId) : IRequest<ServiceResult>;
|
||||
public record UnlockUserCommand(Guid UserId, Guid? ActorId = null) : IRequest<ServiceResult>;
|
||||
@@ -23,10 +23,14 @@ public class UnlockUserHandler : IRequestHandler<UnlockUserCommand, ServiceResul
|
||||
if (user is null)
|
||||
return ServiceResult.NotFound("User not found");
|
||||
|
||||
await _userManager.SetLockoutEndDateAsync(user, null).ConfigureAwait(false);
|
||||
await _userManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);
|
||||
var unlock = await _userManager.SetLockoutEndDateAsync(user, null).ConfigureAwait(false);
|
||||
if (!unlock.Succeeded) return ServiceResult.Failure("Unable to unlock account");
|
||||
var reset = await _userManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false);
|
||||
if (!reset.Succeeded) return ServiceResult.Failure("Unable to reset failed sign-in count");
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded) return ServiceResult.Failure("Unable to revoke existing sessions");
|
||||
|
||||
await _repository.AddAuditLogAsync(null, "UserUnlocked", "User",
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "UserUnlocked", "User",
|
||||
command.UserId.ToString(), null, null, ct);
|
||||
|
||||
return ServiceResult.Success();
|
||||
|
||||
@@ -60,6 +60,13 @@ public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ServiceResul
|
||||
return ServiceResult<UserResponse>.Failure(
|
||||
string.Join(", ", result.Errors.Select(e => e.Description)));
|
||||
|
||||
if (emailChanged)
|
||||
{
|
||||
var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded)
|
||||
return ServiceResult<UserResponse>.Failure("Email updated but existing sessions could not be revoked", 500);
|
||||
}
|
||||
|
||||
if (emailChanged)
|
||||
{
|
||||
await _repository.AddAuditLogAsync(command.ActorId, "User.EmailUpdated", "User", user.Id.ToString(),
|
||||
|
||||
@@ -62,6 +62,9 @@ public static class DependencyInjection
|
||||
// Identity
|
||||
services.AddIdentity<AppUser, AppRole>(options =>
|
||||
{
|
||||
options.User.RequireUniqueEmail = true;
|
||||
options.SignIn.RequireConfirmedEmail = false; // Heimdall enforces the configurable policy at its auth boundary.
|
||||
options.Lockout.AllowedForNewUsers = true;
|
||||
options.Password.RequiredLength = 12;
|
||||
options.Password.RequireDigit = true;
|
||||
options.Password.RequireLowercase = true;
|
||||
|
||||
@@ -90,8 +90,13 @@ public class UserRepository : IUserRepository
|
||||
var adminRole = await _db.Roles.FirstOrDefaultAsync(r => r.Name == AppRoles.Admin, ct).ConfigureAwait(false);
|
||||
if (adminRole is null) return 0;
|
||||
|
||||
return await _db.Set<IdentityUserRole<Guid>>()
|
||||
.CountAsync(ur => ur.RoleId == adminRole.Id, ct);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
return await (from membership in _db.Set<IdentityUserRole<Guid>>()
|
||||
join user in _db.Users on membership.UserId equals user.Id
|
||||
where membership.RoleId == adminRole.Id
|
||||
&& (!user.LockoutEnabled || user.LockoutEnd == null || user.LockoutEnd <= now)
|
||||
select membership.UserId)
|
||||
.CountAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task AddAuditLogAsync(Guid? userId, string action, string resourceType,
|
||||
|
||||
@@ -1,20 +1,166 @@
|
||||
using System.Security.Claims;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Common.Persistence;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
public class RolePermissionService : IRolePermissionService
|
||||
public sealed class RolePermissionService : IRolePermissionService
|
||||
{
|
||||
public IList<string> GetPermissionsForRoles(IList<string> roles)
|
||||
private const string PermissionClaim = "permission";
|
||||
private const string ConfiguredClaim = "heimdall:permissions-configured";
|
||||
private readonly RoleManager<AppRole> _roles;
|
||||
private readonly UserManager<AppUser> _users;
|
||||
private readonly IUserRepository _userRepository;
|
||||
|
||||
public RolePermissionService(RoleManager<AppRole> roles, UserManager<AppUser> users, IUserRepository userRepository)
|
||||
{
|
||||
var permissions = new List<string>();
|
||||
foreach (var role in roles)
|
||||
_roles = roles;
|
||||
_users = users;
|
||||
_userRepository = userRepository;
|
||||
}
|
||||
|
||||
public async Task<IList<string>> GetPermissionsForRolesAsync(IList<string> roleNames, CancellationToken ct)
|
||||
{
|
||||
var permissions = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var name in roleNames)
|
||||
{
|
||||
if (AppPermissions.RolePermissions.TryGetValue(role, out var rolePerms))
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var role = await _roles.FindByNameAsync(name).ConfigureAwait(false);
|
||||
if (role is null) continue;
|
||||
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
|
||||
foreach (var claim in claims.Where(c => c.Type == PermissionClaim))
|
||||
if (claim.Value.Length > 0) permissions.Add(claim.Value);
|
||||
}
|
||||
return permissions.Order(StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<RolePermissionInfo>> GetAllAsync(CancellationToken ct)
|
||||
{
|
||||
var result = new List<RolePermissionInfo>(AppRoles.All.Length);
|
||||
foreach (var name in AppRoles.All)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var role = await _roles.FindByNameAsync(name).ConfigureAwait(false);
|
||||
if (role is null) continue;
|
||||
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
|
||||
result.Add(new RolePermissionInfo(name, claims.Where(c => c.Type == PermissionClaim)
|
||||
.Select(c => c.Value).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> SetPermissionsAsync(string roleName, IReadOnlyCollection<string> permissions,
|
||||
Guid actorId, CancellationToken ct)
|
||||
{
|
||||
if (!AppRoles.All.Contains(roleName, StringComparer.Ordinal))
|
||||
return ServiceResult.NotFound("Role not found");
|
||||
if (roleName == AppRoles.Admin)
|
||||
return ServiceResult.Failure("The Admin role permissions are fixed to preserve full administrative recovery.", 400);
|
||||
|
||||
var allowed = AppPermissions.RolePermissions.Values.SelectMany(p => p).ToHashSet(StringComparer.Ordinal);
|
||||
var requested = permissions.ToHashSet(StringComparer.Ordinal);
|
||||
if (requested.Count != permissions.Count || requested.Any(p => !allowed.Contains(p)))
|
||||
return ServiceResult.Failure("The permission list contains duplicate or unknown permissions.", 400);
|
||||
|
||||
var role = await _roles.FindByNameAsync(roleName).ConfigureAwait(false);
|
||||
if (role is null) return ServiceResult.NotFound("Role not found");
|
||||
var current = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
|
||||
var currentPermissions = current.Where(c => c.Type == PermissionClaim).Select(c => c.Value)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
var additions = requested.Except(currentPermissions, StringComparer.Ordinal).ToArray();
|
||||
var removals = current.Where(c => c.Type == PermissionClaim && !requested.Contains(c.Value)).ToArray();
|
||||
if (additions.Length == 0 && removals.Length == 0) return ServiceResult.Success();
|
||||
|
||||
if (additions.Length > 0)
|
||||
{
|
||||
if (!await AddClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false))
|
||||
return ServiceResult.Failure("Unable to update role permissions", 500);
|
||||
}
|
||||
if (removals.Length > 0)
|
||||
{
|
||||
if (!await RemoveClaimsAsync(role, removals).ConfigureAwait(false))
|
||||
{
|
||||
permissions.AddRange(rolePerms);
|
||||
if (additions.Length > 0)
|
||||
await RemoveClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false);
|
||||
return ServiceResult.Failure("Unable to update role permissions", 500);
|
||||
}
|
||||
}
|
||||
return permissions.Distinct().ToList();
|
||||
|
||||
var members = await _users.GetUsersInRoleAsync(roleName).ConfigureAwait(false);
|
||||
foreach (var user in members)
|
||||
{
|
||||
var stamp = await _users.UpdateSecurityStampAsync(user).ConfigureAwait(false);
|
||||
if (!stamp.Succeeded)
|
||||
{
|
||||
// Earlier stamp rotations only revoke sessions early; restoring role claims
|
||||
// guarantees subsequent logins still receive the previous permission set.
|
||||
if (removals.Length > 0) await AddClaimsAsync(role, removals).ConfigureAwait(false);
|
||||
if (additions.Length > 0)
|
||||
await RemoveClaimsAsync(role, additions.Select(p => new Claim(PermissionClaim, p))).ConfigureAwait(false);
|
||||
return ServiceResult.Failure("Unable to revoke sessions after changing role permissions", 500);
|
||||
}
|
||||
}
|
||||
|
||||
await _userRepository.AddAuditLogAsync(actorId, "RolePermissionsUpdated", "Role", roleName,
|
||||
string.Join(',', currentPermissions.Order(StringComparer.Ordinal)),
|
||||
string.Join(',', requested.Order(StringComparer.Ordinal)), ct).ConfigureAwait(false);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
public async Task EnsureDefaultsAsync(CancellationToken ct)
|
||||
{
|
||||
foreach (var roleName in AppRoles.All)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var role = await _roles.FindByNameAsync(roleName).ConfigureAwait(false);
|
||||
if (role is null) continue;
|
||||
var claims = await _roles.GetClaimsAsync(role).ConfigureAwait(false);
|
||||
if (claims.Any(c => c.Type == ConfiguredClaim)) continue;
|
||||
var defaults = AppPermissions.RolePermissions[roleName]
|
||||
.Select(permission => new Claim(PermissionClaim, permission))
|
||||
.Where(permission => !claims.Contains(permission)).ToList();
|
||||
defaults.Add(new Claim(ConfiguredClaim, "true"));
|
||||
if (!await AddClaimsAsync(role, defaults).ConfigureAwait(false))
|
||||
throw new InvalidOperationException($"Could not initialize permissions for role {roleName}.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> AddClaimsAsync(AppRole role, IEnumerable<Claim> claims)
|
||||
{
|
||||
var added = new List<Claim>();
|
||||
foreach (var claim in claims)
|
||||
{
|
||||
var result = await _roles.AddClaimAsync(role, claim).ConfigureAwait(false);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
added.Add(claim);
|
||||
continue;
|
||||
}
|
||||
foreach (var rollback in added)
|
||||
await _roles.RemoveClaimAsync(role, rollback).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<bool> RemoveClaimsAsync(AppRole role, IEnumerable<Claim> claims)
|
||||
{
|
||||
var removed = new List<Claim>();
|
||||
foreach (var claim in claims)
|
||||
{
|
||||
var result = await _roles.RemoveClaimAsync(role, claim).ConfigureAwait(false);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
removed.Add(claim);
|
||||
continue;
|
||||
}
|
||||
foreach (var rollback in removed)
|
||||
await _roles.AddClaimAsync(role, rollback).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,9 @@ else if (_error)
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mb-4">
|
||||
@Text["AdminClaims_EditableInfo"]
|
||||
</MudAlert>
|
||||
@foreach (var category in _groupedPermissions)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4" @key="category.Key">
|
||||
@@ -40,7 +43,20 @@ else
|
||||
<MudTh>@Text["AdminClaims_Description"]</MudTh>
|
||||
@foreach (var role in _roles)
|
||||
{
|
||||
<MudTh Class="text-center" @key="role.Name">@role.Name</MudTh>
|
||||
<MudTh Class="text-center" @key="role.Name">
|
||||
@role.Name
|
||||
@if (role.Name == "Admin")
|
||||
{
|
||||
<MudText Typo="Typo.caption">@Text["AdminClaims_AdminImmutable"]</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Size="Size.Small" Variant="Variant.Text" Disabled="@(_savingRole == role.Name)"
|
||||
OnClick="@(() => SavePermissions(role.Name))">
|
||||
@(_savingRole == role.Name ? Text["Saving"] : Text["Save"])
|
||||
</MudButton>
|
||||
}
|
||||
</MudTh>
|
||||
}
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
@@ -52,11 +68,11 @@ else
|
||||
</MudTd>
|
||||
@foreach (var role in _roles)
|
||||
{
|
||||
var hasPermission = role.Permissions.Contains(context.Name);
|
||||
var hasPermission = _selectedPermissions.GetValueOrDefault(role.Name)?.Contains(context.Name) == true;
|
||||
<MudTd DataLabel="@role.Name" Class="text-center" @key="role.Name">
|
||||
<MudIcon Icon="@(hasPermission ? Icons.Material.Filled.Check : Icons.Material.Filled.Remove)"
|
||||
Color="@(hasPermission ? Color.Success : Color.Default)"
|
||||
Size="Size.Small" />
|
||||
<MudCheckBox T="bool" Value="@hasPermission" Disabled="@(role.Name == "Admin" || _savingRole == role.Name)"
|
||||
ValueChanged="@((bool enabled) => SetPermission(role.Name, context.Name, enabled))"
|
||||
Color="Color.Primary" />
|
||||
</MudTd>
|
||||
}
|
||||
</RowTemplate>
|
||||
@@ -70,9 +86,11 @@ else
|
||||
@code {
|
||||
private List<PermissionItem>? _permissions;
|
||||
private List<RoleItem> _roles = [];
|
||||
private readonly Dictionary<string, HashSet<string>> _selectedPermissions = new(StringComparer.Ordinal);
|
||||
private Dictionary<string, List<PermissionItem>> _groupedPermissions = new();
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
private string? _savingRole;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
@@ -95,6 +113,9 @@ else
|
||||
|
||||
_permissions = await permissionsTask;
|
||||
_roles = await rolesTask;
|
||||
_selectedPermissions.Clear();
|
||||
foreach (var role in _roles)
|
||||
_selectedPermissions[role.Name] = role.Permissions.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
_groupedPermissions = _permissions
|
||||
.GroupBy(p => string.IsNullOrEmpty(p.Category) ? "General" : p.Category)
|
||||
@@ -107,6 +128,31 @@ else
|
||||
}
|
||||
finally { _loading = false; }
|
||||
}
|
||||
|
||||
private void SetPermission(string role, string permission, bool enabled)
|
||||
{
|
||||
if (!_selectedPermissions.TryGetValue(role, out var selected)) return;
|
||||
if (enabled) selected.Add(permission);
|
||||
else selected.Remove(permission);
|
||||
}
|
||||
|
||||
private async Task SavePermissions(string role)
|
||||
{
|
||||
if (!_selectedPermissions.TryGetValue(role, out var selected)) return;
|
||||
_savingRole = role;
|
||||
try
|
||||
{
|
||||
if (!await Api.UpdateRolePermissionsAsync(role, selected.Order(StringComparer.Ordinal).ToArray()))
|
||||
{
|
||||
Snackbar.Add(Text["AdminClaims_SaveFailed"], Severity.Error);
|
||||
return;
|
||||
}
|
||||
Snackbar.Add(Text["AdminClaims_Saved"], Severity.Success);
|
||||
await LoadData();
|
||||
}
|
||||
catch { Snackbar.Add(Text["AdminClaims_SaveFailed"], Severity.Error); }
|
||||
finally { _savingRole = null; }
|
||||
}
|
||||
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
|
||||
public void Dispose() => Language.LanguageChanged -= OnLanguageChanged;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
@layout MainLayout
|
||||
@implements IDisposable
|
||||
@using Enable2faResponse = Heimdall.Application.DTOs.Enable2faResponse
|
||||
@using Complete2faSetupResponse = Heimdall.Application.DTOs.Complete2faSetupResponse
|
||||
@inject HeimdallApiClient Api
|
||||
@inject AuthState Auth
|
||||
@inject UiLanguageService Language
|
||||
@@ -105,6 +106,12 @@ else if (_profile is not null)
|
||||
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
@Text["DisableTwoFactor"]
|
||||
</MudButton>
|
||||
@if (_confirmDisable2fa)
|
||||
{
|
||||
<MudTextField @bind-Value="_disable2faPassword" Label='@Text["CurrentPassword"]' InputType="InputType.Password" Variant="Variant.Outlined" Class="mt-2" />
|
||||
<MudButton Color="Color.Error" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="ConfirmDisable2fa">@Text["ConfirmDisableTwoFactor"]</MudButton>
|
||||
<MudButton Variant="Variant.Text" Class="mt-2" OnClick="CancelDisable2fa">@Text["Cancel"]</MudButton>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -113,6 +120,12 @@ else if (_profile is not null)
|
||||
@if (_toggling2fa) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
@Text["EnableTwoFactor"]
|
||||
</MudButton>
|
||||
@if (_confirmEnable2fa)
|
||||
{
|
||||
<MudTextField @bind-Value="_enable2faPassword" Label='@Text["CurrentPassword"]' InputType="InputType.Password" Variant="Variant.Outlined" Class="mt-2" />
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="StartEnable2fa">@Text["ConfirmTwoFactor"]</MudButton>
|
||||
<MudButton Variant="Variant.Text" Class="mt-2" OnClick="CancelEnable2fa">@Text["Cancel"]</MudButton>
|
||||
}
|
||||
}
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
@@ -285,7 +298,7 @@ else if (_profile is not null)
|
||||
}
|
||||
</MudAlert>
|
||||
|
||||
@if (_2faSetup.RecoveryCodes is { Count: > 0 })
|
||||
@if (_completed2faSetup is { RecoveryCodes.Count: > 0 })
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning" Variant="Variant.Outlined" Class="mb-2">
|
||||
<MudText Typo="Typo.body2" Class="mb-1">
|
||||
@@ -295,7 +308,7 @@ else if (_profile is not null)
|
||||
</MudAlert>
|
||||
<MudPaper Elevation="0" Class="pa-3 mb-4" Style="border: 1px dashed #f0ad4e; border-radius: 8px;">
|
||||
<div class="d-flex flex-wrap">
|
||||
@foreach (var rc in _2faSetup.RecoveryCodes)
|
||||
@foreach (var rc in _completed2faSetup.RecoveryCodes)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="d-inline mr-4 mb-2" Style="font-family: monospace;">
|
||||
@rc
|
||||
@@ -303,12 +316,17 @@ else if (_profile is not null)
|
||||
}
|
||||
</div>
|
||||
</MudPaper>
|
||||
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label="@Text["RecoveryCodesSaved"]" Class="mb-2" />
|
||||
<MudCheckBox T="bool" @bind-Value="_recoveryCodesConfirmed" Label='@Text["RecoveryCodesSaved"]' Class="mb-2" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTextField @bind-Value="_authenticatorCode" Label='@Text["AuthenticatorCode"]' Variant="Variant.Outlined" />
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" Class="mt-2" Disabled="@_toggling2fa" OnClick="ConfirmEnable2fa">@Text["ConfirmTwoFactor"]</MudButton>
|
||||
}
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _show2faDialog = false)">@Text["Close"]</MudButton>
|
||||
<MudButton Variant="Variant.Text" OnClick="Close2faDialog" Disabled="@(_completed2faSetup is not null && !_recoveryCodesConfirmed)">@Text["Close"]</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@@ -333,8 +351,14 @@ else if (_profile is not null)
|
||||
|
||||
// Section 2FA
|
||||
private bool _toggling2fa;
|
||||
private bool _confirmDisable2fa;
|
||||
private string _disable2faPassword = "";
|
||||
private bool _confirmEnable2fa;
|
||||
private string _enable2faPassword = "";
|
||||
private bool _show2faDialog;
|
||||
private Enable2faResponse? _2faSetup;
|
||||
private Complete2faSetupResponse? _completed2faSetup;
|
||||
private string _authenticatorCode = "";
|
||||
private string? _2faError;
|
||||
private bool _recoveryCodesConfirmed;
|
||||
|
||||
@@ -404,21 +428,55 @@ else if (_profile is not null)
|
||||
|
||||
// ─── Section 3: Changer le mot de passe ───────────────────────
|
||||
|
||||
private async Task Enable2fa()
|
||||
private Task Enable2fa()
|
||||
{
|
||||
_confirmEnable2fa = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void CancelEnable2fa()
|
||||
{
|
||||
_confirmEnable2fa = false;
|
||||
_enable2faPassword = "";
|
||||
}
|
||||
|
||||
private async Task StartEnable2fa()
|
||||
{
|
||||
_toggling2fa = true;
|
||||
_2faError = null;
|
||||
_2faSetup = null;
|
||||
_completed2faSetup = null;
|
||||
_authenticatorCode = "";
|
||||
_recoveryCodesConfirmed = false;
|
||||
var currentPassword = _enable2faPassword;
|
||||
_confirmEnable2fa = false;
|
||||
try
|
||||
{
|
||||
var setup = await Api.Enable2faAsync();
|
||||
var setup = await Api.Enable2faAsync(currentPassword);
|
||||
if (setup is null)
|
||||
{
|
||||
_2faError = Text["OperationFailed"];
|
||||
_show2faDialog = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// ResetAuthenticatorKeyAsync rotates the security stamp. Reissue both
|
||||
// the Blazor token state and middleware cookie before confirming setup.
|
||||
var renewedSession = await Api.LoginAsync(_profile!.Email, currentPassword);
|
||||
if (renewedSession is null || string.IsNullOrEmpty(renewedSession.AccessToken))
|
||||
{
|
||||
_2faError = Text["OperationFailed"];
|
||||
_show2faDialog = true;
|
||||
return;
|
||||
}
|
||||
await AuthProvider.NotifyLoginAsync(renewedSession);
|
||||
if (!await AuthHelper.SignInAsync(JS, AuthHelper.CreateSignInPayload(renewedSession.AccessToken)))
|
||||
{
|
||||
_2faError = Text["OperationFailed"];
|
||||
_show2faDialog = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_2faSetup = setup;
|
||||
_show2faDialog = true;
|
||||
}
|
||||
@@ -429,17 +487,59 @@ else if (_profile is not null)
|
||||
}
|
||||
finally
|
||||
{
|
||||
_enable2faPassword = "";
|
||||
_toggling2fa = false;
|
||||
await LoadProfile();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task Disable2fa()
|
||||
private void Close2faDialog()
|
||||
{
|
||||
_show2faDialog = false;
|
||||
_2faSetup = null;
|
||||
_completed2faSetup = null;
|
||||
_authenticatorCode = "";
|
||||
_recoveryCodesConfirmed = false;
|
||||
}
|
||||
|
||||
private async Task ConfirmEnable2fa()
|
||||
{
|
||||
_toggling2fa = true;
|
||||
try
|
||||
{
|
||||
var ok = await Api.Disable2faAsync();
|
||||
var completed = await Api.ConfirmEnable2faAsync(_authenticatorCode);
|
||||
if (completed is null)
|
||||
{
|
||||
_2faError = "Code invalide ou activation impossible";
|
||||
return;
|
||||
}
|
||||
_completed2faSetup = completed;
|
||||
_2faError = null;
|
||||
}
|
||||
catch { _2faError = Text["OperationFailed"]; }
|
||||
finally { _toggling2fa = false; await LoadProfile(); }
|
||||
}
|
||||
|
||||
private Task Disable2fa()
|
||||
{
|
||||
_confirmDisable2fa = true;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void CancelDisable2fa()
|
||||
{
|
||||
_confirmDisable2fa = false;
|
||||
_disable2faPassword = "";
|
||||
}
|
||||
|
||||
private async Task ConfirmDisable2fa()
|
||||
{
|
||||
_toggling2fa = true;
|
||||
var disabled = false;
|
||||
try
|
||||
{
|
||||
var ok = await Api.Disable2faAsync(_disable2faPassword);
|
||||
disabled = ok;
|
||||
if (ok)
|
||||
{
|
||||
Snackbar.Add(Text["TwoFactorDisabled"], Severity.Success);
|
||||
@@ -456,6 +556,7 @@ else if (_profile is not null)
|
||||
finally
|
||||
{
|
||||
_toggling2fa = false;
|
||||
if (disabled) CancelDisable2fa();
|
||||
await LoadProfile();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,12 +4,12 @@ using Heimdall.Application.Auth.Commands.Login;
|
||||
using Heimdall.Application.Auth.Commands.Verify2fa;
|
||||
using Heimdall.Application.Auth.Commands.RefreshToken;
|
||||
using Heimdall.Application.Auth.Commands.ChangePassword;
|
||||
using Heimdall.Application.Auth.Commands.RegisterAdmin;
|
||||
using Heimdall.Application.Auth.Commands.ConfirmEmail;
|
||||
using Heimdall.Application.Auth.Commands.ForgotPassword;
|
||||
using Heimdall.Application.Auth.Commands.ResetPassword;
|
||||
using Heimdall.Application.Auth.Commands.Enable2fa;
|
||||
using Heimdall.Application.Auth.Commands.Disable2fa;
|
||||
using Heimdall.Application.Auth.Commands.Complete2faSetup;
|
||||
using Heimdall.Application.Auth.Commands.Logout;
|
||||
using Heimdall.Application.Auth.Queries;
|
||||
using Heimdall.Application.Common;
|
||||
@@ -57,7 +57,7 @@ public class AuthController : ControllerBase
|
||||
if (result.IsSuccess)
|
||||
return Ok(result.Data);
|
||||
|
||||
_logger.LogWarning("First administrator setup failed for {Email}: {Error}", request.Email, result.Error);
|
||||
_logger.LogWarning("First administrator setup failed with status {StatusCode}", result.StatusCode);
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
@@ -68,17 +68,17 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Login attempt for {Email}", request.Email);
|
||||
_logger.LogInformation("Login attempt received");
|
||||
var command = new LoginCommand(request.Email, request.Password);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("Login successful for {Email}", request.Email);
|
||||
_logger.LogInformation("Login succeeded");
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
_logger.LogWarning("Login failed for {Email}: {Error}", request.Email, result.Error);
|
||||
_logger.LogWarning("Login failed with status {StatusCode}", result.StatusCode);
|
||||
return StatusCode(result.StatusCode ?? 401, new { error = result.Error });
|
||||
}
|
||||
|
||||
@@ -154,34 +154,12 @@ public class AuthController : ControllerBase
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Register an admin user. Requires Admin role + feature flag auth.admin-registration.enabled.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = "AdminUsers")]
|
||||
[HttpPost("register-admin")]
|
||||
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("RegisterAdmin attempt for {Email}", request.Email);
|
||||
var command = new RegisterAdminCommand(request.Email, request.Password, request.DisplayName);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("Admin user registered successfully: {Email}", request.Email);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
_logger.LogWarning("Admin registration failed for {Email}: {Error}", request.Email, result.Error);
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Enable 2FA for the current user. Returns the shared key and QR code URI for setup.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
|
||||
[HttpPost("2fa/enable")]
|
||||
[ProducesResponseType(typeof(Enable2faResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Enable2fa(CancellationToken ct)
|
||||
public async Task<IActionResult> Enable2fa([FromBody] Enable2faRequest request, CancellationToken ct)
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
||||
@@ -191,11 +169,11 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
_logger.LogInformation("2FA enable attempt for user {UserId}", userId);
|
||||
var result = await _mediator.Send(new Enable2faCommand(userId), ct);
|
||||
var result = await _mediator.Send(new Enable2faCommand(userId, request.CurrentPassword), ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("2FA enabled successfully for user {UserId}", userId);
|
||||
_logger.LogInformation("Authenticator setup initialized; code confirmation is required");
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
@@ -203,12 +181,25 @@ public class AuthController : ControllerBase
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Confirm authenticator setup and return one-time recovery codes.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
|
||||
[EnableRateLimiting("TwoFactor")]
|
||||
[HttpPost("2fa/enable/confirm")]
|
||||
[ProducesResponseType(typeof(Complete2faSetupResponse), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> ConfirmEnable2fa([FromBody] Complete2faSetupRequest request, CancellationToken ct)
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (!Guid.TryParse(userIdClaim, out var userId)) return Unauthorized();
|
||||
var result = await _mediator.Send(new Complete2faSetupCommand(userId, request.Code), ct);
|
||||
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Disable 2FA for the current user.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies")]
|
||||
[HttpPost("2fa/disable")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Disable2fa(CancellationToken ct)
|
||||
public async Task<IActionResult> Disable2fa([FromBody] Disable2faRequest request, CancellationToken ct)
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
||||
@@ -218,7 +209,7 @@ public class AuthController : ControllerBase
|
||||
}
|
||||
|
||||
_logger.LogInformation("2FA disable attempt for user {UserId}", userId);
|
||||
var result = await _mediator.Send(new Disable2faCommand(userId), ct);
|
||||
var result = await _mediator.Send(new Disable2faCommand(userId, request.CurrentPassword), ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
@@ -260,7 +251,7 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> ForgotPassword([FromBody] ForgotPasswordRequest request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("ForgotPassword request for {Email}", request.Email);
|
||||
_logger.LogInformation("Password reset request received");
|
||||
await _mediator.Send(new ForgotPasswordCommand(request.Email), ct);
|
||||
return Ok(new { message = "If the email exists, a reset link has been sent." });
|
||||
}
|
||||
@@ -272,16 +263,16 @@ public class AuthController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequest request, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("ResetPassword attempt for {Email}", request.Email);
|
||||
_logger.LogInformation("Password reset completion requested");
|
||||
var result = await _mediator.Send(new ResetPasswordCommand(request.Email, request.Token, request.NewPassword), ct);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_logger.LogInformation("Password reset successfully for {Email}", request.Email);
|
||||
_logger.LogInformation("Password reset completed successfully");
|
||||
return Ok(new { message = "Password reset successfully" });
|
||||
}
|
||||
|
||||
_logger.LogWarning("Password reset failed for {Email}: {Error}", request.Email, result.Error);
|
||||
_logger.LogWarning("Password reset failed with status {StatusCode}", result.StatusCode);
|
||||
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Application.Services;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
@@ -10,6 +12,7 @@ public record RoleResponse(string Name, IReadOnlyList<string> Permissions);
|
||||
|
||||
/// <summary>Response DTO for a list of roles.</summary>
|
||||
public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
|
||||
public record UpdateRolePermissionsRequest(IReadOnlyList<string> Permissions);
|
||||
|
||||
[ApiController]
|
||||
[Route("api/roles")]
|
||||
@@ -17,16 +20,18 @@ public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
|
||||
[EnableRateLimiting("Api")]
|
||||
public class RolesController : ControllerBase
|
||||
{
|
||||
private readonly IRolePermissionService _permissions;
|
||||
|
||||
public RolesController(IRolePermissionService permissions) => _permissions = permissions;
|
||||
|
||||
/// <summary>Returns all roles with their associated permissions.</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(RolesListResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public IActionResult List()
|
||||
public async Task<IActionResult> List(CancellationToken ct)
|
||||
{
|
||||
var roles = AppPermissions.RolePermissions
|
||||
.Select(kvp => new RoleResponse(kvp.Key, kvp.Value))
|
||||
.ToList();
|
||||
|
||||
var roles = (await _permissions.GetAllAsync(ct).ConfigureAwait(false))
|
||||
.Select(role => new RoleResponse(role.Name, role.Permissions)).ToList();
|
||||
return Ok(new RolesListResponse(roles));
|
||||
}
|
||||
|
||||
@@ -35,11 +40,26 @@ public class RolesController : ControllerBase
|
||||
[ProducesResponseType(typeof(RoleResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
|
||||
public IActionResult GetByName(string name)
|
||||
public async Task<IActionResult> GetByName(string name, CancellationToken ct)
|
||||
{
|
||||
if (!AppPermissions.RolePermissions.TryGetValue(name, out var permissions))
|
||||
var role = (await _permissions.GetAllAsync(ct).ConfigureAwait(false))
|
||||
.FirstOrDefault(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase));
|
||||
if (role is null)
|
||||
return NotFound(new { error = $"Role '{name}' not found" });
|
||||
return Ok(new RoleResponse(role.Name, role.Permissions));
|
||||
}
|
||||
|
||||
return Ok(new RoleResponse(name, permissions));
|
||||
/// <summary>Replace the permission set for a non-Admin role.</summary>
|
||||
[HttpPut("{name}/permissions")]
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> UpdatePermissions(string name,
|
||||
[FromBody] UpdateRolePermissionsRequest request, CancellationToken ct)
|
||||
{
|
||||
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
||||
var result = await _permissions.SetPermissionsAsync(name, request.Permissions, actorId, ct)
|
||||
.ConfigureAwait(false);
|
||||
return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,8 @@ public class UsersController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var command = new CreateUserCommand(request.Email, request.Password, request.DisplayName, request.Roles);
|
||||
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
||||
var command = new CreateUserCommand(request.Email, request.Password, request.DisplayName, request.Roles, actorId);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
@@ -138,7 +139,8 @@ public class UsersController : ControllerBase
|
||||
public async Task<IActionResult> AssignRoles(
|
||||
Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new AssignRolesCommand(id, request.Roles), ct);
|
||||
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
||||
var result = await _mediator.Send(new AssignRolesCommand(id, request.Roles, actorId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
@@ -152,7 +154,8 @@ public class UsersController : ControllerBase
|
||||
public async Task<IActionResult> AssignSites(
|
||||
Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new AssignSitesCommand(id, request.SiteIds), ct);
|
||||
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
||||
var result = await _mediator.Send(new AssignSitesCommand(id, request.SiteIds, actorId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
@@ -165,7 +168,8 @@ public class UsersController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ResetPassword(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new ResetPasswordCommand(id), ct);
|
||||
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
||||
var result = await _mediator.Send(new ResetPasswordCommand(id, actorId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
@@ -197,7 +201,8 @@ public class UsersController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Lock(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new LockUserCommand(id), ct);
|
||||
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
||||
var result = await _mediator.Send(new LockUserCommand(id, actorId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
@@ -210,7 +215,8 @@ public class UsersController : ControllerBase
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Unlock(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new UnlockUserCommand(id), ct);
|
||||
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
||||
var result = await _mediator.Send(new UnlockUserCommand(id, actorId), ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
|
||||
@@ -549,6 +549,9 @@
|
||||
<data name="TwoFactorKey">
|
||||
<value>Key:</value>
|
||||
</data>
|
||||
<data name="AuthenticatorCode"><value>Authenticator app code</value></data>
|
||||
<data name="ConfirmTwoFactor"><value>Confirm setup</value></data>
|
||||
<data name="ConfirmDisableTwoFactor"><value>Confirm disable</value></data>
|
||||
<data name="SetupLink">
|
||||
<value>Setup link:</value>
|
||||
</data>
|
||||
@@ -4067,4 +4070,9 @@
|
||||
<data name="SetupAdmin_Failed" xml:space="preserve"><value>Setup could not be completed. The setup may already have been completed; refresh the page and sign in.</value></data>
|
||||
<data name="SetupAdmin_AutoLoginFailed" xml:space="preserve"><value>The administrator was created, but automatic sign-in failed. Please sign in.</value></data>
|
||||
<data name="SetupAdmin_Unavailable" xml:space="preserve"><value>Setup status could not be loaded. Check the server connection and try again.</value></data>
|
||||
<data name="AdminClaims_EditableInfo" xml:space="preserve"><value>Edit Supervisor and Viewer permissions, then save each role. Changes revoke their active sessions.</value></data>
|
||||
<data name="AdminClaims_AdminImmutable" xml:space="preserve"><value>Fixed</value></data>
|
||||
<data name="AdminClaims_SaveFailed" xml:space="preserve"><value>Could not save the role permissions.</value></data>
|
||||
<data name="AdminClaims_Saved" xml:space="preserve"><value>Role permissions saved. Affected users must sign in again.</value></data>
|
||||
<data name="Saving" xml:space="preserve"><value>Saving…</value></data>
|
||||
</root>
|
||||
@@ -549,6 +549,9 @@
|
||||
<data name="TwoFactorKey">
|
||||
<value>Clé :</value>
|
||||
</data>
|
||||
<data name="AuthenticatorCode"><value>Code de l’application d’authentification</value></data>
|
||||
<data name="ConfirmTwoFactor"><value>Confirmer l’activation</value></data>
|
||||
<data name="ConfirmDisableTwoFactor"><value>Confirmer la désactivation</value></data>
|
||||
<data name="SetupLink">
|
||||
<value>Lien de configuration :</value>
|
||||
</data>
|
||||
@@ -4067,4 +4070,9 @@
|
||||
<data name="SetupAdmin_Failed" xml:space="preserve"><value>La configuration a échoué. Elle est peut-être déjà terminée ; actualisez la page et connectez-vous.</value></data>
|
||||
<data name="SetupAdmin_AutoLoginFailed" xml:space="preserve"><value>L’administrateur a été créé, mais la connexion automatique a échoué. Connectez-vous.</value></data>
|
||||
<data name="SetupAdmin_Unavailable" xml:space="preserve"><value>Impossible de vérifier l’état de configuration. Vérifiez la connexion au serveur et réessayez.</value></data>
|
||||
<data name="AdminClaims_EditableInfo" xml:space="preserve"><value>Modifiez les droits de Supervisor et Viewer, puis enregistrez chaque rôle. Les changements révoquent leurs sessions actives.</value></data>
|
||||
<data name="AdminClaims_AdminImmutable" xml:space="preserve"><value>Fixe</value></data>
|
||||
<data name="AdminClaims_SaveFailed" xml:space="preserve"><value>Impossible d’enregistrer les droits du rôle.</value></data>
|
||||
<data name="AdminClaims_Saved" xml:space="preserve"><value>Droits du rôle enregistrés. Les utilisateurs concernés devront se reconnecter.</value></data>
|
||||
<data name="Saving" xml:space="preserve"><value>Enregistrement…</value></data>
|
||||
</root>
|
||||
@@ -549,6 +549,9 @@
|
||||
<data name="TwoFactorKey">
|
||||
<value>Clé :</value>
|
||||
</data>
|
||||
<data name="AuthenticatorCode"><value>Authenticator app code</value></data>
|
||||
<data name="ConfirmTwoFactor"><value>Confirm setup</value></data>
|
||||
<data name="ConfirmDisableTwoFactor"><value>Confirm disable</value></data>
|
||||
<data name="SetupLink">
|
||||
<value>Lien de configuration :</value>
|
||||
</data>
|
||||
@@ -4067,4 +4070,9 @@
|
||||
<data name="SetupAdmin_Failed" xml:space="preserve"><value>Setup could not be completed. Refresh and sign in if it was already completed.</value></data>
|
||||
<data name="SetupAdmin_AutoLoginFailed" xml:space="preserve"><value>The administrator was created, but automatic sign-in failed. Please sign in.</value></data>
|
||||
<data name="SetupAdmin_Unavailable" xml:space="preserve"><value>Setup status could not be loaded. Check the server connection and try again.</value></data>
|
||||
<data name="AdminClaims_EditableInfo" xml:space="preserve"><value>Edit Supervisor and Viewer permissions, then save each role. Changes revoke their active sessions.</value></data>
|
||||
<data name="AdminClaims_AdminImmutable" xml:space="preserve"><value>Fixed</value></data>
|
||||
<data name="AdminClaims_SaveFailed" xml:space="preserve"><value>Could not save the role permissions.</value></data>
|
||||
<data name="AdminClaims_Saved" xml:space="preserve"><value>Role permissions saved. Affected users must sign in again.</value></data>
|
||||
<data name="Saving" xml:space="preserve"><value>Saving…</value></data>
|
||||
</root>
|
||||
@@ -215,6 +215,8 @@ public partial class Program
|
||||
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
await SeedRolesAsync(roleManager);
|
||||
await seedScope.ServiceProvider.GetRequiredService<IRolePermissionService>()
|
||||
.EnsureDefaultsAsync(CancellationToken.None);
|
||||
await SeedGroupsAsync(groupDb);
|
||||
var existingKeys = await GetExistingSettingKeysAsync(groupDb);
|
||||
await SeedStorageSettingsAsync(groupDb, existingKeys);
|
||||
@@ -403,8 +405,15 @@ public partial class Program
|
||||
var adminPassword = configuration["Seed:AdminPassword"]
|
||||
?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD")
|
||||
?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. Set this env var to create the demo admin on startup.");
|
||||
await userManager.CreateAsync(testAdmin, adminPassword);
|
||||
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
|
||||
var created = await userManager.CreateAsync(testAdmin, adminPassword);
|
||||
if (!created.Succeeded)
|
||||
throw new InvalidOperationException("Configured demo administrator could not be created: " + string.Join(',', created.Errors.Select(e => e.Code)));
|
||||
var assigned = await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
|
||||
if (!assigned.Succeeded)
|
||||
{
|
||||
await userManager.DeleteAsync(testAdmin);
|
||||
throw new InvalidOperationException("Configured demo administrator role could not be assigned: " + string.Join(',', assigned.Errors.Select(e => e.Code)));
|
||||
}
|
||||
}
|
||||
|
||||
var demoSite = await groupDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo");
|
||||
@@ -715,8 +724,7 @@ public partial class Program
|
||||
foreach (var permission in allPermissions)
|
||||
options.AddPolicy(permission, policy => policy.RequireClaim("permission", permission));
|
||||
|
||||
// Policy used by AuthController (register-admin, user management).
|
||||
// Not a permission claim but a role-based gate for admin-only actions.
|
||||
// Legacy role-based policy retained for administrative endpoints.
|
||||
options.AddPolicy("AdminUsers", policy => policy.RequireRole(AppRoles.Admin));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -36,9 +36,10 @@ public class AuthState
|
||||
AuthCookie = null;
|
||||
|
||||
// Resolve permissions from roles (same mapping as JWT + cookie auth)
|
||||
Permissions = response.User?.Roles?
|
||||
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
|
||||
.ToHashSet() ?? new HashSet<string>();
|
||||
Permissions = response.User?.Permissions?.ToHashSet(StringComparer.Ordinal)
|
||||
?? response.User?.Roles?.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
|
||||
.ToHashSet(StringComparer.Ordinal)
|
||||
?? new HashSet<string>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -61,11 +62,10 @@ public class AuthState
|
||||
|
||||
AccessToken = null;
|
||||
RefreshToken = null;
|
||||
User = new UserInfo(id, email, displayName, roles);
|
||||
var permissions = principal.FindAll("permission").Select(c => c.Value).Distinct(StringComparer.Ordinal).ToList();
|
||||
User = new UserInfo(id, email, displayName, roles, permissions);
|
||||
|
||||
Permissions = roles
|
||||
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
|
||||
.ToHashSet();
|
||||
Permissions = permissions.ToHashSet(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public void Logout()
|
||||
@@ -92,7 +92,8 @@ public record UserInfo(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("email")] string Email,
|
||||
[property: JsonPropertyName("displayName")] string DisplayName,
|
||||
[property: JsonPropertyName("roles")] IList<string>? Roles);
|
||||
[property: JsonPropertyName("roles")] IList<string>? Roles,
|
||||
[property: JsonPropertyName("permissions")] IList<string>? Permissions = null);
|
||||
|
||||
public record SiteItem(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
|
||||
@@ -159,6 +159,14 @@ public class HeimdallApiClient : IDisposable
|
||||
return response?.Roles.ToList() ?? [];
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateRolePermissionsAsync(string role, IReadOnlyList<string> permissions)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PutAsJsonAsync($"api/roles/{Uri.EscapeDataString(role)}/permissions",
|
||||
new { permissions }, Json);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
// ─── Permissions ──────────────────────────────────────────────
|
||||
|
||||
public async Task<List<PermissionItem>> GetPermissionsAsync()
|
||||
@@ -286,18 +294,26 @@ public class HeimdallApiClient : IDisposable
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<Enable2faResponse?> Enable2faAsync()
|
||||
public async Task<Enable2faResponse?> Enable2faAsync(string currentPassword)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync("api/auth/2fa/enable", null);
|
||||
var response = await client.PostAsJsonAsync("api/auth/2fa/enable", new Enable2faRequest(currentPassword));
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<Enable2faResponse>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> Disable2faAsync()
|
||||
public async Task<Complete2faSetupResponse?> ConfirmEnable2faAsync(string code)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync("api/auth/2fa/disable", null);
|
||||
var response = await client.PostAsJsonAsync("api/auth/2fa/enable/confirm", new Complete2faSetupRequest(code));
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<Complete2faSetupResponse>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> Disable2faAsync(string currentPassword)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/auth/2fa/disable", new Disable2faRequest(currentPassword));
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
|
||||
@@ -154,9 +154,10 @@ public class HeimdallAuthStateProvider : RevalidatingServerAuthenticationStatePr
|
||||
foreach (var role in response.User.Roles ?? [])
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
|
||||
// Map roles → permissions via the AppPermissions dictionary (same as AuthService)
|
||||
var permissions = response.User.Roles?
|
||||
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var perms) ? perms : [])
|
||||
// Permissions arrive with the signed auth response so the UI and API use
|
||||
// the same persisted Identity role claims.
|
||||
var permissions = response.User.Permissions ?? response.User.Roles?
|
||||
.SelectMany(r => AppPermissions.RolePermissions.TryGetValue(r, out var defaults) ? defaults : [])
|
||||
.ToList() ?? [];
|
||||
|
||||
foreach (var permission in permissions)
|
||||
|
||||
Reference in new issue
Block a user