Search in sources :

Example 21 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException in project gerrit by GerritCodeReview.

the class AccountCreator method addGroupMember.

private void addGroupMember(AccountGroup.UUID groupUuid, Account.Id accountId) throws IOException, NoSuchGroupException, ConfigInvalidException {
    GroupDelta groupDelta = GroupDelta.builder().setMemberModification(memberIds -> Sets.union(memberIds, ImmutableSet.of(accountId))).build();
    groupsUpdateProvider.get().updateGroup(groupUuid, groupDelta);
}
Also used : InternalGroup(com.google.gerrit.entities.InternalGroup) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) Inject(com.google.inject.Inject) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) GroupsUpdate(com.google.gerrit.server.group.db.GroupsUpdate) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) Map(java.util.Map) ExternalIdFactory(com.google.gerrit.server.account.externalids.ExternalIdFactory) AccountsUpdate(com.google.gerrit.server.account.AccountsUpdate) AccountGroup(com.google.gerrit.entities.AccountGroup) ImmutableSet(com.google.common.collect.ImmutableSet) Sequences(com.google.gerrit.server.notedb.Sequences) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) Provider(com.google.inject.Provider) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) ServerInitiated(com.google.gerrit.server.ServerInitiated) Optional(java.util.Optional) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) GroupDelta(com.google.gerrit.server.group.db.GroupDelta) GroupCache(com.google.gerrit.server.account.GroupCache) ServiceUserClassifier(com.google.gerrit.server.account.ServiceUserClassifier) Singleton(com.google.inject.Singleton) GroupDelta(com.google.gerrit.server.group.db.GroupDelta)

Example 22 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException in project gerrit by GerritCodeReview.

the class GroupsOnInit method addGroupMemberInNoteDb.

private void addGroupMemberInNoteDb(Repository repository, AccountGroup.UUID groupUuid, Account account) throws IOException, ConfigInvalidException, NoSuchGroupException {
    GroupConfig groupConfig = GroupConfig.loadForGroup(allUsers, repository, groupUuid);
    InternalGroup group = groupConfig.getLoadedGroup().orElseThrow(() -> new NoSuchGroupException(groupUuid));
    GroupDelta groupDelta = getMemberAdditionDelta(account);
    AuditLogFormatter auditLogFormatter = getAuditLogFormatter(account);
    groupConfig.setGroupDelta(groupDelta, auditLogFormatter);
    commit(repository, groupConfig, group.getCreatedOn());
}
Also used : GroupConfig(com.google.gerrit.server.group.db.GroupConfig) GroupDelta(com.google.gerrit.server.group.db.GroupDelta) AuditLogFormatter(com.google.gerrit.server.group.db.AuditLogFormatter) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) InternalGroup(com.google.gerrit.entities.InternalGroup)

Example 23 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException in project gerrit by GerritCodeReview.

the class GroupsOnInit method getExistingGroup.

/**
 * Returns the {@code AccountGroup} for the specified {@code GroupReference}.
 *
 * @param groupReference the {@code GroupReference} of the group
 * @return the {@code InternalGroup} represented by the {@code GroupReference}
 * @throws IOException if an error occurs while reading from NoteDb
 * @throws ConfigInvalidException if the data in NoteDb is in an incorrect format
 * @throws NoSuchGroupException if a group with such a name doesn't exist
 */
public InternalGroup getExistingGroup(GroupReference groupReference) throws NoSuchGroupException, IOException, ConfigInvalidException {
    File allUsersRepoPath = getPathToAllUsersRepository();
    if (allUsersRepoPath != null) {
        try (Repository allUsersRepo = new FileRepository(allUsersRepoPath)) {
            AccountGroup.UUID groupUuid = groupReference.getUUID();
            GroupConfig groupConfig = GroupConfig.loadForGroup(allUsers, allUsersRepo, groupUuid);
            return groupConfig.getLoadedGroup().orElseThrow(() -> new NoSuchGroupException(groupReference.getUUID()));
        }
    }
    throw new NoSuchGroupException(groupReference.getUUID());
}
Also used : FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) Repository(org.eclipse.jgit.lib.Repository) AccountGroup(com.google.gerrit.entities.AccountGroup) GroupConfig(com.google.gerrit.server.group.db.GroupConfig) File(java.io.File) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException)

Example 24 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException in project gerrit by GerritCodeReview.

the class InitAdminUser method postRun.

