Search in sources :

Example 6 with AccountGroupMember

use of com.google.gerrit.reviewdb.client.AccountGroupMember in project gerrit by GerritCodeReview.

the class AccountManager method create.

private AuthResult create(ReviewDb db, AuthRequest who) throws OrmException, AccountException, IOException, ConfigInvalidException {
    Account.Id newId = new Account.Id(db.nextAccountId());
    Account account = new Account(newId, TimeUtil.nowTs());
    ExternalId extId = ExternalId.createWithEmail(who.getExternalIdKey(), newId, who.getEmailAddress());
    account.setFullName(who.getDisplayName());
    account.setPreferredEmail(extId.email());
    boolean isFirstAccount = awaitsFirstAccountCheck.getAndSet(false) && db.accounts().anyAccounts().toList().isEmpty();
    try {
        AccountsUpdate accountsUpdate = accountsUpdateFactory.create();
        accountsUpdate.upsert(db, account);
        ExternalId existingExtId = externalIds.get(extId.key());
        if (existingExtId != null && !existingExtId.accountId().equals(extId.accountId())) {
            // external ID is assigned to another account, do not overwrite
            accountsUpdate.delete(db, account);
            throw new AccountException("Cannot assign external ID \"" + extId.key().get() + "\" to account " + newId + "; external ID already in use.");
        }
        externalIdsUpdateFactory.create().upsert(extId);
    } 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 (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).getPermission(GlobalCapability.ADMINISTRATE_SERVER);
        AccountGroup.UUID uuid = admin.getRules().get(0).getGroup().getUUID();
        AccountGroup g = db.accountGroups().byUUID(uuid).iterator().next();
        AccountGroup.Id adminId = g.getId();
        AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(newId, adminId));
        auditService.dispatchAddAccountsToGroup(newId, Collections.singleton(m));
        db.accountGroupMembers().insert(Collections.singleton(m));
    }
    if (who.getUserName() != null) {
        // Only set if the name hasn't been used yet, but was given to us.
        //
        IdentifiedUser user = userFactory.create(newId);
        try {
            changeUserNameFactory.create(user, who.getUserName()).call();
        } catch (NameAlreadyUsedException e) {
            String message = "Cannot assign user name \"" + who.getUserName() + "\" to account " + newId + "; name already in use.";
            handleSettingUserNameFailure(db, account, extId, message, e, false);
        } catch (InvalidUserNameException e) {
            String message = "Cannot assign user name \"" + who.getUserName() + "\" to account " + newId + "; name does not conform.";
            handleSettingUserNameFailure(db, account, extId, message, e, false);
        } catch (OrmException e) {
            String message = "Cannot assign user name";
            handleSettingUserNameFailure(db, account, extId, message, e, true);
        }
    }
    byEmailCache.evict(account.getPreferredEmail());
    byIdCache.evict(account.getId());
    realm.onCreateAccount(who, account);
    return new AuthResult(newId, extId.key(), true);
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) NameAlreadyUsedException(com.google.gerrit.common.errors.NameAlreadyUsedException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) OrmException(com.google.gwtorm.server.OrmException) Permission(com.google.gerrit.common.data.Permission) ExternalId(com.google.gerrit.server.account.externalids.ExternalId)

Example 7 with AccountGroupMember

use of com.google.gerrit.reviewdb.client.AccountGroupMember in project gerrit by GerritCodeReview.

the class InitAdminUser method postRun.

