Esempio n. 1
0
  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()));
      }
    }
  }
Esempio n. 2
0
  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);
  }
Esempio n. 3
0
 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;
 }
Esempio n. 4
0
 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));
   }
 }
Esempio n. 5
0
 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;
 }
Esempio n. 7
0
 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;
 }
Esempio n. 8
0
 @Deprecated()
 public CruiseConfig loadCruiseConfigForEdit(
     Username username, HttpLocalizedOperationResult result) {
   if (!isUserAdmin(username) && !isUserTemplateAdmin(username)) {
     result.unauthorized(
         LocalizedMessage.string("UNAUTHORIZED_TO_ADMINISTER"), HealthStateType.unauthorised());
   }
   return clonedConfigForEdit();
 }
Esempio n. 9
0
 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;
 }
Esempio n. 10
0
 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;
 }
Esempio n. 11
0
 @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;
 }
Esempio n. 12
0
 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()));
   }
 }
Esempio n. 13
0
 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));
  }
Esempio n. 15
0
 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);
           }
         });
   }
 }
Esempio n. 16
0
  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));
  }