@Override
public void postRun() throws Exception {
    if (!accounts.hasAnyAccount()) {
        welcome();
    }
    AuthType authType = flags.cfg.getEnum(AuthType.values(), "auth", null, "type", null);
    if (authType != AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT) {
        return;
    }
    if (!accounts.hasAnyAccount()) {
        ui.header("Gerrit Administrator");
        if (ui.yesno(true, "Create administrator user")) {
            Account.Id id = Account.id(sequencesOnInit.nextAccountId());
            String username = ui.readString("admin", "username");
            String name = ui.readString("Administrator", "name");
            String httpPassword = ui.readString("secret", "HTTP password");
            AccountSshKey sshKey = readSshKey(id);
            String email = readEmail(sshKey);
            List<ExternalId> extIds = new ArrayList<>(2);
            extIds.add(externalIdFactory.createUsername(username, id, httpPassword));
            if (email != null) {
                extIds.add(externalIdFactory.createEmail(id, email));
            }
            externalIds.insert("Add external IDs for initial admin user", extIds);
            Account persistedAccount = accounts.insert(Account.builder(id, TimeUtil.now()).setFullName(name).setPreferredEmail(email));
            // Only two groups should exist at this point in time and hence iterating over all of them
            // is cheap.
            Optional<GroupReference> adminGroupReference = groupsOnInit.getAllGroupReferences().filter(group -> group.getName().equals("Administrators")).findAny();
            if (!adminGroupReference.isPresent()) {
                throw new NoSuchGroupException("Administrators");
            }
            GroupReference adminGroup = adminGroupReference.get();
            groupsOnInit.addGroupMember(adminGroup.getUUID(), persistedAccount);
            if (sshKey != null) {
                VersionedAuthorizedKeysOnInit authorizedKeys = authorizedKeysFactory.create(id).load();
                authorizedKeys.addKey(sshKey.sshPublicKey());
                authorizedKeys.save("Add SSH key for initial admin user\n");
            }
            AccountState as = AccountState.forAccount(persistedAccount, extIds);
            for (AccountIndex accountIndex : accountIndexCollection.getWriteIndexes()) {
                accountIndex.replace(as);
            }
            InternalGroup adminInternalGroup = groupsOnInit.getExistingGroup(adminGroup);
            for (GroupIndex groupIndex : groupIndexCollection.getWriteIndexes()) {
                groupIndex.replace(adminInternalGroup);
            }
        }
    }
}
Also used : InternalGroup(com.google.gerrit.entities.InternalGroup) AuthType(com.google.gerrit.extensions.client.AuthType) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) Inject(com.google.inject.Inject) GroupIndexCollection(com.google.gerrit.server.index.group.GroupIndexCollection) InitStep(com.google.gerrit.pgm.init.api.InitStep) EmailValidator(org.apache.commons.validator.routines.EmailValidator) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) ExternalIdFactory(com.google.gerrit.server.account.externalids.ExternalIdFactory) ConsoleUI(com.google.gerrit.pgm.init.api.ConsoleUI) Path(java.nio.file.Path) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Account(com.google.gerrit.entities.Account) AccountIndexCollection(com.google.gerrit.server.index.account.AccountIndexCollection) IOException(java.io.IOException) GroupReference(com.google.gerrit.entities.GroupReference) List(java.util.List) AccountSshKey(com.google.gerrit.server.account.AccountSshKey) Paths(java.nio.file.Paths) Optional(java.util.Optional) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) GroupIndex(com.google.gerrit.server.index.group.GroupIndex) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) AccountState(com.google.gerrit.server.account.AccountState) SequencesOnInit(com.google.gerrit.pgm.init.api.SequencesOnInit) InitFlags(com.google.gerrit.pgm.init.api.InitFlags) Account(com.google.gerrit.entities.Account) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) AccountSshKey(com.google.gerrit.server.account.AccountSshKey) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AccountState(com.google.gerrit.server.account.AccountState) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) InternalGroup(com.google.gerrit.entities.InternalGroup) GroupIndex(com.google.gerrit.server.index.group.GroupIndex) AuthType(com.google.gerrit.extensions.client.AuthType) GroupReference(com.google.gerrit.entities.GroupReference)

Example 25 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException 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

NoSuchGroupException (com.google.gerrit.exceptions.NoSuchGroupException)26 AccountGroup (com.google.gerrit.entities.AccountGroup)22 GroupDescription (com.google.gerrit.entities.GroupDescription)13 AuthException (com.google.gerrit.extensions.restapi.AuthException)12 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)12 GroupControl (com.google.gerrit.server.account.GroupControl)12 GroupDelta (com.google.gerrit.server.group.db.GroupDelta)12 Account (com.google.gerrit.entities.Account)10 ArrayList (java.util.ArrayList)10 Inject (com.google.inject.Inject)9 IOException (java.io.IOException)9 Singleton (com.google.inject.Singleton)8 Sets (com.google.common.collect.Sets)7 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)7 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)7 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)6 IdString (com.google.gerrit.extensions.restapi.IdString)6 Response (com.google.gerrit.extensions.restapi.Response)6 GroupResource (com.google.gerrit.server.group.GroupResource)6 GroupsUpdate (com.google.gerrit.server.group.db.GroupsUpdate)6