Search in sources :

Example 16 with AccountState

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

the class ProjectWatch method getWatchers.

/**
 * Returns all watchers that are relevant
 */
public final Watchers getWatchers(NotifyConfig.NotifyType type, boolean includeWatchersFromNotifyConfig) {
    Watchers matching = new Watchers();
    Set<Account.Id> projectWatchers = new HashSet<>();
    for (AccountState a : args.accountQueryProvider.get().byWatchedProject(project)) {
        Account.Id accountId = a.account().id();
        for (Map.Entry<ProjectWatchKey, ImmutableSet<NotifyConfig.NotifyType>> e : a.projectWatches().entrySet()) {
            if (project.equals(e.getKey().project()) && add(matching, accountId, e.getKey(), e.getValue(), type)) {
                // We only want to prevent matching All-Projects if this filter hits
                projectWatchers.add(accountId);
            }
        }
    }
    for (AccountState a : args.accountQueryProvider.get().byWatchedProject(args.allProjectsName)) {
        for (Map.Entry<ProjectWatchKey, ImmutableSet<NotifyConfig.NotifyType>> e : a.projectWatches().entrySet()) {
            if (args.allProjectsName.equals(e.getKey().project())) {
                Account.Id accountId = a.account().id();
                if (!projectWatchers.contains(accountId)) {
                    add(matching, accountId, e.getKey(), e.getValue(), type);
                }
            }
        }
    }
    if (!includeWatchersFromNotifyConfig) {
        return matching;
    }
    for (ProjectState state : projectState.tree()) {
        for (NotifyConfig nc : state.getConfig().getNotifySections().values()) {
            if (nc.isNotify(type)) {
                try {
                    add(matching, state.getNameKey(), nc);
                } catch (QueryParseException e) {
                    logger.atInfo().log("Project %s has invalid notify %s filter \"%s\": %s", state.getName(), nc.getName(), nc.getFilter(), e.getMessage());
                }
            }
        }
    }
    return matching;
}
Also used : Account(com.google.gerrit.entities.Account) ProjectWatchKey(com.google.gerrit.server.account.ProjectWatches.ProjectWatchKey) AccountState(com.google.gerrit.server.account.AccountState) QueryParseException(com.google.gerrit.index.query.QueryParseException) ImmutableSet(com.google.common.collect.ImmutableSet) NotifyConfig(com.google.gerrit.entities.NotifyConfig) ProjectState(com.google.gerrit.server.project.ProjectState) Map(java.util.Map) HashSet(java.util.HashSet)

Example 17 with AccountState

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

the class SetMembersCommand method reportMembersAction.

private void reportMembersAction(String action, GroupResource group, List<Account.Id> accountIdList) throws UnsupportedEncodingException, IOException {
    String names = accountIdList.stream().map(accountId -> {
        Optional<AccountState> accountState = accountCache.get(accountId);
        if (!accountState.isPresent()) {
            return "n/a";
        }
        return MoreObjects.firstNonNull(accountState.get().account().preferredEmail(), "n/a");
    }).collect(joining(", "));
    out.write(String.format("Members %s group %s: %s\n", action, group.getName(), names).getBytes(ENC));
}
Also used : CommandMetaData(com.google.gerrit.sshd.CommandMetaData) InternalGroup(com.google.gerrit.entities.InternalGroup) AccountCache(com.google.gerrit.server.account.AccountCache) GroupResource(com.google.gerrit.server.group.GroupResource) DeleteSubgroups(com.google.gerrit.server.restapi.group.DeleteSubgroups) IdString(com.google.gerrit.extensions.restapi.IdString) Inject(com.google.inject.Inject) DeleteMembers(com.google.gerrit.server.restapi.group.DeleteMembers) ArrayList(java.util.ArrayList) AddSubgroups(com.google.gerrit.server.restapi.group.AddSubgroups) GroupsCollection(com.google.gerrit.server.restapi.group.GroupsCollection) Argument(org.kohsuke.args4j.Argument) AddMembers(com.google.gerrit.server.restapi.group.AddMembers) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) AccountGroup(com.google.gerrit.entities.AccountGroup) MoreObjects(com.google.common.base.MoreObjects) Account(com.google.gerrit.entities.Account) IOException(java.io.IOException) Option(org.kohsuke.args4j.Option) Streams(com.google.common.collect.Streams) Collectors.joining(java.util.stream.Collectors.joining) TopLevelResource(com.google.gerrit.extensions.restapi.TopLevelResource) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) SshCommand(com.google.gerrit.sshd.SshCommand) Optional(java.util.Optional) AccountState(com.google.gerrit.server.account.AccountState) GroupCache(com.google.gerrit.server.account.GroupCache) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Optional(java.util.Optional) IdString(com.google.gerrit.extensions.restapi.IdString)

Example 18 with AccountState

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

the class AbstractQueryAccountsTest method rawDocument.

