Spaces:
Runtime error
Runtime error
Download src/SCM.Application/Users/UserService.cs from rafaeldavila/scm-api: direct link, hf CLI and curl.
- Browser
- Download file 4.25 kB
-
https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Application/Users/UserService.cs
- Command line
-
hf download hf://spaces/rafaeldavila/scm-api/src/SCM.Application/Users/UserService.cs
-
curl -L -o UserService.cs https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Application/Users/UserService.cs
4.25 kB
| using SCM.Application.Authentication; | |
| using SCM.Application.Common; | |
| using SCM.Domain.Users; | |
| using SCM.Shared.Constants; | |
| using SCM.Shared.Exceptions; | |
| namespace SCM.Application.Users; | |
| public sealed record CreateUserRequest(string Username, string Email, string Role, string Password); | |
| public sealed record UpdateUserRequest(string Email, string Role, bool IsActive); | |
| public sealed record ResetPasswordRequest(string Password); | |
| public sealed record UserResponse(Guid Id, string Username, string Email, string Role, bool IsActive, DateTime CreatedAt); | |
| public interface IUserService | |
| { | |
| Task<IReadOnlyList<UserResponse>> GetAllAsync(CancellationToken ct = default); | |
| Task<UserResponse> CreateAsync(CreateUserRequest request, CancellationToken ct = default); | |
| Task<UserResponse> UpdateAsync(Guid id, UpdateUserRequest request, CancellationToken ct = default); | |
| Task ResetPasswordAsync(Guid id, ResetPasswordRequest request, CancellationToken ct = default); | |
| } | |
| /// <summary> | |
| /// Administração de usuários/perfis (7ª passada / A.4). RBAC de papel único por usuário. | |
| /// Senhas são hasheadas com o mesmo IPasswordHasherService usado no login. | |
| /// </summary> | |
| public sealed class UserService : IUserService | |
| { | |
| private readonly IUserRepository _repository; | |
| private readonly IPasswordHasherService _hasher; | |
| private readonly IUnitOfWork _unitOfWork; | |
| public UserService(IUserRepository repository, IPasswordHasherService hasher, IUnitOfWork unitOfWork) | |
| { | |
| _repository = repository; | |
| _hasher = hasher; | |
| _unitOfWork = unitOfWork; | |
| } | |
| public async Task<IReadOnlyList<UserResponse>> GetAllAsync(CancellationToken ct = default) | |
| => (await _repository.GetAllAsync(ct)).Select(ToResponse).ToList(); | |
| public async Task<UserResponse> CreateAsync(CreateUserRequest r, CancellationToken ct = default) | |
| { | |
| if (string.IsNullOrWhiteSpace(r.Password) || r.Password.Length < 6) | |
| throw new DomainException("A senha deve ter ao menos 6 caracteres."); | |
| if (await _repository.UsernameExistsAsync(r.Username.Trim(), ct)) | |
| throw new ConflictException($"Já existe usuário '{r.Username}'."); | |
| var user = User.Create(r.Username, r.Email, r.Role, _hasher.Hash(r.Password), DateTime.UtcNow); | |
| await ExecuteInTransactionAsync(() => _repository.AddAsync(user, ct)); | |
| return ToResponse(user); | |
| } | |
| public async Task<UserResponse> UpdateAsync(Guid id, UpdateUserRequest r, CancellationToken ct = default) | |
| { | |
| var user = await _repository.GetByIdAsync(id, ct) | |
| ?? throw new NotFoundException($"Usuário {id} não encontrado."); | |
| // Trava de segurança: não permitir desativar/rebaixar o último Administrador ativo. | |
| if (user.Role == Roles.Administrador && (r.Role != Roles.Administrador || !r.IsActive)) | |
| { | |
| var admins = (await _repository.GetAllAsync(ct)) | |
| .Count(u => u.Role == Roles.Administrador && u.IsActive); | |
| if (admins <= 1) | |
| throw new DomainException("Não é possível remover/desativar o último administrador ativo."); | |
| } | |
| user.Atualizar(r.Email, r.Role); | |
| user.DefinirAtivo(r.IsActive); | |
| await ExecuteInTransactionAsync(() => _repository.UpdateAsync(user, ct)); | |
| return ToResponse(user); | |
| } | |
| public async Task ResetPasswordAsync(Guid id, ResetPasswordRequest r, CancellationToken ct = default) | |
| { | |
| var user = await _repository.GetByIdAsync(id, ct) | |
| ?? throw new NotFoundException($"Usuário {id} não encontrado."); | |
| if (string.IsNullOrWhiteSpace(r.Password) || r.Password.Length < 6) | |
| throw new DomainException("A senha deve ter ao menos 6 caracteres."); | |
| user.RedefinirSenha(_hasher.Hash(r.Password)); | |
| await ExecuteInTransactionAsync(() => _repository.UpdateAsync(user, ct)); | |
| } | |
| private static UserResponse ToResponse(User u) => | |
| new(u.Id, u.Username, u.Email, u.Role, u.IsActive, u.CreatedAt); | |
| private async Task ExecuteInTransactionAsync(Func<Task> action) | |
| { | |
| _unitOfWork.BeginTransaction(); | |
| try { await action(); _unitOfWork.Commit(); } | |
| catch { _unitOfWork.Rollback(); throw; } | |
| } | |
| } | |