public IActionResult PatchTaxonomy([FromRoute] int id, TaxonomyRequest taxonomyRequest) { try { var response = _taxonomyUseCase.ExecutePatch(id, taxonomyRequest); if (response != null) { return(Ok(response)); } } catch (InvalidOperationException e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); return(BadRequest( new ErrorResponse($"Error updating taxonomy") { Status = "Bad request", Errors = new List <string> { $"An error occurred attempting to update taxonomy {id}: {e.Message}" } })); } return(BadRequest( new ErrorResponse($"Invalid request. ") { Status = "Bad request", Errors = new List <string> { "Unable to update taxonomy." } })); }
public IActionResult DeleteOrganisation([FromRoute] int id) { //add validation try { UserClaims userClaims = new UserClaims { UserId = int.Parse(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value), UserRole = HttpContext.User.FindFirst(ClaimTypes.Role).Value }; LambdaLogger.Log($"UserID:{userClaims.UserId.ToString()} UserRole:{userClaims.UserRole}"); _organisationsUseCase.ExecuteDelete(id, userClaims); return(Ok()); } catch (InvalidOperationException e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); return(BadRequest( new ErrorResponse($"Error deleting organisation") { Status = "Bad request", Errors = new List <string> { $"An error occurred attempting to delete organisation {id}: {e.Message}" } })); } catch (UseCaseException e) { return(BadRequest(e)); } }
public IActionResult DeleteTaxonomy([FromRoute] int id) { try { _taxonomyUseCase.ExecuteDelete(id); return(Ok()); } catch (InvalidOperationException e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); return(BadRequest( new ErrorResponse($"Error deleting taxonomy") { Status = "Bad request", Errors = new List <string> { $"An error occurred attempting to delete taxonomy {id}: {e.Message}" } })); } catch (UseCaseException e) { return(BadRequest(e)); } catch (ServiceTaxonomyExistsException ex) { var errorResponse = new ServiceErrorResponse { ErrorMessage = ex.DevErrorMessage, Services = ex.Services }; return(BadRequest(errorResponse)); } }
public SynonymGroupDomain PatchSynonymGroup(SynonymGroupDomain synonymGroupDomain) { try { var sg = Context.SynonymGroups .Include(o => o.SynonymWords) .FirstOrDefault(o => o.Id == synonymGroupDomain.Id); sg.Name = synonymGroupDomain.Name; sg.CreatedAt = synonymGroupDomain.CreatedAt; Context.SynonymGroups.Attach(sg); SaveChanges(); return(_mapper.ToDomain(sg)); } catch (DbUpdateException dbe) { HandleDbUpdateException(dbe); throw; } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public async Task <List <AddressXRef> > GetAddressXrefs(string uprn) { try { var response = await _client.GetAsync(new Uri($"properties/{uprn}/crossreferences", UriKind.Relative)).ConfigureAwait(true); if (!response.IsSuccessStatusCode) { throw new Exception(response.ReasonPhrase); } var content = await response.Content.ReadAsStringAsync().ConfigureAwait(true); var addressXRefDomain = JsonConvert.DeserializeObject <AddressXRefAPIResponse>(content); var addressXRef = addressXRefDomain.Data.AddressCrossReferences; if (addressXRef != null) { return(addressXRef); } return(null); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); return(null); } }
public UserResponse Execute(UserCreateRequest createRequestData) { string createdUserId = null; try { createdUserId = _authGateway.CreateUser(createRequestData); } catch (AmazonCognitoIdentityProviderException e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); return(null); } var userDomain = SaveNewUser(createRequestData, createdUserId); var userCreateResponse = new UserResponse { Id = userDomain.Id, CreatedAt = userDomain.CreatedAt, Email = createRequestData.Email, Name = createRequestData.Name, SubId = createdUserId, Status = userDomain.Status }; return(userCreateResponse); }
public SynonymWordDomain PatchSynonymWord(SynonymWordDomain synonymWordDomain) { try { var sw = Context.SynonymWords .FirstOrDefault(o => o.Id == synonymWordDomain.Id); sw.Word = synonymWordDomain.Word; sw.GroupId = synonymWordDomain.GroupId; sw.CreatedAt = synonymWordDomain.CreatedAt; Context.SynonymWords.Attach(sw); SaveChanges(); return(_mapper.ToDomain(sw)); } catch (DbUpdateException dbe) { HandleDbUpdateException(dbe); throw; } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public TaxonomyDomain PatchTaxonomy(int id, Taxonomy taxonomy) { try { var taxonomyEntity = Context.Taxonomies .Include(o => o.ServiceTaxonomies) .FirstOrDefault(o => o.Id == id); if (taxonomy == null) { throw new InvalidOperationException("Taxonomy does not exist"); } taxonomyEntity.Name = taxonomy.Name; taxonomyEntity.Description = taxonomy.Description; taxonomyEntity.Vocabulary = taxonomy.Vocabulary; taxonomyEntity.Weight = taxonomy.Weight; Context.SaveChanges(); return(_mapper.ToDomain(taxonomyEntity)); } catch (DbUpdateException dbe) { HandleDbUpdateException(dbe); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } return(null); }
public UserDomain SetDefaultRole(UserDomain user) { try { var defaultRole = Context.Roles.FirstOrDefault(x => x.Name.ToUpper() == "VCSO"); if (defaultRole == null) { throw new InvalidOperationException("The role specified does not exist."); } var userRole = new UserRole { RoleId = defaultRole.Id, UserId = user.Id, Role = defaultRole, CreatedAt = DateTime.Now }; Context.UserRoles.Add(userRole); Context.SaveChanges(); var domainUser = Context.Users .Include(u => u.UserRoles) .ThenInclude(ur => ur.Role) .FirstOrDefault(u => u.Id == user.Id); return(_mapper.ToDomain(domainUser)); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public async Task DeleteFileInfo(int serviceId, File file) { try { var service = Context.Services.FirstOrDefault(s => s.Id == serviceId); if (service == null) { LoggingHandler.LogError("The specified service does not exist"); throw new UseCaseException() { UserErrorMessage = "The specified service does not exist" }; } service.ImageId = null; Context.Services.Attach(service); await Context.SaveChangesAsync().ConfigureAwait(false); Context.Files.Remove(file); await Context.SaveChangesAsync().ConfigureAwait(false); LoggingHandler.LogInfo("Image deleted successfully."); } catch (Exception e) { LoggingHandler.LogError("Error deleting image"); LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public AuthenticationResult ChallengePassword(ResetPasswordQueryParams resetPasswordQueryParams) { RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest { ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED, ChallengeResponses = new Dictionary <string, string> { { "NEW_PASSWORD", resetPasswordQueryParams.Password }, { "USERNAME", resetPasswordQueryParams.Email } }, ClientId = _connectionInfo.ClientId, Session = resetPasswordQueryParams.Session }; var authResult = new AuthenticationResult(); try { var authResp = _provider.RespondToAuthChallengeAsync(authChallengeRequest).Result; authResult.AccessToken = authResp.AuthenticationResult.AccessToken; authResult.IdToken = authResp.AuthenticationResult.IdToken; authResult.RefreshToken = authResp.AuthenticationResult.RefreshToken; authResult.TokenType = authResp.AuthenticationResult.TokenType; authResult.ExpiresIn = authResp.AuthenticationResult.ExpiresIn; authResult.Success = true; } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } return(authResult); }
public UserDomain AddUser(UserDomain userDomain) { // POST /registration // Adds basic user record for registration process try { var userEntity = userDomain.ToEntity(); Context.Users.Add(userEntity); Context.SaveChanges(); userDomain = _mapper.ToDomain(userEntity); return(userDomain); } catch (DbUpdateException dbe) { HandleDbUpdateException(dbe); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } return(null); }
public void DeleteOrganisation(int id) { try { var organisation = Context.Organisations .Include(o => o.UserOrganisations) .Include(o => o.Services) .ThenInclude(s => s.ServiceLocations) .Include(o => o.Services) .ThenInclude(s => s.ServiceTaxonomies) .FirstOrDefault(o => o.Id == id); if (organisation == null) { throw new InvalidOperationException("Organisation does not exist"); } Context.Organisations.Remove(organisation); SaveChanges(); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public LoginUserQueryParam ChangePassword(ResetPasswordQueryParams changePasswordParams) { var userPool = new CognitoUserPool(_connectionInfo.UserPoolId, _connectionInfo.ClientId, _provider); var cognitoUser = new CognitoUser(changePasswordParams.Email, _connectionInfo.ClientId, userPool, _provider); try { AuthFlowResponse authResponse = null; authResponse = cognitoUser.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = changePasswordParams.Password }).Result; while (authResponse.AuthenticationResult == null) { if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { authResponse = cognitoUser.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest() { SessionID = authResponse.SessionID, NewPassword = changePasswordParams.NewPassword, }).Result; } } if (authResponse.AuthenticationResult != null) { LoggingHandler.LogInfo("User successfully authenticated."); var loginParams = new LoginUserQueryParam(); loginParams.Email = changePasswordParams.Email; loginParams.Password = changePasswordParams.NewPassword; return(loginParams); } else { LoggingHandler.LogError("Error in authentication process."); } } catch (AggregateException e) { e.Handle((x) => { if (x is NotAuthorizedException) // This we know how to handle. { LoggingHandler.LogInfo("Authentication Gateway: Invalid credentials provided."); return(true); } if (x is UserNotFoundException) // This we know how to handle. { LoggingHandler.LogInfo("Authentication Gateway: User not found."); return(true); } return(false); // Let anything else stop the application. }); } return(null); }
public OrganisationDomain PatchOrganisation(OrganisationDomain organisationDomain) { try { var org = Context.Organisations .Include(o => o.ReviewerU) .FirstOrDefault(o => o.Id == organisationDomain.Id); org.Name = organisationDomain.Name; org.CreatedAt = organisationDomain.CreatedAt; org.UpdatedAt = organisationDomain.UpdatedAt; org.SubmittedAt = organisationDomain.SubmittedAt; org.ReviewedAt = organisationDomain.ReviewedAt; org.ReviewerMessage = organisationDomain.ReviewerMessage; org.Status = organisationDomain.Status; org.IsRegisteredCharity = organisationDomain.IsRegisteredCharity; org.CharityNumber = organisationDomain.CharityNumber; org.IsRegisteredCommunityInterestCompany = organisationDomain.IsRegisteredCommunityInterestCompany; org.CommunityInterestCompanyNumber = organisationDomain.CommunityInterestCompanyNumber; org.HasHcOrColGrant = organisationDomain.HasHcOrColGrant; org.HasHcvsOrHgOrAelGrant = organisationDomain.HasHcvsOrHgOrAelGrant; org.IsTraRegistered = organisationDomain.IsTraRegistered; org.IsHackneyBased = organisationDomain.IsHackneyBased; org.RslOrHaAssociation = organisationDomain.RslOrHaAssociation; org.IsLotteryFunded = organisationDomain.IsLotteryFunded; org.LotteryFundedProject = organisationDomain.LotteryFundedProject; org.FundingOther = organisationDomain.FundingOther; org.HasChildSupport = organisationDomain.HasChildSupport; org.ChildSafeguardingLeadFirstName = organisationDomain.ChildSafeguardingLeadFirstName; org.ChildSafeguardingLeadLastName = organisationDomain.ChildSafeguardingLeadLastName; org.ChildSafeguardingLeadTrainingMonth = organisationDomain.ChildSafeguardingLeadTrainingMonth; org.ChildSafeguardingLeadTrainingYear = organisationDomain.ChildSafeguardingLeadTrainingYear; org.HasAdultSupport = organisationDomain.HasAdultSupport; org.HasAdultSafeguardingLead = organisationDomain.HasAdultSafeguardingLead; org.AdultSafeguardingLeadFirstName = organisationDomain.AdultSafeguardingLeadFirstName; org.AdultSafeguardingLeadLastName = organisationDomain.AdultSafeguardingLeadLastName; org.AdultSafeguardingLeadTrainingMonth = organisationDomain.AdultSafeguardingLeadTrainingMonth; org.AdultSafeguardingLeadTrainingYear = organisationDomain.AdultSafeguardingLeadTrainingYear; org.HasEnhancedSupport = organisationDomain.HasEnhancedSupport; org.IsLocalOfferListed = organisationDomain.IsLocalOfferListed; org.ReviewerUid = organisationDomain.ReviewerUid; Context.Organisations.Attach(org); SaveChanges(); return(_mapper.ToDomain(org)); } catch (DbUpdateException dbe) { HandleDbUpdateException(dbe); throw; } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public void UpdateUserAndRoles(UserDomain userDomain) { // PATCH /users try { var userEntity = Context.Users.FirstOrDefault(u => u.Id == userDomain.Id); if (userEntity == null) { throw new UseCaseException { UserErrorMessage = $"User with ID '{userDomain.Id}' could not be found" } } ; userEntity.Email = userDomain.Email; userEntity.Name = userDomain.Name; userEntity.Status = userDomain.Status; userEntity.CreatedAt = userDomain.CreatedAt; userEntity.SubId = userDomain.SubId; Context.SaveChanges(); // add any role associations this user does not already have if (userDomain.UserRoles != null) { // Since we are updating the user, clear any current role associations even if the request // contains an empty list of roles. The behaviour is to clear the associated roles if an empty // list of roles is provided ClearUserRoles(userEntity.Id); var rolesInDomain = GetRoleNamesFromUserDomain(userDomain); if (rolesInDomain != null) { // add any valid new roles var validRoles = UserRoleValidator.ToValidList(rolesInDomain); if (validRoles.Any()) { AddRolesToUser(userEntity.Id, validRoles); } } } } catch (DbUpdateException dbe) { HandleDbUpdateException(dbe); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public OrganisationDomain AssociateUserWithOrganisation(int userId, int organisationId) { OrganisationDomain response = null; try { // check organisation actually exists before creating association in database var orgEntity = Context.Organisations.FirstOrDefault(o => o.Id == organisationId); if (orgEntity == null) { throw new UseCaseException() { UserErrorMessage = $"The supplied organisation ID '{organisationId}' was not found", DevErrorMessage = $"The [organisations] table does not contain an organisation with ID = {organisationId}" }; } var userOrg = Context.UserOrganisations.FirstOrDefault(u => u.UserId == userId); // check if an association already exists and modify this one if it does if (userOrg != null) { userOrg.OrganisationId = organisationId; Context.UserOrganisations.Update(userOrg); } else { // create new organisation <-> user association userOrg = new UserOrganisation() { CreatedAt = DateTime.UtcNow, UserId = userId, OrganisationId = organisationId }; Context.UserOrganisations.Add(userOrg); } Context.SaveChanges(); response = _mapper.ToDomain(orgEntity); } catch (DbUpdateException e) { HandleDbUpdateException(e); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } return(response); }
public async Task SendMessage(NotifyMessageTypes messageType, string[] addresses, string message) { if (messageType == null || addresses == null) { LoggingHandler.LogError("Notify request with invalid arguments"); throw new ArgumentException("Notify request with invalid arguments"); } var template = string.Empty; var personalisation = new Dictionary <string, dynamic>(); switch (messageType) { case NotifyMessageTypes.Reminder: template = _reminderTemplate; break; case NotifyMessageTypes.AdminNotification: template = _adminNotificationTemplate; break; case NotifyMessageTypes.StatusUpdate: template = _statusTemplate; break; case NotifyMessageTypes.NotReverified: template = _notReverifiedTemplate; break; case NotifyMessageTypes.NotApproved: template = _notApprovedTemplate; personalisation.Add("status_message", message ?? ""); break; } try { for (int a = 0; a < addresses.Length; a++) { await _client.SendEmailAsync(addresses[a], template, personalisation).ConfigureAwait(false); } } catch (NotifyClientException e) { LoggingHandler.LogError("Gov Notify send error"); LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public async Task <IDictionary <string, string[]> > ReadSpreadsheetAsync(string spreadSheetId, string sheetName, string sheetRange, string googleApiKey) { LoggingHandler.LogInfo("Initialise Google API."); await _googleClient.InitialiseWithGoogleApiKey(googleApiKey).ConfigureAwait(false); LoggingHandler.LogInfo("Initialisation complete. Getting spreadsheet rows."); IList <IList <object> > values = await _googleClient.ReadSheetToObjectRowListAsync(spreadSheetId, sheetName, sheetRange).ConfigureAwait(false); if (values == null || !values.Any()) { LoggingHandler.LogError("No data found. Unresolved issue, so just return without making any updates."); return(null); } LoggingHandler.LogInfo("Spreadsheet rows received. Parsing data."); //Start Synonyms IDictionary <string, string[]> synonymGroups = new Dictionary <string, string[]>(); foreach (IList <object> row in values.Skip(2)) { if (row.Count > 1) { try { string synonymGroupName = row[0].ToString().Trim(); if (synonymGroupName.Length > 0) { List <string> words = new List <string>(); foreach (object cell in row) //Include group name. { if (cell != null) { string word = cell.ToString().Trim(); if (word.Length > 0) { words.Add(word); } } } synonymGroups.Add(synonymGroupName, words.ToArray()); } } catch (NullReferenceException e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); Debugger.Break(); } } } return(synonymGroups); }
public List <TaxonomyDomain> GetTaxonomiesByVocabulary(string vocabulary) { try { var taxonomies = Context.Taxonomies.Where(x => x.Vocabulary == vocabulary); return(_mapper.ToDomain(taxonomies)); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public List <TaxonomyDomain> GetAllTaxonomies() { try { var taxonomies = Context.Taxonomies.AsQueryable(); return(_mapper.ToDomain(taxonomies)); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public UserDomain AddUser(AdminCreateUserRequest requestData, string subId) { // POST /users UserDomain userDomain = null; var userEntity = new User() { CreatedAt = requestData.CreatedAt.HasValue ? requestData.CreatedAt : DateTime.UtcNow, Email = requestData.Email, Name = requestData.Name, Status = requestData.Status, SubId = subId }; try { // add the user Context.Users.Add(userEntity); Context.SaveChanges(); if (requestData.OrganisationId.HasValue) { AssociateUserWithOrganisation(userEntity.Id, requestData.OrganisationId.Value); } if (requestData.Roles != null) { var validatedRoles = UserRoleValidator.ToValidList(requestData.Roles); AddRolesToUser(userEntity.Id, validatedRoles); } // refresh the user domain object userDomain = GetUserById(userEntity.Id); } catch (DbUpdateException dbe) { HandleDbUpdateException(dbe); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } return(userDomain); }
public void BaseTearDown() { Client.Dispose(); _factory.Dispose(); try { _transaction.Rollback(); } catch (InvalidOperationException e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); } _transaction.Dispose(); }
public TaxonomyDomain CreateTaxonomy(Taxonomy request) { try { Context.Taxonomies.Add(request); SaveChanges(); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } return(_mapper.ToDomain(request)); }
public TaxonomyDomain GetTaxonomy(int id) { try { var taxonomy = Context.Taxonomies .FirstOrDefault(o => o.Id == id); return(_mapper.ToDomain(taxonomy)); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public SynonymWordDomain GetSynonymWord(int id) { try { var synonymWord = Context.SynonymWords .FirstOrDefault(o => o.Id == id); return(_mapper.ToDomain(synonymWord)); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }
public SynonymWordDomain CreateSynonymWord(SynonymWord request) { try { Context.SynonymWords.Add(request); SaveChanges(); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } return(_mapper.ToDomain(request)); }
public OrganisationDomain CreateOrganisation(Organisation request) { try { Context.Organisations.Add(request); SaveChanges(); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } return(_mapper.ToDomain(request)); }
public void ExecutePasswordRecoveryConfirmation(ResetPasswordQueryParams queryParams) { try { _authenticateGateway.ConfirmResetPassword(queryParams); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw new UseCaseException() { UserErrorMessage = "Unable to execute password recovery confirmation" }; } }
public List <ServiceTaxonomyDomain> GetServiceTaxonomies(int taxonomyId) { try { var serviceTaxonomies = Context.ServiceTaxonomies .Where(x => x.TaxonomyId == taxonomyId) .Include(x => x.Service); return(_mapper.ToDomain(serviceTaxonomies)); } catch (Exception e) { LoggingHandler.LogError(e.Message); LoggingHandler.LogError(e.StackTrace); throw; } }