@Test
public void rawDocument() throws Exception {
    AccountInfo userInfo = gApi.accounts().id(admin.getAccountId().get()).get();
    Schema<AccountState> schema = indexes.getSearchIndex().getSchema();
    Optional<FieldBundle> rawFields = indexes.getSearchIndex().getRaw(Account.id(userInfo._accountId), QueryOptions.create(IndexConfig.createDefault(), 0, 1, schema.getStoredFields().keySet()));
    assertThat(rawFields).isPresent();
    if (schema.useLegacyNumericFields()) {
        assertThat(rawFields.get().getValue(AccountField.ID)).isEqualTo(userInfo._accountId);
    } else {
        assertThat(Integer.valueOf(rawFields.get().getValue(AccountField.ID_STR))).isEqualTo(userInfo._accountId);
    }
    // The field EXTERNAL_ID_STATE is only supported from schema version 6.
    if (getSchemaVersion() < 6) {
        return;
    }
    List<AccountExternalIdInfo> externalIdInfos = gApi.accounts().self().getExternalIds();
    List<ByteArrayWrapper> blobs = new ArrayList<>();
    for (AccountExternalIdInfo info : externalIdInfos) {
        Optional<ExternalId> extId = externalIds.get(externalIdKeyFactory.parse(info.identity));
        assertThat(extId).isPresent();
        blobs.add(new ByteArrayWrapper(extId.get().toByteArray()));
    }
    assertThat(rawFields.get().getValue(AccountField.EXTERNAL_ID_STATE)).hasSize(blobs.size());
    assertThat(Streams.stream(rawFields.get().getValue(AccountField.EXTERNAL_ID_STATE)).map(ByteArrayWrapper::new).collect(toList())).containsExactlyElementsIn(blobs);
}
Also used : FieldBundle(com.google.gerrit.index.query.FieldBundle) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AccountState(com.google.gerrit.server.account.AccountState) AccountExternalIdInfo(com.google.gerrit.extensions.common.AccountExternalIdInfo) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) Test(org.junit.Test)

Example 19 with AccountState

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

the class QueryAccounts method apply.

@Override
public Response<List<AccountInfo>> apply(TopLevelResource rsrc) throws RestApiException, PermissionBackendException {
    if (Strings.isNullOrEmpty(query)) {
        throw new BadRequestException("missing query field");
    }
    if (suggest && (!suggestConfig || query.length() < suggestFrom)) {
        return Response.ok(Collections.emptyList());
    }
    Set<FillOptions> fillOptions = EnumSet.of(FillOptions.ID);
    if (options.contains(ListAccountsOption.DETAILS)) {
        fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
    }
    boolean modifyAccountCapabilityChecked = false;
    if (options.contains(ListAccountsOption.ALL_EMAILS)) {
        permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
        modifyAccountCapabilityChecked = true;
        fillOptions.add(FillOptions.EMAIL);
        fillOptions.add(FillOptions.SECONDARY_EMAILS);
    }
    if (suggest) {
        fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
        fillOptions.add(FillOptions.EMAIL);
        if (modifyAccountCapabilityChecked) {
            fillOptions.add(FillOptions.SECONDARY_EMAILS);
        } else {
            if (permissionBackend.currentUser().test(GlobalPermission.MODIFY_ACCOUNT)) {
                fillOptions.add(FillOptions.SECONDARY_EMAILS);
            }
        }
    }
    accountLoader = accountLoaderFactory.create(fillOptions);
    AccountQueryProcessor queryProcessor = queryProcessorProvider.get();
    if (queryProcessor.isDisabled()) {
        throw new MethodNotAllowedException("query disabled");
    }
    if (limit != null) {
        queryProcessor.setUserProvidedLimit(limit);
    }
    if (start != null) {
        queryProcessor.setStart(start);
    }
    Map<Account.Id, AccountInfo> matches = new LinkedHashMap<>();
    try {
        Predicate<AccountState> queryPred;
        if (suggest) {
            queryPred = queryBuilder.defaultQuery(query);
            queryProcessor.setUserProvidedLimit(suggestLimit);
        } else {
            queryPred = queryBuilder.parse(query);
        }
        if (!AccountPredicates.hasActive(queryPred)) {
            // if neither 'is:active' nor 'is:inactive' appears in the query only
            // active accounts should be queried
            queryPred = AccountPredicates.andActive(queryPred);
        }
        QueryResult<AccountState> result = queryProcessor.query(queryPred);
        for (AccountState accountState : result.entities()) {
            Account.Id id = accountState.account().id();
            matches.put(id, accountLoader.get(id));
        }
        accountLoader.fill();
        List<AccountInfo> sorted = AccountInfoComparator.ORDER_NULLS_LAST.sortedCopy(matches.values());
        if (!sorted.isEmpty() && result.more()) {
            sorted.get(sorted.size() - 1)._moreAccounts = true;
        }
        return Response.ok(sorted);
    } catch (QueryParseException e) {
        if (suggest) {
            return Response.ok(ImmutableList.of());
        }
        throw new BadRequestException(e.getMessage());
    }
}
Also used : Account(com.google.gerrit.entities.Account) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountQueryProcessor(com.google.gerrit.server.query.account.AccountQueryProcessor) AccountState(com.google.gerrit.server.account.AccountState) LinkedHashMap(java.util.LinkedHashMap) QueryParseException(com.google.gerrit.index.query.QueryParseException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) FillOptions(com.google.gerrit.server.account.AccountDirectory.FillOptions) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Example 20 with AccountState

use of com.google.gerrit.server.account.AccountState 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)

Aggregations

AccountState (com.google.gerrit.server.account.AccountState)63 Account (com.google.gerrit.entities.Account)37 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)18 IOException (java.io.IOException)17 Test (org.junit.Test)16 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)15 Inject (com.google.inject.Inject)15 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)14 AuthException (com.google.gerrit.extensions.restapi.AuthException)12 ArrayList (java.util.ArrayList)12 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)11 HashSet (java.util.HashSet)11 List (java.util.List)11 ImmutableSet (com.google.common.collect.ImmutableSet)10 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)10 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)10 AccountsUpdate (com.google.gerrit.server.account.AccountsUpdate)10 TestAccount (com.google.gerrit.acceptance.TestAccount)9 Nullable (com.google.gerrit.common.Nullable)9 StorageException (com.google.gerrit.exceptions.StorageException)9