Search in sources :

Example 1 with DuplicateExternalIdKeyException

use of com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException in project gerrit by GerritCodeReview.

the class AccountManager method create.

private AuthResult create(AuthRequest who) throws AccountException, IOException, ConfigInvalidException {
    Account.Id newId = Account.id(sequences.nextAccountId());
    logger.atFine().log("Assigning new Id %s to account", newId);
    ExternalId extId = externalIdFactory.createWithEmail(who.getExternalIdKey(), newId, who.getEmailAddress());
    logger.atFine().log("Created external Id: %s", extId);
    checkEmailNotUsed(newId, extId);
    ExternalId userNameExtId = who.getUserName().isPresent() ? createUsername(newId, who.getUserName().get()) : null;
    boolean isFirstAccount = awaitsFirstAccountCheck.getAndSet(false) && !accounts.hasAnyAccount();
    AccountState accountState;
    try {
        accountState = accountsUpdateProvider.get().insert("Create Account on First Login", newId, u -> {
            u.setFullName(who.getDisplayName()).setPreferredEmail(extId.email()).addExternalId(extId);
            if (userNameExtId != null) {
                u.addExternalId(userNameExtId);
            }
        });
    } catch (DuplicateExternalIdKeyException e) {
        throw new AccountException("Cannot assign external ID \"" + e.getDuplicateKey().get() + "\" to account " + newId + "; external ID already in use.");
    } finally {
        // If adding the account failed, it may be that it actually was the
        // first account. So we reset the 'check for first account'-guard, as
        // otherwise the first account would not get administration permissions.
        awaitsFirstAccountCheck.set(isFirstAccount);
    }
    if (userNameExtId != null) {
        who.getUserName().ifPresent(sshKeyCache::evict);
    }
    IdentifiedUser user = userFactory.create(newId);
    if (isFirstAccount) {
        // This is the first user account on our site. Assume this user
        // is going to be the site's administrator and just make them that
        // to bootstrap the authentication database.
        // 
        Permission admin = projectCache.getAllProjects().getConfig().getAccessSection(AccessSection.GLOBAL_CAPABILITIES).orElseThrow(() -> new IllegalStateException("access section does not exist")).getPermission(GlobalCapability.ADMINISTRATE_SERVER);
        AccountGroup.UUID adminGroupUuid = admin.getRules().get(0).getGroup().getUUID();
        addGroupMember(adminGroupUuid, user);
    }
    realm.onCreateAccount(who, accountState.account());
    return new AuthResult(newId, extId.key(), true);
}
Also used : ExternalIdKeyFactory(com.google.gerrit.server.account.externalids.ExternalIdKeyFactory) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) GlobalCapability(com.google.gerrit.common.data.GlobalCapability) ProjectCache(com.google.gerrit.server.project.ProjectCache) Inject(com.google.inject.Inject) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) GroupsUpdate(com.google.gerrit.server.group.db.GroupsUpdate) Strings(com.google.common.base.Strings) Config(org.eclipse.jgit.lib.Config) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) SCHEME_USERNAME(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME) ExternalIdFactory(com.google.gerrit.server.account.externalids.ExternalIdFactory) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) AccountGroup(com.google.gerrit.entities.AccountGroup) ImmutableSet(com.google.common.collect.ImmutableSet) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Sequences(com.google.gerrit.server.notedb.Sequences) SshKeyCache(com.google.gerrit.server.ssh.SshKeyCache) AccessSection(com.google.gerrit.entities.AccessSection) StorageException(com.google.gerrit.exceptions.StorageException) Collection(java.util.Collection) Permission(com.google.gerrit.entities.Permission) Account(com.google.gerrit.entities.Account) Set(java.util.Set) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) Objects(java.util.Objects) Consumer(java.util.function.Consumer) Provider(com.google.inject.Provider) List(java.util.List) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ServerInitiated(com.google.gerrit.server.ServerInitiated) Optional(java.util.Optional) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) VisibleForTesting(com.google.common.annotations.VisibleForTesting) DuplicateExternalIdKeyException(com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException) GroupDelta(com.google.gerrit.server.group.db.GroupDelta) FluentLogger(com.google.common.flogger.FluentLogger) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) DuplicateExternalIdKeyException(com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) AccountGroup(com.google.gerrit.entities.AccountGroup) Permission(com.google.gerrit.entities.Permission)

Example 2 with DuplicateExternalIdKeyException

use of com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException in project gerrit by GerritCodeReview.

the class AccountIT method externalIdBatchUpdates_fail_duplicateKey.