@Override
public void postRun() throws Exception {
    AuthType authType = flags.cfg.getEnum(AuthType.values(), "auth", null, "type", null);
    if (authType != AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT) {
        return;
    }
    try (ReviewDb db = dbFactory.open()) {
        if (db.accounts().anyAccounts().toList().isEmpty()) {
            ui.header("Gerrit Administrator");
            if (ui.yesno(true, "Create administrator user")) {
                Account.Id id = new Account.Id(db.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(ExternalId.createUsername(username, id, httpPassword));
                if (email != null) {
                    extIds.add(ExternalId.createEmail(id, email));
                }
                externalIds.insert("Add external IDs for initial admin user", extIds);
                Account a = new Account(id, TimeUtil.nowTs());
                a.setFullName(name);
                a.setPreferredEmail(email);
                accounts.insert(db, a);
                AccountGroupName adminGroupName = db.accountGroupNames().get(new AccountGroup.NameKey("Administrators"));
                AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, adminGroupName.getId()));
                db.accountGroupMembers().insert(Collections.singleton(m));
                if (sshKey != null) {
                    VersionedAuthorizedKeysOnInit authorizedKeys = authorizedKeysFactory.create(id).load();
                    authorizedKeys.addKey(sshKey.getSshPublicKey());
                    authorizedKeys.save("Add SSH key for initial admin user\n");
                }
                AccountGroup adminGroup = db.accountGroups().get(adminGroupName.getId());
                AccountState as = new AccountState(a, Collections.singleton(adminGroup.getGroupUUID()), extIds, new HashMap<>());
                for (AccountIndex accountIndex : indexCollection.getWriteIndexes()) {
                    accountIndex.replace(as);
                }
            }
        }
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountGroupName(com.google.gerrit.reviewdb.client.AccountGroupName) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AccountState(com.google.gerrit.server.account.AccountState) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) AuthType(com.google.gerrit.extensions.client.AuthType) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Example 8 with AccountGroupMember

use of com.google.gerrit.reviewdb.client.AccountGroupMember in project gerrit by GerritCodeReview.

the class CreateAccount method apply.

@Override
public Response<AccountInfo> apply(TopLevelResource rsrc, AccountInput input) throws BadRequestException, ResourceConflictException, UnprocessableEntityException, OrmException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new AccountInput();
    }
    if (input.username != null && !username.equals(input.username)) {
        throw new BadRequestException("username must match URL");
    }
    if (!username.matches(Account.USER_NAME_PATTERN)) {
        throw new BadRequestException("Username '" + username + "' must contain only letters, numbers, _, - or .");
    }
    Set<AccountGroup.Id> groups = parseGroups(input.groups);
    Account.Id id = new Account.Id(db.nextAccountId());
    ExternalId extUser = ExternalId.createUsername(username, id, input.httpPassword);
    if (externalIds.get(extUser.key()) != null) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        if (externalIds.get(ExternalId.Key.create(SCHEME_MAILTO, input.email)) != null) {
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
        if (!validator.isValid(input.email)) {
            throw new BadRequestException("invalid email address");
        }
    }
    List<ExternalId> extIds = new ArrayList<>();
    extIds.add(extUser);
    for (AccountExternalIdCreator c : externalIdCreators) {
        extIds.addAll(c.create(id, username, input.email));
    }
    ExternalIdsUpdate externalIdsUpdate = externalIdsUpdateFactory.create();
    try {
        externalIdsUpdate.insert(extIds);
    } catch (OrmDuplicateKeyException duplicateKey) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        try {
            externalIdsUpdate.insert(ExternalId.createEmail(id, input.email));
        } catch (OrmDuplicateKeyException duplicateKey) {
            try {
                externalIdsUpdate.delete(extUser);
            } catch (IOException | ConfigInvalidException cleanupError) {
            // Ignored
            }
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
    }
    Account a = new Account(id, TimeUtil.nowTs());
    a.setFullName(input.name);
    a.setPreferredEmail(input.email);
    accountsUpdate.create().insert(db, a);
    for (AccountGroup.Id groupId : groups) {
        AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, groupId));
        auditService.dispatchAddAccountsToGroup(currentUser.get().getAccountId(), Collections.singleton(m));
        db.accountGroupMembers().insert(Collections.singleton(m));
    }
    if (input.sshKey != null) {
        try {
            authorizedKeys.addKey(id, input.sshKey);
            sshKeyCache.evict(username);
        } catch (InvalidSshKeyException e) {
            throw new BadRequestException(e.getMessage());
        }
    }
    accountCache.evictByUsername(username);
    byEmailCache.evict(input.email);
    indexer.index(id);
    AccountLoader loader = infoLoader.create(true);
    AccountInfo info = loader.get(id);
    loader.fill();
    return Response.created(info);
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) ArrayList(java.util.ArrayList) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountExternalIdCreator(com.google.gerrit.server.api.accounts.AccountExternalIdCreator) InvalidSshKeyException(com.google.gerrit.common.errors.InvalidSshKeyException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AccountInput(com.google.gerrit.extensions.api.accounts.AccountInput) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Example 9 with AccountGroupMember

use of com.google.gerrit.reviewdb.client.AccountGroupMember in project gerrit by GerritCodeReview.

the class ProjectWatch method deliverToMembers.

private void deliverToMembers(Watchers.List matching, AccountGroup.UUID startUUID) throws OrmException {
    ReviewDb db = args.db.get();
    Set<AccountGroup.UUID> seen = new HashSet<>();
    List<AccountGroup.UUID> q = new ArrayList<>();
    seen.add(startUUID);
    q.add(startUUID);
    while (!q.isEmpty()) {
        AccountGroup.UUID uuid = q.remove(q.size() - 1);
        GroupDescription.Basic group = args.groupBackend.get(uuid);
        if (!Strings.isNullOrEmpty(group.getEmailAddress())) {
            // If the group has an email address, do not expand membership.
            matching.emails.add(new Address(group.getEmailAddress()));
            continue;
        }
        AccountGroup ig = GroupDescriptions.toAccountGroup(group);
        if (ig == null) {
            // Non-internal groups cannot be expanded by the server.
            continue;
        }
        for (AccountGroupMember m : db.accountGroupMembers().byGroup(ig.getId())) {
            matching.accounts.add(m.getAccountId());
        }
        for (AccountGroup.UUID m : args.groupIncludes.subgroupsOf(uuid)) {
            if (seen.add(m)) {
                q.add(m);
            }
        }
    }
}
Also used : GroupDescription(com.google.gerrit.common.data.GroupDescription) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) Address(com.google.gerrit.server.mail.Address) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) ArrayList(java.util.ArrayList) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) HashSet(java.util.HashSet)

