using System.Security.Cryptography; using Heimdall.Application.Common; using Heimdall.Application.Common.Persistence; using Heimdall.Application.DTOs; using Heimdall.Domain.Entities; using MediatR; using Microsoft.AspNetCore.Identity; namespace Heimdall.Application.Users.Commands.ResetPassword; public class ResetPasswordHandler : IRequestHandler> { private readonly UserManager _userManager; private readonly IUserRepository _repository; public ResetPasswordHandler(UserManager userManager, IUserRepository repository) { _userManager = userManager; _repository = repository; } public async Task> Handle(ResetPasswordCommand command, CancellationToken ct) { var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false); if (user is null) return ServiceResult.NotFound("User not found"); var temporaryPassword = GenerateTemporaryPassword(); var token = await _userManager.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false); var result = await _userManager.ResetPasswordAsync(user, token, temporaryPassword).ConfigureAwait(false); if (!result.Succeeded) return ServiceResult.Failure("Password reset failed"); user.MustChangePassword = true; var updated = await _userManager.UpdateAsync(user).ConfigureAwait(false); if (!updated.Succeeded) return ServiceResult.Failure("Password reset failed"); var stamp = await _userManager.UpdateSecurityStampAsync(user).ConfigureAwait(false); if (!stamp.Succeeded) return ServiceResult.Failure("Password reset failed"); await _repository.AddAuditLogAsync(command.ActorId, "UserPasswordReset", "User", command.UserId.ToString(), null, null, ct); return ServiceResult.Success( new ResetPasswordResponse(temporaryPassword)); } private static string GenerateTemporaryPassword() { const string lower = "abcdefghijklmnopqrstuvwxyz"; const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string digits = "0123456789"; const string special = "!@#$%"; var chars = (lower + upper + digits + special).ToCharArray(); var password = new char[16]; password[0] = digits[RandomNumberGenerator.GetInt32(digits.Length)]; password[1] = lower[RandomNumberGenerator.GetInt32(lower.Length)]; password[2] = upper[RandomNumberGenerator.GetInt32(upper.Length)]; password[3] = special[RandomNumberGenerator.GetInt32(special.Length)]; for (int i = 4; i < password.Length; i++) password[i] = chars[RandomNumberGenerator.GetInt32(chars.Length)]; RandomNumberGenerator.Shuffle(password.AsSpan()); return new string(password); } }