@Test
public void externalIdBatchUpdates_fail_duplicateKey() {
    ExternalId extIdAdmin = externalIdFactory.createWithEmail(externalIdKeyFactory.parse("foo:bar"), admin.id(), "1@foo.com");
    ExternalId extIdUser = externalIdFactory.createWithEmail(externalIdKeyFactory.parse("foo:bar"), user.id(), "2@foo.com");
    AccountsUpdate.UpdateArguments ua1 = new AccountsUpdate.UpdateArguments("Add External ID", admin.id(), (a, u) -> u.addExternalId(extIdAdmin));
    AccountsUpdate.UpdateArguments ua2 = new AccountsUpdate.UpdateArguments("Add External ID", user.id(), (a, u) -> u.addExternalId(extIdUser));
    DuplicateExternalIdKeyException e = assertThrows(DuplicateExternalIdKeyException.class, () -> accountsUpdateProvider.get().updateBatch(ImmutableList.of(ua1, ua2)));
    assertThat(e).hasMessageThat().contains("foo:bar");
}
Also used : DuplicateExternalIdKeyException(com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException) AccountsUpdate(com.google.gerrit.server.account.AccountsUpdate) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 3 with DuplicateExternalIdKeyException

use of com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException in project gerrit by GerritCodeReview.

the class CreateAccount method apply.

public Response<AccountInfo> apply(IdString id, AccountInput input) throws BadRequestException, ResourceConflictException, UnprocessableEntityException, IOException, ConfigInvalidException, PermissionBackendException {
    String username = applyCaseOfUsername(id.get());
    if (input.username != null && !username.equals(applyCaseOfUsername(input.username))) {
        throw new BadRequestException("username must match URL");
    }
    if (!ExternalId.isValidUsername(username)) {
        throw new BadRequestException("Invalid username '" + username + "'");
    }
    if (input.name == null) {
        input.name = input.username;
    }
    Set<AccountGroup.UUID> groups = parseGroups(input.groups);
    Account.Id accountId = Account.id(seq.nextAccountId());
    List<ExternalId> extIds = new ArrayList<>();
    if (input.email != null) {
        if (!validator.isValid(input.email)) {
            throw new BadRequestException("invalid email address");
        }
        extIds.add(externalIdFactory.createEmail(accountId, input.email));
    }
    extIds.add(externalIdFactory.createUsername(username, accountId, input.httpPassword));
    externalIdCreators.runEach(c -> extIds.addAll(c.create(accountId, username, input.email)));
    try {
        accountsUpdateProvider.get().insert("Create Account via API", accountId, u -> u.setFullName(input.name).setPreferredEmail(input.email).addExternalIds(extIds));
    } catch (DuplicateExternalIdKeyException e) {
        if (e.getDuplicateKey().isScheme(SCHEME_USERNAME)) {
            throw new ResourceConflictException("username '" + e.getDuplicateKey().id() + "' already exists");
        } else if (e.getDuplicateKey().isScheme(SCHEME_MAILTO)) {
            throw new UnprocessableEntityException("email '" + e.getDuplicateKey().id() + "' already exists");
        } else {
            // AccountExternalIdCreator returned an external ID that already exists
            throw e;
        }
    }
    for (AccountGroup.UUID groupUuid : groups) {
        try {
            addGroupMember(groupUuid, accountId);
        } catch (NoSuchGroupException e) {
            throw new UnprocessableEntityException(String.format("Group %s not found", groupUuid), e);
        }
    }
    if (input.sshKey != null) {
        try {
            authorizedKeys.addKey(accountId, input.sshKey);
            sshKeyCache.evict(username);
        } catch (InvalidSshKeyException e) {
            throw new BadRequestException(e.getMessage());
        }
    }
    AccountLoader loader = infoLoader.create(true);
    AccountInfo info = loader.get(accountId);
    loader.fill();
    return Response.created(info);
}
Also used : Account(com.google.gerrit.entities.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) DuplicateExternalIdKeyException(com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) IdString(com.google.gerrit.extensions.restapi.IdString) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) InvalidSshKeyException(com.google.gerrit.exceptions.InvalidSshKeyException) AccountGroup(com.google.gerrit.entities.AccountGroup) AccountLoader(com.google.gerrit.server.account.AccountLoader) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Aggregations

DuplicateExternalIdKeyException (com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException)3 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)3 Account (com.google.gerrit.entities.Account)2 AccountGroup (com.google.gerrit.entities.AccountGroup)2 NoSuchGroupException (com.google.gerrit.exceptions.NoSuchGroupException)2 ArrayList (java.util.ArrayList)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)1 Strings (com.google.common.base.Strings)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)1 Sets (com.google.common.collect.Sets)1 FluentLogger (com.google.common.flogger.FluentLogger)1 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)1 GlobalCapability (com.google.gerrit.common.data.GlobalCapability)1 AccessSection (com.google.gerrit.entities.AccessSection)1 Permission (com.google.gerrit.entities.Permission)1 InvalidSshKeyException (com.google.gerrit.exceptions.InvalidSshKeyException)1 StorageException (com.google.gerrit.exceptions.StorageException)1