Refactor JWT token generation and update password handling logic; add exception handling behavior

This commit is contained in:
masoodafar-web
2025-11-13 21:40:14 +03:30
parent 4b1b135065
commit 8c4b1ab4f4
15 changed files with 199 additions and 34 deletions
@@ -3,15 +3,50 @@ namespace CMSMicroservice.Application.UserCQ.Commands.SetPasswordForUser;
public class SetPasswordForUserCommandHandler : IRequestHandler<SetPasswordForUserCommand, Unit>
{
private readonly IApplicationDbContext _context;
private readonly IHashService _hashService;
public SetPasswordForUserCommandHandler(IApplicationDbContext context)
public SetPasswordForUserCommandHandler(IApplicationDbContext context, IHashService hashService)
{
_context = context;
_hashService = hashService;
}
public async Task<Unit> Handle(SetPasswordForUserCommand request, CancellationToken cancellationToken)
{
//TODO: Implement your business logic
return new Unit();
// basic validations
if (!string.Equals(request.NewPassword, request.ConfirmPassword, StringComparison.Ordinal))
{
throw new CMSMicroservice.Application.Common.Exceptions.ValidationException(new[]
{
new FluentValidation.Results.ValidationFailure(nameof(request.ConfirmPassword), "کلمه عبور و تایید آن یکسان نیستند.")
});
}
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == request.UserId, cancellationToken)
?? throw new NotFoundException(nameof(User), request.UserId);
var hasExistingPassword = !string.IsNullOrWhiteSpace(user.HashPassword);
if (hasExistingPassword)
{
if (string.IsNullOrWhiteSpace(request.CurrentPassword))
{
throw new CMSMicroservice.Application.Common.Exceptions.ValidationException(new[]
{
new FluentValidation.Results.ValidationFailure(nameof(request.CurrentPassword), "کلمه عبور فعلی الزامی است.")
});
}
if (!_hashService.VerifyPassword(request.CurrentPassword, user.HashPassword))
{
throw new UnauthorizedAccessException("کلمه عبور فعلی نادرست است.");
}
}
// set new password (PBKDF2)
user.HashPassword = _hashService.HashPassword(request.NewPassword);
_context.Users.Update(user);
user.AddDomainEvent(new CMSMicroservice.Domain.Events.SetPasswordForUserEvent(user));
await _context.SaveChangesAsync(cancellationToken);
return Unit.Value;
}
}
@@ -1,7 +1,7 @@
using CMSMicroservice.Domain.Events;
using Microsoft.Extensions.Logging;
namespace CMSMicroservice.Application.UserCQ.EventHandlers;
namespace CMSMicroservice.Application.UserCQ.EventHandlers.SetPasswordForUserEventHandlers;
public class SetPasswordForUserEventHandler : INotificationHandler<SetPasswordForUserEvent>
{
@@ -1,18 +1,21 @@
namespace CMSMicroservice.Application.UserCQ.Queries.AdminGetJwtToken;
public class AdminGetJwtTokenQueryHandler : IRequestHandler<AdminGetJwtTokenQuery, AdminGetJwtTokenResponseDto>
{
private readonly IApplicationDbContext _context;
private readonly IGenerateJwtToken _generateJwt;
private readonly IHashService _hashService;
public AdminGetJwtTokenQueryHandler(IApplicationDbContext context, IGenerateJwtToken generateJwt, IHashService hashService)
public AdminGetJwtTokenQueryHandler(IApplicationDbContext context, IGenerateJwtToken generateJwt,
IHashService hashService)
{
_context = context;
_generateJwt = generateJwt;
_hashService = hashService;
}
public async Task<AdminGetJwtTokenResponseDto> Handle(AdminGetJwtTokenQuery request, CancellationToken cancellationToken)
public async Task<AdminGetJwtTokenResponseDto> Handle(AdminGetJwtTokenQuery request,
CancellationToken cancellationToken)
{
var user = await _context.Users
.Include(u => u.UserRoles)
@@ -21,14 +24,16 @@ public class AdminGetJwtTokenQueryHandler : IRequestHandler<AdminGetJwtTokenQuer
if (user == null)
throw new Exception("Invalid username or password.");
if (user.UserRoles.All(a => a.RoleId != 2))
throw new Exception("You do not have permission to do that.");
// verify password (supports PBKDF2 or legacy SHA-256)
if (!_hashService.VerifyPassword(request.Password, user.HashPassword))
throw new Exception("Invalid username or password.");
return new AdminGetJwtTokenResponseDto()
{
Token = await _generateJwt.GenerateJwtToken(user),
Token = await _generateJwt.GenerateJwtToken(user,15),
};
}
}
}