Files
Heimdall/src/Heimdall.Application/Users/Commands/ResetPassword/ResetPasswordHandler.cs
T

67 lines
3.0 KiB
C#
Raw Normal View History

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<ResetPasswordCommand, ServiceResult<ResetPasswordResponse>>
{
private readonly UserManager<AppUser> _userManager;
private readonly IUserRepository _repository;
public ResetPasswordHandler(UserManager<AppUser> userManager, IUserRepository repository)
{
_userManager = userManager;
_repository = repository;
}
public async Task<ServiceResult<ResetPasswordResponse>> Handle(ResetPasswordCommand command, CancellationToken ct)
{
var user = await _userManager.FindByIdAsync(command.UserId.ToString()).ConfigureAwait(false);
if (user is null)
return ServiceResult<ResetPasswordResponse>.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<ResetPasswordResponse>.Failure("Password reset failed");
user.MustChangePassword = true;
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(command.ActorId, "UserPasswordReset", "User",
command.UserId.ToString(), null, null, ct);
return ServiceResult<ResetPasswordResponse>.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);
}
}