public void create(List<UserSearchModel> userSearchModels, HttpLocalizedOperationResult result) { if (userSearchModels.isEmpty()) { result.badRequest(LocalizedMessage.string("NO_USERS_SELECTED")); return; } synchronized (enableUserMutex) { for (UserSearchModel userSearchModel : userSearchModels) { User user = userSearchModel.getUser(); if (userExists(user)) { result.conflict( LocalizedMessage.string( "USER_ALREADY_EXISTS", user.getName(), user.getDisplayName(), user.getEmail())); return; } if (user.isAnonymous()) { result.badRequest(LocalizedMessage.string("USERNAME_NOT_PERMITTED", user.getName())); return; } if (!userSearchModel.getUserSourceType().equals(UserSourceType.PASSWORD_FILE) && validateEmailAndMatcher(result, user)) { return; } userDao.saveOrUpdate(user); result.setMessage(LocalizedMessage.string("USER_SUCCESSFULLY_ADDED", user.getName())); } } }
public ConfigUpdateResponse updateConfigFromUI( final UpdateConfigFromUI command, final String md5, Username username, final LocalizedOperationResult result) { UiBasedConfigUpdateCommand updateCommand = new UiBasedConfigUpdateCommand(md5, command, result, cachedGoPartials); UpdatedNodeSubjectResolver updatedConfigResolver = new UpdatedNodeSubjectResolver(); try { ConfigSaveState configSaveState = updateConfig(updateCommand); return latestUpdateResponse( command, updateCommand, updatedConfigResolver, clonedConfigForEdit(), configSaveState); } catch (ConfigFileHasChangedException e) { CruiseConfig updatedConfig = handleMergeException(md5, updateCommand); result.conflict(LocalizedMessage.string("SAVE_FAILED_WITH_REASON", e.getMessage())); return latestUpdateResponse( command, updateCommand, new OldNodeSubjectResolver(), updatedConfig, null); } catch (ConfigUpdateCheckFailedException e) { // result is already set } catch (Exception e) { ConfigMergeException mergeException = ExceptionUtils.getCause(e, ConfigMergeException.class); ConfigMergePostValidationException mergePostValidationException = ExceptionUtils.getCause(e, ConfigMergePostValidationException.class); if (mergeException != null || mergePostValidationException != null) { CruiseConfig updatedConfig = handleMergeException(md5, updateCommand); result.conflict(LocalizedMessage.string("SAVE_FAILED_WITH_REASON", e.getMessage())); return latestUpdateResponse( command, updateCommand, new OldNodeSubjectResolver(), updatedConfig, null); } GoConfigInvalidException ex = ExceptionUtils.getCause(e, GoConfigInvalidException.class); if (ex != null) { CruiseConfig badConfig = ex.getCruiseConfig(); setMD5(md5, badConfig); Validatable node = updatedConfigResolver.getNode(command, updateCommand.cruiseConfig()); BasicCruiseConfig.copyErrors(command.updatedNode(badConfig), node); result.badRequest(LocalizedMessage.string("SAVE_FAILED")); return new ConfigUpdateResponse( badConfig, node, subjectFromNode(command, updatedConfigResolver, node), updateCommand, null); } else { result.badRequest(LocalizedMessage.string("SAVE_FAILED_WITH_REASON", e.getMessage())); } } CruiseConfig newConfigSinceNoOtherConfigExists = clonedConfigForEdit(); setMD5(md5, newConfigSinceNoOtherConfigExists); return latestUpdateResponse( command, updateCommand, new OldNodeSubjectResolver(), newConfigSinceNoOtherConfigExists, null); }
public String configChangesFor( String laterMd5, String earlierMd5, LocalizedOperationResult result) { try { return configRepository.configChangesFor(laterMd5, earlierMd5); } catch (IllegalArgumentException e) { result.badRequest(LocalizedMessage.string("CONFIG_VERSION_NOT_FOUND")); } catch (Exception e) { result.internalServerError(LocalizedMessage.string("COULD_NOT_RETRIEVE_CONFIG_DIFF")); } return null; }
public void deleteUser(String username, HttpLocalizedOperationResult result) { try { userDao.deleteUser(username); result.setMessage(LocalizedMessage.string("USER_DELETE_SUCCESSFUL", username)); } catch (UserNotFoundException e) { result.notFound( LocalizedMessage.string("USER_NOT_FOUND", username), HealthStateType.general(HealthStateScope.GLOBAL)); } catch (UserEnabledException e) { result.badRequest(LocalizedMessage.string("USER_NOT_DISABLED", username)); } }
@Deprecated() public CruiseConfig loadCruiseConfigForEdit( Username username, HttpLocalizedOperationResult result) { if (!isUserAdmin(username) && !isUserTemplateAdmin(username)) { result.unauthorized( LocalizedMessage.string("UNAUTHORIZED_TO_ADMINISTER"), HealthStateType.unauthorised()); } return clonedConfigForEdit(); }
private boolean doesPipelineExist(String pipelineName, LocalizedOperationResult result) { if (!getCurrentConfig().hasPipelineNamed(new CaseInsensitiveString(pipelineName))) { result.notFound( LocalizedMessage.string("RESOURCE_NOT_FOUND", "pipeline", pipelineName), HealthStateType.general(HealthStateScope.forPipeline(pipelineName))); return false; } return true; }
private boolean isAuthorized() { if (!(goConfigService.isUserAdmin(username) || goConfigService.isGroupAdministrator(username.getUsername()))) { result.unauthorized( LocalizedMessage.string("UNAUTHORIZED_TO_EDIT"), HealthStateType.unauthorised()); return false; } return true; }
private boolean validateEmailAndMatcher(HttpLocalizedOperationResult result, User user) { try { validate(user); } catch (ValidationException e) { result.badRequest(LocalizedMessage.string("USER_FIELD_VALIDATIONS_FAILED", e.getMessage())); return true; } return false; }
private boolean isAdminOfGroup( String toGroupName, Username username, HttpLocalizedOperationResult result) { if (!isUserAdminOfGroup(username.getUsername(), toGroupName)) { result.unauthorized( LocalizedMessage.string("UNAUTHORIZED_TO_EDIT_GROUP", toGroupName), HealthStateType.unauthorised()); return false; } return true; }
private boolean isValidGroup( String groupName, CruiseConfig cruiseConfig, HttpLocalizedOperationResult result) { if (!cruiseConfig.hasPipelineGroup(groupName)) { result.notFound( LocalizedMessage.string("PIPELINE_GROUP_NOT_FOUND", groupName), HealthStateType.general(HealthStateScope.forGroup(groupName))); return false; } return true; }
@Override public boolean canContinue(CruiseConfig cruiseConfig) { if (goConfigService.groups().hasGroup(groupName) && !goConfigService.isUserAdminOfGroup(currentUser.getUsername(), groupName)) { result.unauthorized( LocalizedMessage.string("UNAUTHORIZED_TO_EDIT_GROUP", groupName), HealthStateType.unauthorised()); return false; } return true; }
public void modifyRolesAndUserAdminPrivileges( final List<String> users, final TriStateSelection adminPrivilege, final List<TriStateSelection> roleSelections, LocalizedOperationResult result) { Users allUsers = userDao.allUsers(); for (String user : users) { if (!allUsers.containsUserNamed(user)) { result.badRequest(LocalizedMessage.string("USER_DOES_NOT_EXIST_IN_DB", user)); return; } } try { final GoConfigDao.CompositeConfigCommand command = new GoConfigDao.CompositeConfigCommand(); command.addCommand(goConfigService.modifyRolesCommand(users, roleSelections)); command.addCommand(goConfigService.modifyAdminPrivilegesCommand(users, adminPrivilege)); goConfigService.updateConfig(command); } catch (Exception e) { result.badRequest(LocalizedMessage.string("INVALID_ROLE_NAME", e.getMessage())); } }
public boolean canEditPipeline( String pipelineName, Username username, LocalizedOperationResult result, String groupName) { if (!doesPipelineExist(pipelineName, result)) { return false; } if (!isUserAdminOfGroup(username.getUsername(), groupName)) { result.unauthorized( LocalizedMessage.string("UNAUTHORIZED_TO_EDIT_PIPELINE", pipelineName), HealthStateType.unauthorisedForPipeline(pipelineName)); return false; } return true; }
@Test public void shouldNotContinueIfTheUserDontHavePermissionsToOperateOnPackageRepositories() throws Exception { when(goConfigService.isUserAdmin(currentUser)).thenReturn(false); CreatePackageRepositoryCommand command = new CreatePackageRepositoryCommand( goConfigService, packageRepositoryService, packageRepository, currentUser, result); HttpLocalizedOperationResult expectedResult = new HttpLocalizedOperationResult(); expectedResult.unauthorized( LocalizedMessage.string("UNAUTHORIZED_TO_EDIT"), HealthStateType.unauthorised()); assertThat(command.canContinue(cruiseConfig), is(false)); assertThat(result, is(expectedResult)); }
@Test public void shouldNotBeAuthorizedToViewAPipeline() { when(securityService.hasViewPermissionForPipeline("pavan", "pipeline")).thenReturn(false); LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class); materialService.searchRevisions( "pipeline", "sha", "search-string", new Username(new CaseInsensitiveString("pavan")), operationResult); verify(operationResult) .unauthorized( LocalizedMessage.cannotViewPipeline("pipeline"), HealthStateType.general(HealthStateScope.forPipeline("pipeline"))); }
@Test public void shouldReturnNotFoundIfTheMaterialDoesNotBelongToTheGivenPipeline() { when(securityService.hasViewPermissionForPipeline("pavan", "pipeline")).thenReturn(true); LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class); when(goConfigService.materialForPipelineWithFingerprint("pipeline", "sha")) .thenThrow(new RuntimeException("Not found")); materialService.searchRevisions( "pipeline", "sha", "23", new Username(new CaseInsensitiveString("pavan")), operationResult); verify(operationResult) .notFound( LocalizedMessage.materialWithFingerPrintNotFound("pipeline", "sha"), HealthStateType.general(HealthStateScope.forPipeline("pipeline"))); }
public void disable(final List<String> usersToBeDisabled, LocalizedOperationResult result) { synchronized (disableUserMutex) { if (willDisableAllAdmins(usersToBeDisabled)) { result.badRequest(LocalizedMessage.string("CANNOT_DISABLE_LAST_ADMIN")); return; } transactionTemplate.execute( new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { userDao.disableUsers(usersToBeDisabled); oauthRepository.deleteUsersOauthGrants(usersToBeDisabled); } }); } }
public User update( final User user, TriState enabled, TriState emailMe, String email, String checkinAliases, LocalizedOperationResult result) { if (enabled.isTrue()) { user.enable(); } if (enabled.isFalse()) { user.disable(); } if (email != null) { user.setEmail(email); } if (checkinAliases != null) { user.setMatcher(checkinAliases); } if (emailMe.isTrue()) { user.setEmailMe(true); } if (emailMe.isFalse()) { user.setEmailMe(false); } try { saveOrUpdate(user); } catch (ValidationException e) { result.badRequest(LocalizedMessage.string("USER_FIELD_VALIDATIONS_FAILED", e.getMessage())); } return user; }
@Test public void shouldNotContinueIfTheUserSubmittedStaleEtag() throws Exception { when(goConfigService.isUserAdmin(currentUser)).thenReturn(true); when(goConfigService.getPackageRepository(repoId)).thenReturn(oldPackageRepo); when(entityHashingService.md5ForEntity(oldPackageRepo)).thenReturn("foobar"); HttpLocalizedOperationResult expectResult = new HttpLocalizedOperationResult(); expectResult.stale( LocalizedMessage.string("STALE_RESOURCE_CONFIG", "Package Repository", repoId)); UpdatePackageRepositoryCommand command = new UpdatePackageRepositoryCommand( goConfigService, packageRepositoryService, newPackageRepo, currentUser, "md5", entityHashingService, result, repoId); assertThat(command.canContinue(cruiseConfig), is(false)); assertThat(result, is(expectResult)); }
@Test public void shouldNotContinueIfRepoIdIsChanged() { when(goConfigService.isUserAdmin(currentUser)).thenReturn(true); when(goConfigService.getPackageRepository(repoId)).thenReturn(oldPackageRepo); when(entityHashingService.md5ForEntity(oldPackageRepo)).thenReturn("md5"); HttpLocalizedOperationResult expectResult = new HttpLocalizedOperationResult(); expectResult.unprocessableEntity( LocalizedMessage.string("PACKAGE_REPOSITORY_ID_CHANGED", "repository")); UpdatePackageRepositoryCommand command = new UpdatePackageRepositoryCommand( goConfigService, packageRepositoryService, newPackageRepo, currentUser, "md5", entityHashingService, result, "old-repo-id"); assertThat(command.canContinue(cruiseConfig), is(false)); assertThat(result, is(expectResult)); }