Search in sources :

Example 61 with IdentifiedUser

use of com.google.gerrit.server.IdentifiedUser in project gerrit by GerritCodeReview.

the class AccountsUpdate method commit.

private void commit(Repository allUsersRepo, List<UpdatedAccount> updatedAccounts) throws IOException {
    if (updatedAccounts.isEmpty()) {
        return;
    }
    beforeCommit.run();
    BatchRefUpdate batchRefUpdate = allUsersRepo.getRefDatabase().newBatchUpdate();
    String externalIdUpdateMessage = updatedAccounts.size() == 1 ? Iterables.getOnlyElement(updatedAccounts).message : "Batch update for " + updatedAccounts.size() + " accounts";
    for (UpdatedAccount updatedAccount : updatedAccounts) {
        // These updates are all for different refs (because batches never update the same account
        // more than once), so there can be multiple commits in the same batch, all with the same base
        // revision in their AccountConfig.
        commitAccountConfig(updatedAccount.message, allUsersRepo, batchRefUpdate, updatedAccount.accountConfig, updatedAccount.created);
        // When creating a new account we must allow empty commits so that the user branch gets
        // created with an empty commit when no account properties are set and hence no
        // 'account.config' file will be created.
        // These update the same ref, so they need to be stacked on top of one another using the same
        // ExternalIdNotes instance.
        commitExternalIdUpdates(externalIdUpdateMessage, allUsersRepo, batchRefUpdate);
    }
    RefUpdateUtil.executeChecked(batchRefUpdate, allUsersRepo);
    Set<Account.Id> accountsToSkipForReindex = getUpdatedAccountIds(batchRefUpdate);
    extIdNotesLoader.updateExternalIdCacheAndMaybeReindexAccounts(externalIdNotes, accountsToSkipForReindex);
    gitRefUpdated.fire(allUsersName, batchRefUpdate, currentUser.map(IdentifiedUser::state).orElse(null));
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Example 62 with IdentifiedUser

use of com.google.gerrit.server.IdentifiedUser in project gerrit by GerritCodeReview.

the class AccountManager method addGroupMember.

private void addGroupMember(AccountGroup.UUID groupUuid, IdentifiedUser user) throws IOException, ConfigInvalidException, AccountException {
    // The user initiated this request by logging in. -> Attribute all modifications to that user.
    GroupsUpdate groupsUpdate = groupsUpdateFactory.create(user);
    GroupDelta groupDelta = GroupDelta.builder().setMemberModification(memberIds -> Sets.union(memberIds, ImmutableSet.of(user.getAccountId()))).build();
    try {
        groupsUpdate.updateGroup(groupUuid, groupDelta);
    } catch (NoSuchGroupException e) {
        throw new AccountException(String.format("Group %s not found", groupUuid), e);
    }
}
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) GroupDelta(com.google.gerrit.server.group.db.GroupDelta) GroupsUpdate(com.google.gerrit.server.group.db.GroupsUpdate) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException)

Example 63 with IdentifiedUser

use of com.google.gerrit.server.IdentifiedUser in project gerrit by GerritCodeReview.

the class InternalAccountDirectory method fill.

private void fill(AccountInfo info, AccountState accountState, Set<FillOptions> options) {
    Account account = accountState.account();
    if (options.contains(FillOptions.ID)) {
        info._accountId = account.id().get();
    } else {
        // Was previously set to look up account for filling.
        info._accountId = null;
    }
    if (options.contains(FillOptions.NAME)) {
        info.name = Strings.emptyToNull(account.fullName());
        if (info.name == null) {
            info.name = accountState.userName().orElse(null);
        }
    }
    if (options.contains(FillOptions.EMAIL)) {
        info.email = account.preferredEmail();
    }
    if (options.contains(FillOptions.SECONDARY_EMAILS)) {
        info.secondaryEmails = getSecondaryEmails(account, accountState.externalIds());
    }
    if (options.contains(FillOptions.USERNAME)) {
        info.username = accountState.userName().orElse(null);
    }
    if (options.contains(FillOptions.DISPLAY_NAME)) {
        info.displayName = account.displayName();
    }
    if (options.contains(FillOptions.STATUS)) {
        info.status = account.status();
    }
    if (options.contains(FillOptions.STATE)) {
        info.inactive = account.inactive() ? true : null;
    }
    if (options.contains(FillOptions.TAGS)) {
        List<String> tags = getTags(account.id());
        if (!tags.isEmpty()) {
            info.tags = tags;
        }
    }
    if (options.contains(FillOptions.AVATARS)) {
        AvatarProvider ap = avatar.get();
        if (ap != null) {
            info.avatars = new ArrayList<>();
            IdentifiedUser user = userFactory.create(account.id());
            // PolyGerrit UI uses the following sizes for avatars:
            // - 32px for avatars next to names e.g. on the dashboard. This is also Gerrit's default.
            // - 56px for the user's own avatar in the menu
            // - 100ox for other user's avatars on dashboards
            // - 120px for the user's own profile settings page
            addAvatar(ap, info, user, AvatarInfo.DEFAULT_SIZE);
            if (!info.avatars.isEmpty()) {
                addAvatar(ap, info, user, 56);
                addAvatar(ap, info, user, 100);
                addAvatar(ap, info, user, 120);
            }
        }
    }
}
Also used : Account(com.google.gerrit.entities.Account) AvatarProvider(com.google.gerrit.server.avatar.AvatarProvider) IdentifiedUser(com.google.gerrit.server.IdentifiedUser)

Example 64 with IdentifiedUser

use of com.google.gerrit.server.IdentifiedUser in project gerrit by GerritCodeReview.

