using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; using Heimdall.Domain.Entities; using MediatR; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; namespace Heimdall.Application.Auth.Commands.BootstrapAdmin; public sealed class BootstrapAdminHandler : IRequestHandler> { private readonly IAuthDataService _authData; private readonly UserManager _users; private readonly IJwtService _jwt; private readonly IRolePermissionService _permissions; private readonly IPasswordBreachChecker _breachChecker; private readonly ILogger _logger; public BootstrapAdminHandler(IAuthDataService authData, UserManager users, IJwtService jwt, IRolePermissionService permissions, IPasswordBreachChecker breachChecker, ILogger logger) { _authData = authData; _users = users; _jwt = jwt; _permissions = permissions; _breachChecker = breachChecker; _logger = logger; } public async Task> Handle(BootstrapAdminCommand request, CancellationToken ct) { if (await _breachChecker.IsPasswordBreachedAsync(request.Password, ct).ConfigureAwait(false)) return ServiceResult.Failure("This password has appeared in a data breach. Please choose a different password."); return await _authData.RunFirstAdminBootstrapTransactionAsync(async token => { if (await _authData.HasAnyUsersAsync(token).ConfigureAwait(false)) return ServiceResult.Conflict("Initial administrator setup has already been completed."); var user = new AppUser { UserName = request.Email, Email = request.Email, DisplayName = request.DisplayName, EmailConfirmed = true }; var created = await _users.CreateAsync(user, request.Password).ConfigureAwait(false); if (!created.Succeeded) { _logger.LogWarning("Identity rejected initial administrator creation with codes {Codes}", string.Join(',', created.Errors.Select(e => e.Code))); return ServiceResult.Failure("Initial administrator creation failed"); } var role = await _users.AddToRoleAsync(user, "Admin").ConfigureAwait(false); if (!role.Succeeded) { 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.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"); return await AuthHelper.CreateAuthResponseAsync(user, _jwt, _permissions, _users, ct: token).ConfigureAwait(false); }, ct).ConfigureAwait(false); } }