Search in sources :

Example 56 with AccountState

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

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

the class BatchAbandon method batchAbandon.

/**
 * If an extension has more than one changes to abandon that belong to the same project, they
 * should use the batch instead of abandoning one by one.
 *
 * <p>It's the caller's responsibility to ensure that all jobs inside the same batch have the
 * matching project from its ChangeData. Violations will result in a ResourceConflictException.
 */
public void batchAbandon(BatchUpdate.Factory updateFactory, Project.NameKey project, CurrentUser user, Collection<ChangeData> changes, String msgTxt, NotifyResolver.Result notify) throws RestApiException, UpdateException {
    if (changes.isEmpty()) {
        return;
    }
    AccountState accountState = user.isIdentifiedUser() ? user.asIdentifiedUser().state() : null;
    try (BatchUpdate u = updateFactory.create(project, user, TimeUtil.now())) {
        u.setNotify(notify);
        for (ChangeData change : changes) {
            if (!project.equals(change.project())) {
                throw new ResourceConflictException(String.format("Project name \"%s\" doesn't match \"%s\"", change.project().get(), project.get()));
            }
            u.addOp(change.getId(), abandonOpFactory.create(accountState, msgTxt));
            u.addOp(change.getId(), storeSubmitRequirementsOpFactory.create(change.submitRequirements().values(), change));
        }
        u.execute();
        if (cfg.getCleanupAccountPatchReview()) {
            cleanupAccountPatchReview(changes);
        }
    }
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountState(com.google.gerrit.server.account.AccountState) ChangeData(com.google.gerrit.server.query.change.ChangeData) BatchUpdate(com.google.gerrit.server.update.BatchUpdate)

Example 58 with AccountState

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

the class InternalAuthBackend method authenticate.

// TODO(gerritcodereview-team): This function has no coverage.
@Override
public AuthUser authenticate(AuthRequest req) throws MissingCredentialsException, InvalidCredentialsException, UnknownUserException, UserNotAllowedException, AuthException {
    if (!req.getUsername().isPresent() || !req.getPassword().isPresent()) {
        throw new MissingCredentialsException();
    }
    String username;
    if (authConfig.isUserNameToLowerCase()) {
        username = req.getUsername().map(u -> u.toLowerCase(Locale.US)).get();
    } else {
        username = req.getUsername().get();
    }
    AccountState who = accountCache.getByUsername(username).orElseThrow(UnknownUserException::new);
    if (!who.account().isActive()) {
        throw new UserNotAllowedException("Authentication failed for " + username + ": account inactive or not provisioned in Gerrit");
    }
    if (!passwordVerifier.checkPassword(who.externalIds(), username, req.getPassword().get())) {
        throw new InvalidCredentialsException();
    }
    return new AuthUser(AuthUser.UUID.create(username), username);
}
Also used : AccountState(com.google.gerrit.server.account.AccountState)

Example 59 with AccountState

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

the class PostReview method batchReviewerEvents.

private void batchReviewerEvents(CurrentUser user, ChangeData cd, PatchSet patchSet, List<ReviewerModification> reviewerModifications, Instant when) {
    List<AccountState> newlyAddedReviewers = new ArrayList<>();
    // There are no events for CCs and reviewers added/deleted by email.
    for (ReviewerModification modification : reviewerModifications) {
        Result reviewerAdditionResult = modification.op.getResult();
        if (modification.state() == ReviewerState.REVIEWER) {
            newlyAddedReviewers.addAll(reviewerAdditionResult.addedReviewers().stream().map(psa -> psa.accountId()).map(accountId -> accountCache.get(accountId)).flatMap(Streams::stream).collect(toList()));
        } else if (modification.state() == ReviewerState.REMOVED) {
            // There is no batch event for reviewer removals, hence fire the event for each
            // modification that deleted a reviewer immediately.
            modification.op.sendEvent();
        }
    }
    // Fire a batch event for all newly added reviewers.
    reviewerAdded.fire(cd, patchSet, newlyAddedReviewers, user.asIdentifiedUser().state(), when);
}
Also used : ON_BEHALF_OF(com.google.gerrit.server.permissions.LabelPermission.ForUser.ON_BEHALF_OF) Whitespace(com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace) ProjectCache(com.google.gerrit.server.project.ProjectCache) Comment(com.google.gerrit.entities.Comment) FixSuggestion(com.google.gerrit.entities.FixSuggestion) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) ReviewerSet(com.google.gerrit.server.ReviewerSet) DiffSummaryKey(com.google.gerrit.server.patch.DiffSummaryKey) Config(org.eclipse.jgit.lib.Config) Map(java.util.Map) FixReplacement(com.google.gerrit.entities.FixReplacement) DraftHandling(com.google.gerrit.extensions.api.changes.ReviewInput.DraftHandling) Side(com.google.gerrit.extensions.client.Side) Metadata(com.google.gerrit.server.logging.Metadata) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) TraceContext(com.google.gerrit.server.logging.TraceContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) NotifyHandling(com.google.gerrit.extensions.api.changes.NotifyHandling) Stream(java.util.stream.Stream) CommentAdded(com.google.gerrit.server.extensions.events.CommentAdded) AutoValue(com.google.auto.value.AutoValue) DiffSummary(com.google.gerrit.server.patch.DiffSummary) PluginSetContext(com.google.gerrit.server.plugincontext.PluginSetContext) Counter1(com.google.gerrit.metrics.Counter1) MetricMaker(com.google.gerrit.metrics.MetricMaker) PatchListKey(com.google.gerrit.server.patch.PatchListKey) FluentLogger(com.google.common.flogger.FluentLogger) Joiner(com.google.common.base.Joiner) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Singleton(com.google.inject.Singleton) AccountCache(com.google.gerrit.server.account.AccountCache) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) CommentsUtil(com.google.gerrit.server.CommentsUtil) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) Response(com.google.gerrit.extensions.restapi.Response) ArrayList(java.util.ArrayList) PATCHSET_LEVEL(com.google.gerrit.entities.Patch.PATCHSET_LEVEL) Strings(com.google.common.base.Strings) ReviewerInput(com.google.gerrit.extensions.api.changes.ReviewerInput) Lists(com.google.common.collect.Lists) ReviewerModification(com.google.gerrit.server.change.ReviewerModifier.ReviewerModification) Description(com.google.gerrit.metrics.Description) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) PatchSet(com.google.gerrit.entities.PatchSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) Address(com.google.gerrit.entities.Address) REVIEWER(com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) NotifyResolver(com.google.gerrit.server.change.NotifyResolver) HashCode(com.google.common.hash.HashCode) Result(com.google.gerrit.server.change.ReviewerOp.Result) PatchListCache(com.google.gerrit.server.patch.PatchListCache) StorageException(com.google.gerrit.exceptions.StorageException) CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) RobotCommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.RobotCommentInput) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) LabelVote(com.google.gerrit.server.util.LabelVote) SC_BAD_REQUEST(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) CommentValidator(com.google.gerrit.extensions.validators.CommentValidator) AccountState(com.google.gerrit.server.account.AccountState) Patch(com.google.gerrit.entities.Patch) Inject(com.google.inject.Inject) HumanComment(com.google.gerrit.entities.HumanComment) UpdateException(com.google.gerrit.server.update.UpdateException) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) LabelTypes(com.google.gerrit.entities.LabelTypes) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) LabelType(com.google.gerrit.entities.LabelType) AuthException(com.google.gerrit.extensions.restapi.AuthException) ReviewerModifier(com.google.gerrit.server.change.ReviewerModifier) Collectors.toSet(java.util.stream.Collectors.toSet) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) Streams(com.google.common.collect.Streams) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) Objects(java.util.Objects) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) FixSuggestionInfo(com.google.gerrit.extensions.common.FixSuggestionInfo) Url(com.google.gerrit.extensions.restapi.Url) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) LabelPermission(com.google.gerrit.server.permissions.LabelPermission) PatchListNotAvailableException(com.google.gerrit.server.patch.PatchListNotAvailableException) WorkInProgressOp(com.google.gerrit.server.change.WorkInProgressOp) CommentValidationContext(com.google.gerrit.extensions.validators.CommentValidationContext) PublishCommentUtil(com.google.gerrit.server.PublishCommentUtil) ChangePermission(com.google.gerrit.server.permissions.ChangePermission) Hashing(com.google.common.hash.Hashing) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) HashMap(java.util.HashMap) HashSet(java.util.HashSet) CommentsRejectedException(com.google.gerrit.server.update.CommentsRejectedException) ImmutableList(com.google.common.collect.ImmutableList) ChangeResource(com.google.gerrit.server.change.ChangeResource) PostUpdateContext(com.google.gerrit.server.update.PostUpdateContext) CommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput) Range(com.google.gerrit.extensions.client.Comment.Range) RobotComment(com.google.gerrit.entities.RobotComment) Field(com.google.gerrit.metrics.Field) Change(com.google.gerrit.entities.Change) ChangeUtil(com.google.gerrit.server.ChangeUtil) ChangeContext(com.google.gerrit.server.update.ChangeContext) ModifyReviewersEmail(com.google.gerrit.server.change.ModifyReviewersEmail) FixReplacementInfo(com.google.gerrit.extensions.common.FixReplacementInfo) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResolver(com.google.gerrit.server.account.AccountResolver) Iterator(java.util.Iterator) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ReviewerAdded(com.google.gerrit.server.extensions.events.ReviewerAdded) ProjectState(com.google.gerrit.server.project.ProjectState) Maps(com.google.common.collect.Maps) ObjectId(org.eclipse.jgit.lib.ObjectId) Collectors.toList(java.util.stream.Collectors.toList) Ordering(com.google.common.collect.Ordering) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) RevisionResource(com.google.gerrit.server.change.RevisionResource) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) EmailReviewComments(com.google.gerrit.server.change.EmailReviewComments) Collections(java.util.Collections) ArrayList(java.util.ArrayList) ReviewerModification(com.google.gerrit.server.change.ReviewerModifier.ReviewerModification) AccountState(com.google.gerrit.server.account.AccountState) Streams(com.google.common.collect.Streams) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) Result(com.google.gerrit.server.change.ReviewerOp.Result)

Example 60 with AccountState

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

the class AccountTemplateUtil method replaceTemplates.

/**
 * Builds user-readable text from text, that might contain {@link #ACCOUNT_TEMPLATE}.
 */
public String replaceTemplates(String messageTemplate) {
    Matcher matcher = ACCOUNT_TEMPLATE_PATTERN.matcher(messageTemplate);
    StringBuilder out = new StringBuilder();
    while (matcher.find()) {
        String accountId = matcher.group(1);
        String unrecognizedAccount = "Unrecognized Gerrit Account " + accountId;
        Optional<Account.Id> parsedAccountId = Account.Id.tryParse(accountId);
        if (parsedAccountId.isPresent()) {
            Optional<AccountState> account = accountCache.get(parsedAccountId.get());
            if (account.isPresent()) {
                matcher.appendReplacement(out, account.get().account().getNameEmail(unrecognizedAccount));
                continue;
            }
        }
        matcher.appendReplacement(out, unrecognizedAccount);
    }
    matcher.appendTail(out);
    return out.toString();
}
Also used : Matcher(java.util.regex.Matcher) AccountState(com.google.gerrit.server.account.AccountState)

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