35 lines
1.3 KiB
C#
35 lines
1.3 KiB
C#
using MediatR;
|
|||
|
|
using mws.backend.dotnet.application.Audit;
|
||
|
|
using mws.backend.dotnet.application.Common;
|
||
|
|
using mws.backend.dotnet.application.Permissions;
|
||
|
|
using mws.backend.dotnet.domain.Users;
|
||
|
|
|
||
|
|
namespace mws.backend.dotnet.application.Users;
|
||
|
|
|
||
|
|
public record AssignUserRoleCommand(Guid ActorUserId, Guid TargetUserId, Guid RoleId) : IRequest, IAuditableRequest
|
||
|
|
{
|
||
|
|
public string Action => "User.AssignRole";
|
||
|
|
public string EntityType => "User";
|
||
|
|
public Guid? EntityId => TargetUserId;
|
||
|
|
}
|
||
|
|
|
||
|
|
public class AssignUserRoleHandler(IUnitOfWork uow, IPermissionService permissions, IAuditContext auditContext)
|
||
|
|
: IRequestHandler<AssignUserRoleCommand>
|
||
|
|
{
|
||
|
|
public async Task Handle(AssignUserRoleCommand command, CancellationToken ct)
|
||
|
|
{
|
||
|
|
await permissions.EnsureAsync(command.ActorUserId, "permissions", PermissionAction.Edit, ct);
|
||
|
|
|
||
|
|
var user = await uow.Users.GetByIdWithRoleAsync(command.TargetUserId, ct)
|
||
|
|
?? throw new NotFoundException("User not found");
|
||
|
|
|
||
|
|
if (user.UserRoles.All(ur => ur.RoleId != command.RoleId))
|
||
|
|
{
|
||
|
|
user.UserRoles.Add(new UserRole { UserId = command.TargetUserId, RoleId = command.RoleId });
|
||
|
|
await uow.SaveChangesAsync(ct);
|
||
|
|
}
|
||
|
|
|
||
|
|
auditContext.EntityName = user.Username;
|
||
|
|
}
|
||
|
|
}
|