the class ReviewerModifier method byAccountId.

@Nullable
private ReviewerModification byAccountId(ReviewerInput input, ChangeNotes notes, CurrentUser user) throws PermissionBackendException, IOException, ConfigInvalidException {
    IdentifiedUser reviewerUser;
    boolean exactMatchFound = false;
    try {
        reviewerUser = accountResolver.resolveIncludeInactive(input.reviewer).asUniqueUser();
        if (input.reviewer.equalsIgnoreCase(reviewerUser.getName()) || input.reviewer.equals(String.valueOf(reviewerUser.getAccountId()))) {
            exactMatchFound = true;
        }
    } catch (UnprocessableEntityException e) {
        // group, but if not, the error message will be useful.
        return fail(input, FailureType.NOT_FOUND, e.getMessage());
    }
    if (isValidReviewer(notes.getChange().getDest(), reviewerUser.getAccount())) {
        return new ReviewerModification(input, notes, user, ImmutableSet.of(reviewerUser.getAccount()), null, exactMatchFound, false);
    }
    return fail(input, FailureType.OTHER, MessageFormat.format(ChangeMessages.get().reviewerCantSeeChange, input.reviewer));
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Nullable(com.google.gerrit.common.Nullable)

Example 65 with IdentifiedUser

use of com.google.gerrit.server.IdentifiedUser in project gerrit by GerritCodeReview.

the class ModifyReviewersEmail method emailReviewersAsync.

public void emailReviewersAsync(IdentifiedUser user, Change change, Collection<Account.Id> added, Collection<Account.Id> copied, Collection<Account.Id> removed, Collection<Address> addedByEmail, Collection<Address> copiedByEmail, Collection<Address> removedByEmail, NotifyResolver.Result notify) {
    // The user knows they added/removed themselves, don't bother emailing them.
    Account.Id userId = user.getAccountId();
    ImmutableList<Account.Id> immutableToMail = added.stream().filter(id -> !id.equals(userId)).collect(toImmutableList());
    ImmutableList<Account.Id> immutableToCopy = copied.stream().filter(id -> !id.equals(userId)).collect(toImmutableList());
    ImmutableList<Account.Id> immutableToRemove = removed.stream().filter(id -> !id.equals(userId)).collect(toImmutableList());
    if (immutableToMail.isEmpty() && immutableToCopy.isEmpty() && immutableToRemove.isEmpty() && addedByEmail.isEmpty() && copiedByEmail.isEmpty() && removedByEmail.isEmpty()) {
        return;
    }
    // Make immutable copies of collections and hand over only immutable data types to the other
    // thread.
    Change.Id cId = change.getId();
    Project.NameKey projectNameKey = change.getProject();
    ImmutableList<Address> immutableAddedByEmail = ImmutableList.copyOf(addedByEmail);
    ImmutableList<Address> immutableCopiedByEmail = ImmutableList.copyOf(copiedByEmail);
    ImmutableList<Address> immutableRemovedByEmail = ImmutableList.copyOf(removedByEmail);
    @SuppressWarnings("unused") Future<?> possiblyIgnoredError = sendEmailsExecutor.submit(() -> {
        try {
            ModifyReviewerSender emailSender = addReviewerSenderFactory.create(projectNameKey, cId);
            emailSender.setNotify(notify);
            emailSender.setFrom(userId);
            emailSender.addReviewers(immutableToMail);
            emailSender.addReviewersByEmail(immutableAddedByEmail);
            emailSender.addExtraCC(immutableToCopy);
            emailSender.addExtraCCByEmail(immutableCopiedByEmail);
            emailSender.addRemovedReviewers(immutableToRemove);
            emailSender.addRemovedByEmailReviewers(immutableRemovedByEmail);
            emailSender.setMessageId(messageIdGenerator.fromChangeUpdate(change.getProject(), change.currentPatchSetId()));
            emailSender.send();
        } catch (Exception err) {
            logger.atSevere().withCause(err).log("Cannot send email to new reviewers of change %s", change.getId());
        }
    });
}
Also used : ModifyReviewerSender(com.google.gerrit.server.mail.send.ModifyReviewerSender) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Inject(com.google.inject.Inject) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) MessageIdGenerator(com.google.gerrit.server.mail.send.MessageIdGenerator) Future(java.util.concurrent.Future) ImmutableList(com.google.common.collect.ImmutableList) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.entities.Project) Change(com.google.gerrit.entities.Change) Address(com.google.gerrit.entities.Address) FluentLogger(com.google.common.flogger.FluentLogger) ExecutorService(java.util.concurrent.ExecutorService) SendEmailExecutor(com.google.gerrit.server.config.SendEmailExecutor) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) Address(com.google.gerrit.entities.Address) Change(com.google.gerrit.entities.Change) Project(com.google.gerrit.entities.Project) ModifyReviewerSender(com.google.gerrit.server.mail.send.ModifyReviewerSender)

Aggregations

IdentifiedUser (com.google.gerrit.server.IdentifiedUser)89 AuthException (com.google.gerrit.extensions.restapi.AuthException)27 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)19 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)15 CurrentUser (com.google.gerrit.server.CurrentUser)13 IOException (java.io.IOException)13 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)13 Project (com.google.gerrit.entities.Project)12 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)12 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)12 Inject (com.google.inject.Inject)12 Singleton (com.google.inject.Singleton)12 ArrayList (java.util.ArrayList)12 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)11 Provider (com.google.inject.Provider)11 Change (com.google.gerrit.entities.Change)10 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)10 Repository (org.eclipse.jgit.lib.Repository)10 Account (com.google.gerrit.entities.Account)9 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)9