Search in sources :

Example 96 with ResourceConflictException

use of com.google.gerrit.extensions.restapi.ResourceConflictException in project gerrit by GerritCodeReview.

the class DeleteEmail method apply.

public Response<?> apply(IdentifiedUser user, String email) throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException, IOException, ConfigInvalidException {
    Account.Id accountId = user.getAccountId();
    if (realm.accountBelongsToRealm(externalIds.byAccount(accountId)) && !realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
        throw new MethodNotAllowedException("realm does not allow deleting emails");
    }
    Set<ExternalId> extIds = externalIds.byAccount(accountId).stream().filter(e -> email.equals(e.email())).collect(toSet());
    if (extIds.isEmpty()) {
        throw new ResourceNotFoundException(email);
    }
    if (realm.accountBelongsToRealm(extIds)) {
        String errorMsg = String.format("Cannot remove e-mail '%s' which is directly associated with %s authentication", email, authType);
        throw new ResourceConflictException(errorMsg);
    }
    try {
        accountManager.unlink(user.getAccountId(), extIds.stream().map(ExternalId::key).collect(toSet()));
    } catch (AccountException e) {
        throw new ResourceConflictException(e.getMessage());
    }
    return Response.none();
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) AuthType(com.google.gerrit.extensions.client.AuthType) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Inject(com.google.inject.Inject) Input(com.google.gerrit.extensions.common.Input) Response(com.google.gerrit.extensions.restapi.Response) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) AuthException(com.google.gerrit.extensions.restapi.AuthException) Collectors.toSet(java.util.stream.Collectors.toSet) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResource(com.google.gerrit.server.account.AccountResource) Account(com.google.gerrit.entities.Account) Set(java.util.Set) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountException(com.google.gerrit.server.account.AccountException) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AuthConfig(com.google.gerrit.server.config.AuthConfig) Realm(com.google.gerrit.server.account.Realm) AccountManager(com.google.gerrit.server.account.AccountManager) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountException(com.google.gerrit.server.account.AccountException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 97 with ResourceConflictException

use of com.google.gerrit.extensions.restapi.ResourceConflictException in project gerrit by GerritCodeReview.

the class PutPreferred method apply.

public Response<String> apply(IdentifiedUser user, String preferredEmail) throws RestApiException, IOException, ConfigInvalidException {
    AtomicReference<Optional<RestApiException>> exception = new AtomicReference<>(Optional.empty());
    AtomicBoolean alreadyPreferred = new AtomicBoolean(false);
    Optional<AccountState> updatedAccount = accountsUpdateProvider.get().update("Set Preferred Email via API", user.getAccountId(), (a, u) -> {
        if (preferredEmail.equals(a.account().preferredEmail())) {
            alreadyPreferred.set(true);
        } else {
            // check if the user has a matching email
            String matchingEmail = null;
            for (String email : a.externalIds().stream().map(ExternalId::email).filter(Objects::nonNull).collect(toSet())) {
                if (email.equals(preferredEmail)) {
                    // we have an email that matches exactly, prefer this one
                    matchingEmail = email;
                    break;
                } else if (matchingEmail == null && email.equalsIgnoreCase(preferredEmail)) {
                    // we found an email that matches but has a different case
                    matchingEmail = email;
                }
            }
            if (matchingEmail == null) {
                // user doesn't have an external ID for this email
                if (user.hasEmailAddress(preferredEmail)) {
                    // but Realm says the user is allowed to use this email
                    Set<ExternalId> existingExtIdsWithThisEmail = externalIds.byEmail(preferredEmail);
                    if (!existingExtIdsWithThisEmail.isEmpty()) {
                        // but the email is already assigned to another account
                        logger.atWarning().log("Cannot set preferred email %s for account %s because it is owned" + " by the following account(s): %s", preferredEmail, user.getAccountId(), existingExtIdsWithThisEmail.stream().map(ExternalId::accountId).collect(toList()));
                        exception.set(Optional.of(new ResourceConflictException("email in use by another account")));
                        return;
                    }
                    // claim the email now
                    u.addExternalId(externalIdFactory.createEmail(a.account().id(), preferredEmail));
                    matchingEmail = preferredEmail;
                } else {
                    // Realm says that the email doesn't belong to the user. This can only
                    // happen as
                    // a race condition because EmailsCollection would have thrown
                    // ResourceNotFoundException already before invoking this REST endpoint.
                    exception.set(Optional.of(new ResourceNotFoundException(preferredEmail)));
                    return;
                }
            }
            u.setPreferredEmail(matchingEmail);
        }
    });
    if (!updatedAccount.isPresent()) {
        throw new ResourceNotFoundException("account not found");
    }
    if (exception.get().isPresent()) {
        throw exception.get().get();
    }
    return alreadyPreferred.get() ? Response.ok() : Response.created();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Optional(java.util.Optional) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AtomicReference(java.util.concurrent.atomic.AtomicReference) AccountState(com.google.gerrit.server.account.AccountState) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 98 with ResourceConflictException

use of com.google.gerrit.extensions.restapi.ResourceConflictException in project gerrit by GerritCodeReview.

the class AccountIT method cannotAddEmailAddressUsedByAnotherAccount.

@Test
public void cannotAddEmailAddressUsedByAnotherAccount() throws Exception {
    String email = "new.email@example.com";
    EmailInput input = newEmailInput(email);
    gApi.accounts().self().addEmail(input);
    ResourceConflictException thrown = assertThrows(ResourceConflictException.class, () -> gApi.accounts().id(user.username()).addEmail(input));
    assertThat(thrown).hasMessageThat().contains("Identity 'mailto:" + email + "' in use by another account");
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) EmailInput(com.google.gerrit.extensions.api.accounts.EmailInput) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 99 with ResourceConflictException

use of com.google.gerrit.extensions.restapi.ResourceConflictException in project gerrit by GerritCodeReview.

the class AccountIT method addOtherUsersGpgKey_Conflict.

@Test
public void addOtherUsersGpgKey_Conflict() throws Exception {
    AccountIndexedCounter accountIndexedCounter = new AccountIndexedCounter();
    try (Registration registration = extensionRegistry.newRegistration().add(accountIndexedCounter)) {
        // Both users have a matching external ID for this key.
        addExternalIdEmail(admin, "test5@example.com");
        accountIndexedCounter.clear();
        accountsUpdateProvider.get().update("Add External ID", user.id(), u -> u.addExternalId(externalIdFactory.create("foo", "myId", user.id())));
        accountIndexedCounter.assertReindexOf(user);
        TestKey key = validKeyWithSecondUserId();
        addGpgKey(key.getPublicKeyArmored());
        requestScopeOperations.setApiUser(user.id());
        ResourceConflictException thrown = assertThrows(ResourceConflictException.class, () -> addGpgKey(user, key.getPublicKeyArmored()));
        assertThat(thrown).hasMessageThat().contains("GPG key already associated with another account");
    }
}
Also used : AccountIndexedCounter(com.google.gerrit.acceptance.AccountIndexedCounter) TestKey(com.google.gerrit.gpg.testing.TestKey) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Registration(com.google.gerrit.acceptance.ExtensionRegistry.Registration) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 100 with ResourceConflictException

use of com.google.gerrit.extensions.restapi.ResourceConflictException in project gerrit by GerritCodeReview.

the class AccountIT method deactivateNotActive.

@Test
public void deactivateNotActive() throws Exception {
    int id = gApi.accounts().id("user").get()._accountId;
    assertThat(gApi.accounts().id("user").getActive()).isTrue();
    gApi.accounts().id("user").setActive(false);
    assertThat(gApi.accounts().id(id).getActive()).isFalse();
    ResourceConflictException thrown = assertThrows(ResourceConflictException.class, () -> gApi.accounts().id(id).setActive(false));
    assertThat(thrown).hasMessageThat().isEqualTo("account not active");
    gApi.accounts().id(id).setActive(true);
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Fingerprint(com.google.gerrit.gpg.Fingerprint) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Aggregations

ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)252 Test (org.junit.Test)106 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)102 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)57 AuthException (com.google.gerrit.extensions.restapi.AuthException)46 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)44 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)42 IOException (java.io.IOException)39 ObjectId (org.eclipse.jgit.lib.ObjectId)36 Repository (org.eclipse.jgit.lib.Repository)34 Change (com.google.gerrit.entities.Change)29 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)28 RevCommit (org.eclipse.jgit.revwalk.RevCommit)27 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)26 RevWalk (org.eclipse.jgit.revwalk.RevWalk)25 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)23 ArrayList (java.util.ArrayList)21 PatchSet (com.google.gerrit.entities.PatchSet)20 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)20 ProjectState (com.google.gerrit.server.project.ProjectState)19