0
0
mirror of https://github.com/alex289/CleanArchitecture.git synced 2025-07-04 12:32:57 +00:00
CleanArchitecture/CleanArchitecture.Domain/Commands/Users/DeleteUser/DeleteUserCommandHandler.cs
Alexander Konietzko b36aaff112
Add User auth
2023-03-17 08:44:51 +01:00

62 lines
1.8 KiB
C#

using System.Threading;
using System.Threading.Tasks;
using CleanArchitecture.Domain.Enums;
using CleanArchitecture.Domain.Errors;
using CleanArchitecture.Domain.Events.User;
using CleanArchitecture.Domain.Interfaces;
using CleanArchitecture.Domain.Interfaces.Repositories;
using CleanArchitecture.Domain.Notifications;
using MediatR;
namespace CleanArchitecture.Domain.Commands.Users.DeleteUser;
public sealed class DeleteUserCommandHandler : CommandHandlerBase,
IRequestHandler<DeleteUserCommand>
{
private readonly IUserRepository _userRepository;
private readonly IUser _user;
public DeleteUserCommandHandler(
IMediatorHandler bus,
IUnitOfWork unitOfWork,
INotificationHandler<DomainNotification> notifications,
IUserRepository userRepository,
IUser user) : base(bus, unitOfWork, notifications)
{
_userRepository = userRepository;
_user = user;
}
public async Task Handle(DeleteUserCommand request, CancellationToken cancellationToken)
{
if (!await TestValidityAsync(request))
{
return;
}
var user = await _userRepository.GetByIdAsync(request.UserId);
if (user == null)
{
await NotifyAsync(
new DomainNotification(
request.MessageType,
$"There is no User with Id {request.UserId}",
ErrorCodes.ObjectNotFound));
return;
}
if (_user.GetUserId() != request.UserId || _user.GetUserRole() != UserRole.Admin)
{
return;
}
_userRepository.Remove(user);
if (await CommitAsync())
{
await _bus.RaiseEventAsync(new UserDeletedEvent(request.UserId));
}
}
}