public Task <Result> Set(int agencyId, int agentId, ApiClientData clientData) { return(Validate() .BindWithTransaction(_context, () => SetClient() .Bind(WriteAuditLog))); async Task <Result> Validate() { var doesAgencyExist = await _context.AgentAgencyRelations .AnyAsync(r => r.AgencyId == agencyId && r.AgentId == agentId); return(doesAgencyExist ? Result.Success() : Result.Failure("Could not find agent and agency")); } async Task <Result> SetClient() { var existingClient = await _context.ApiClients .SingleOrDefaultAsync(a => a.AgentId == agentId && a.AgencyId == agencyId); if (existingClient is null) { var doesSameNameClientExist = await _context.ApiClients.AnyAsync(a => a.Name == clientData.Name); if (doesSameNameClientExist) { return(Result.Failure("Client with same name already exists")); } _context.ApiClients.Add(new ApiClient { AgentId = agentId, AgencyId = agencyId, Name = clientData.Name, PasswordHash = HashGenerator.ComputeSha256(clientData.Password) }); } else { existingClient.Name = clientData.Name; existingClient.PasswordHash = HashGenerator.ComputeSha256(clientData.Password); _context.Update(existingClient); } await _context.SaveChangesAsync(); return(Result.Success()); } Task <Result> WriteAuditLog() => _managementAuditService.Write(ManagementEventType.AgentApiClientCreateOrEdit, new AgentApiClientEventData(agentId, agencyId)); }
public async Task <IActionResult> SetApiClient([FromRoute] int agentId, [FromRoute] int agencyId, [FromBody] ApiClientData apiClientData) { var(_, isFailure, error) = await _apiClientManagementService.Set(agencyId, agentId, apiClientData); if (isFailure) { return(BadRequest(ProblemDetailsBuilder.Build(error))); } return(Ok()); }