Example 10 with AccountGroupMember

use of com.google.gerrit.reviewdb.client.AccountGroupMember in project gerrit by GerritCodeReview.

the class DbGroupMemberAuditListener method logOrmExceptionForAccounts.

private void logOrmExceptionForAccounts(String header, Account.Id me, Collection<AccountGroupMember> values, OrmException e) {
    List<String> descriptions = new ArrayList<>();
    for (AccountGroupMember m : values) {
        Account.Id accountId = m.getAccountId();
        String userName = accountCache.get(accountId).getUserName();
        AccountGroup.Id groupId = m.getAccountGroupId();
        String groupName = groupCache.get(groupId).getName();
        descriptions.add(MessageFormat.format("account {0}/{1}, group {2}/{3}", accountId, userName, groupId, groupName));
    }
    logOrmException(header, me, descriptions, e);
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) ArrayList(java.util.ArrayList)

Aggregations

AccountGroupMember (com.google.gerrit.reviewdb.client.AccountGroupMember)12 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)9 Account (com.google.gerrit.reviewdb.client.Account)8 ArrayList (java.util.ArrayList)8 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)5 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)4 OrmException (com.google.gwtorm.server.OrmException)3 GroupDetail (com.google.gerrit.common.data.GroupDetail)2 AccountInfo (com.google.gerrit.extensions.common.AccountInfo)2 AccountGroupById (com.google.gerrit.reviewdb.client.AccountGroupById)2 AccountGroupMemberAudit (com.google.gerrit.reviewdb.client.AccountGroupMemberAudit)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 GroupDescription (com.google.gerrit.common.data.GroupDescription)1 Permission (com.google.gerrit.common.data.Permission)1 InvalidSshKeyException (com.google.gerrit.common.errors.InvalidSshKeyException)1 NameAlreadyUsedException (com.google.gerrit.common.errors.NameAlreadyUsedException)1 NoSuchGroupException (com.google.gerrit.common.errors.NoSuchGroupException)1 AccountInput (com.google.gerrit.extensions.api.accounts.AccountInput)1 AuthType (com.google.gerrit.extensions.client.AuthType)1