Search in sources :

Example 46 with CurrentUser

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

the class RefControlTest method setUp.

@Before
public void setUp() throws Exception {
    repoManager = new InMemoryRepositoryManager();
    projectCache = new ProjectCache() {

        @Override
        public ProjectState getAllProjects() {
            return get(allProjectsName);
        }

        @Override
        public ProjectState getAllUsers() {
            return null;
        }

        @Override
        public ProjectState get(Project.NameKey projectName) {
            return all.get(projectName);
        }

        @Override
        public void evict(Project p) {
        }

        @Override
        public void remove(Project p) {
        }

        @Override
        public Iterable<Project.NameKey> all() {
            return Collections.emptySet();
        }

        @Override
        public Iterable<Project.NameKey> byName(String prefix) {
            return Collections.emptySet();
        }

        @Override
        public void onCreateProject(Project.NameKey newProjectName) {
        }

        @Override
        public Set<AccountGroup.UUID> guessRelevantGroupUUIDs() {
            return Collections.emptySet();
        }

        @Override
        public ProjectState checkedGet(Project.NameKey projectName) throws IOException {
            return all.get(projectName);
        }

        @Override
        public void evict(Project.NameKey p) {
        }
    };
    Injector injector = Guice.createInjector(new InMemoryModule());
    injector.injectMembers(this);
    try {
        Repository repo = repoManager.createRepository(allProjectsName);
        ProjectConfig allProjects = new ProjectConfig(new Project.NameKey(allProjectsName.get()));
        allProjects.load(repo);
        LabelType cr = Util.codeReview();
        allProjects.getLabelSections().put(cr.getName(), cr);
        add(allProjects);
    } catch (IOException | ConfigInvalidException e) {
        throw new RuntimeException(e);
    }
    db = schemaFactory.open();
    singleVersionListener.start();
    try {
        schemaCreator.create(db);
    } finally {
        singleVersionListener.stop();
    }
    Cache<SectionSortCache.EntryKey, SectionSortCache.EntryVal> c = CacheBuilder.newBuilder().build();
    sectionSorter = new PermissionCollection.Factory(new SectionSortCache(c));
    parent = new ProjectConfig(parentKey);
    parent.load(newRepository(parentKey));
    add(parent);
    local = new ProjectConfig(localKey);
    local.load(newRepository(localKey));
    add(local);
    local.getProject().setParentName(parentKey);
    requestContext.setContext(new RequestContext() {

        @Override
        public CurrentUser getUser() {
            return null;
        }

        @Override
        public Provider<ReviewDb> getReviewDbProvider() {
            return Providers.of(db);
        }
    });
    changeControlFactory = injector.getInstance(ChangeControl.Factory.class);
}
Also used : Set(java.util.Set) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) CurrentUser(com.google.gerrit.server.CurrentUser) InMemoryRepositoryManager(com.google.gerrit.testutil.InMemoryRepositoryManager) Injector(com.google.inject.Injector) LabelType(com.google.gerrit.common.data.LabelType) ThreadLocalRequestContext(com.google.gerrit.server.util.ThreadLocalRequestContext) RequestContext(com.google.gerrit.server.util.RequestContext) InMemoryModule(com.google.gerrit.testutil.InMemoryModule) IOException(java.io.IOException) AllUsersNameProvider(com.google.gerrit.server.config.AllUsersNameProvider) AllProjectsNameProvider(com.google.gerrit.server.config.AllProjectsNameProvider) Provider(com.google.inject.Provider) ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Project(com.google.gerrit.reviewdb.client.Project) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) InMemoryRepositoryManager.newRepository(com.google.gerrit.testutil.InMemoryRepositoryManager.newRepository) Repository(org.eclipse.jgit.lib.Repository) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) Before(org.junit.Before)

Example 47 with CurrentUser

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

the class ChangeJson method toChangeInfo.

private ChangeInfo toChangeInfo(ChangeData cd, Optional<PatchSet.Id> limitToPsId) throws PatchListNotAvailableException, GpgException, OrmException, IOException, PermissionBackendException {
    ChangeInfo out = new ChangeInfo();
    CurrentUser user = userProvider.get();
    ChangeControl ctl = cd.changeControl().forUser(user);
    if (has(CHECK)) {
        out.problems = checkerProvider.get().check(ctl, fix).problems();
        // If any problems were fixed, the ChangeData needs to be reloaded.
        for (ProblemInfo p : out.problems) {
            if (p.status == ProblemInfo.Status.FIXED) {
                cd = changeDataFactory.create(cd.db(), cd.project(), cd.getId());
                break;
            }
        }
    }
    PermissionBackend.ForChange perm = permissionBackend.user(user).database(db).change(cd);
    Change in = cd.change();
    out.project = in.getProject().get();
    out.branch = in.getDest().getShortName();
    out.topic = in.getTopic();
    if (indexes.getSearchIndex().getSchema().hasField(ChangeField.ASSIGNEE)) {
        if (in.getAssignee() != null) {
            out.assignee = accountLoader.get(in.getAssignee());
        }
    }
    out.hashtags = cd.hashtags();
    out.changeId = in.getKey().get();
    if (in.getStatus().isOpen()) {
        SubmitTypeRecord str = cd.submitTypeRecord();
        if (str.isOk()) {
            out.submitType = str.type;
        }
        out.mergeable = cd.isMergeable();
        if (has(SUBMITTABLE)) {
            out.submittable = submittable(cd);
        }
    }
    Optional<ChangedLines> changedLines = cd.changedLines();
    if (changedLines.isPresent()) {
        out.insertions = changedLines.get().insertions;
        out.deletions = changedLines.get().deletions;
    }
    out.isPrivate = in.isPrivate() ? true : null;
    out.workInProgress = in.isWorkInProgress() ? true : null;
    out.subject = in.getSubject();
    out.status = in.getStatus().asChangeStatus();
    out.owner = accountLoader.get(in.getOwner());
    out.created = in.getCreatedOn();
    out.updated = in.getLastUpdatedOn();
    out._number = in.getId().get();
    out.unresolvedCommentCount = cd.unresolvedCommentCount();
    if (user.isIdentifiedUser()) {
        Collection<String> stars = cd.stars(user.getAccountId());
        out.starred = stars.contains(StarredChangesUtil.DEFAULT_LABEL) ? true : null;
        out.muted = stars.contains(StarredChangesUtil.MUTE_LABEL + "/" + cd.currentPatchSet().getPatchSetId()) ? true : null;
        if (!stars.isEmpty()) {
            out.stars = stars;
        }
    }
    if (in.getStatus().isOpen() && has(REVIEWED) && user.isIdentifiedUser()) {
        Account.Id accountId = user.getAccountId();
        if (out.muted != null) {
            out.reviewed = true;
        } else {
            out.reviewed = cd.reviewedBy().contains(accountId) ? true : null;
        }
    }
    out.labels = labelsFor(perm, ctl, cd, has(LABELS), has(DETAILED_LABELS));
    out.submitted = getSubmittedOn(cd);
    out.plugins = pluginDefinedAttributesFactory != null ? pluginDefinedAttributesFactory.create(cd) : null;
    if (out.labels != null && has(DETAILED_LABELS)) {
        // list permitted labels, since users can't vote on those patch sets.
        if (user.isIdentifiedUser() && (!limitToPsId.isPresent() || limitToPsId.get().equals(in.currentPatchSetId()))) {
            out.permittedLabels = cd.change().getStatus() != Change.Status.ABANDONED ? permittedLabels(perm, cd) : ImmutableMap.of();
        }
        out.reviewers = new HashMap<>();
        for (ReviewerStateInternal state : ReviewerStateInternal.values()) {
            if (state == ReviewerStateInternal.REMOVED) {
                continue;
            }
            Collection<AccountInfo> reviewers = toAccountInfo(cd.reviewers().byState(state));
            reviewers.addAll(toAccountInfoByEmail(cd.reviewersByEmail().byState(state)));
            if (!reviewers.isEmpty()) {
                out.reviewers.put(state.asReviewerState(), reviewers);
            }
        }
        out.removableReviewers = removableReviewers(ctl, out);
    }
    if (has(REVIEWER_UPDATES)) {
        out.reviewerUpdates = reviewerUpdates(cd);
    }
    boolean needMessages = has(MESSAGES);
    boolean needRevisions = has(ALL_REVISIONS) || has(CURRENT_REVISION) || limitToPsId.isPresent();
    Map<PatchSet.Id, PatchSet> src;
    if (needMessages || needRevisions) {
        src = loadPatchSets(cd, limitToPsId);
    } else {
        src = null;
    }
    if (needMessages) {
        out.messages = messages(ctl, cd, src);
    }
    finish(out);
    // it will be passed to ActionVisitors as-is.
    if (needRevisions) {
        out.revisions = revisions(ctl, cd, src, out);
        if (out.revisions != null) {
            for (Map.Entry<String, RevisionInfo> entry : out.revisions.entrySet()) {
                if (entry.getValue().isCurrent) {
                    out.currentRevision = entry.getKey();
                    break;
                }
            }
        }
    }
    if (has(CURRENT_ACTIONS) || has(CHANGE_ACTIONS)) {
        actionJson.addChangeActions(out, ctl);
    }
    return out;
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) CurrentUser(com.google.gerrit.server.CurrentUser) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ChangeControl(com.google.gerrit.server.project.ChangeControl) ChangedLines(com.google.gerrit.server.query.change.ChangeData.ChangedLines) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) ReviewerStateInternal(com.google.gerrit.server.notedb.ReviewerStateInternal) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) SubmitTypeRecord(com.google.gerrit.common.data.SubmitTypeRecord) RevisionInfo(com.google.gerrit.extensions.common.RevisionInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 48 with CurrentUser

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

the class PostReview method onBehalfOf.

private RevisionResource onBehalfOf(RevisionResource rev, ReviewInput in) throws BadRequestException, AuthException, UnprocessableEntityException, OrmException, PermissionBackendException {
    if (in.labels == null || in.labels.isEmpty()) {
        throw new AuthException(String.format("label required to post review on behalf of \"%s\"", in.onBehalfOf));
    }
    if (in.drafts == null) {
        in.drafts = DraftHandling.KEEP;
    }
    if (in.drafts != DraftHandling.KEEP) {
        throw new AuthException("not allowed to modify other user's drafts");
    }
    CurrentUser caller = rev.getUser();
    PermissionBackend.ForChange perm = rev.permissions().database(db);
    LabelTypes labelTypes = rev.getControl().getLabelTypes();
    Iterator<Map.Entry<String, Short>> itr = in.labels.entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, Short> ent = itr.next();
        LabelType type = labelTypes.byLabel(ent.getKey());
        if (type == null && in.strictLabels) {
            throw new BadRequestException(String.format("label \"%s\" is not a configured label", ent.getKey()));
        } else if (type == null) {
            itr.remove();
            continue;
        }
        if (!caller.isInternalUser()) {
            try {
                perm.check(new LabelPermission.WithValue(ON_BEHALF_OF, type, ent.getValue()));
            } catch (AuthException e) {
                throw new AuthException(String.format("not permitted to modify label \"%s\" on behalf of \"%s\"", type.getName(), in.onBehalfOf));
            }
        }
    }
    if (in.labels.isEmpty()) {
        throw new AuthException(String.format("label required to post review on behalf of \"%s\"", in.onBehalfOf));
    }
    IdentifiedUser reviewer = accounts.parseOnBehalfOf(caller, in.onBehalfOf);
    try {
        perm.user(reviewer).check(ChangePermission.READ);
    } catch (AuthException e) {
        throw new UnprocessableEntityException(String.format("on_behalf_of account %s cannot see change", reviewer.getAccountId()));
    }
    ChangeControl ctl = rev.getControl().forUser(reviewer);
    return new RevisionResource(changes.parse(ctl), rev.getPatchSet());
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) LabelTypes(com.google.gerrit.common.data.LabelTypes) CurrentUser(com.google.gerrit.server.CurrentUser) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) AuthException(com.google.gerrit.extensions.restapi.AuthException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ChangeControl(com.google.gerrit.server.project.ChangeControl) LabelType(com.google.gerrit.common.data.LabelType) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Map(java.util.Map) HashMap(java.util.HashMap) LabelPermission(com.google.gerrit.server.permissions.LabelPermission)

Example 49 with CurrentUser

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

the class GetRevisionActions method getETag.

@Override
public String getETag(RevisionResource rsrc) {
    Hasher h = Hashing.md5().newHasher();
    CurrentUser user = rsrc.getControl().getUser();
    try {
        rsrc.getChangeResource().prepareETag(h, user);
        h.putBoolean(Submit.wholeTopicEnabled(config));
        ReviewDb db = dbProvider.get();
        ChangeSet cs = mergeSuperSet.get().completeChangeSet(db, rsrc.getChange(), user);
        for (ChangeData cd : cs.changes()) {
            changeResourceFactory.create(cd.changeControl()).prepareETag(h, user);
        }
        h.putBoolean(cs.furtherHiddenChanges());
    } catch (IOException | OrmException e) {
        throw new OrmRuntimeException(e);
    }
    return h.hash().toString();
}
Also used : Hasher(com.google.common.hash.Hasher) OrmRuntimeException(com.google.gwtorm.server.OrmRuntimeException) CurrentUser(com.google.gerrit.server.CurrentUser) OrmException(com.google.gwtorm.server.OrmException) IOException(java.io.IOException) ChangeSet(com.google.gerrit.server.git.ChangeSet) ChangeData(com.google.gerrit.server.query.change.ChangeData) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Example 50 with CurrentUser

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

the class DeleteComment method applyImpl.

@Override
public CommentInfo applyImpl(BatchUpdate.Factory batchUpdateFactory, CommentResource rsrc, DeleteCommentInput input) throws RestApiException, IOException, ConfigInvalidException, OrmException, PermissionBackendException, UpdateException {
    CurrentUser user = userProvider.get();
    permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
    String newMessage = getCommentNewMessage(user.asIdentifiedUser().getName(), input.reason);
    DeleteCommentOp deleteCommentOp = new DeleteCommentOp(rsrc, newMessage);
    try (BatchUpdate batchUpdate = batchUpdateFactory.create(dbProvider.get(), rsrc.getRevisionResource().getProject(), user, TimeUtil.nowTs())) {
        batchUpdate.addOp(rsrc.getRevisionResource().getChange().getId(), deleteCommentOp).execute();
    }
    ChangeNotes updatedNotes = notesFactory.createChecked(rsrc.getRevisionResource().getChange().getId());
    List<Comment> changeComments = commentsUtil.publishedByChange(dbProvider.get(), updatedNotes);
    Optional<Comment> updatedComment = changeComments.stream().filter(c -> c.key.equals(rsrc.getComment().key)).findFirst();
    if (!updatedComment.isPresent()) {
        // This should not happen as this endpoint should not remove the whole comment.
        throw new ResourceNotFoundException("comment not found: " + rsrc.getComment().key);
    }
    return commentJson.get().newCommentFormatter().format(updatedComment.get());
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) OrmException(com.google.gwtorm.server.OrmException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) CommentInfo(com.google.gerrit.extensions.common.CommentInfo) Inject(com.google.inject.Inject) CommentsUtil(com.google.gerrit.server.CommentsUtil) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) UpdateException(com.google.gerrit.server.update.UpdateException) Strings(com.google.common.base.Strings) Comment(com.google.gerrit.reviewdb.client.Comment) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) RetryHelper(com.google.gerrit.server.update.RetryHelper) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) RetryingRestModifyView(com.google.gerrit.server.update.RetryingRestModifyView) ChangeContext(com.google.gerrit.server.update.ChangeContext) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) CurrentUser(com.google.gerrit.server.CurrentUser) DeleteCommentInput(com.google.gerrit.extensions.api.changes.DeleteCommentInput) TimeUtil(com.google.gerrit.common.TimeUtil) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Provider(com.google.inject.Provider) List(java.util.List) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Optional(java.util.Optional) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) Singleton(com.google.inject.Singleton) Comment(com.google.gerrit.reviewdb.client.Comment) CurrentUser(com.google.gerrit.server.CurrentUser) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) BatchUpdate(com.google.gerrit.server.update.BatchUpdate)

Aggregations

CurrentUser (com.google.gerrit.server.CurrentUser)73 AuthException (com.google.gerrit.extensions.restapi.AuthException)21 Account (com.google.gerrit.reviewdb.client.Account)11 Account (com.google.gerrit.entities.Account)10 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)10 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)10 ChangeData (com.google.gerrit.server.query.change.ChangeData)10 Change (com.google.gerrit.entities.Change)9 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)9 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)9 IOException (java.io.IOException)9 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)8 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)8 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)8 Provider (com.google.inject.Provider)8 HashMap (java.util.HashMap)8 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 Test (org.junit.Test)6 PatchSet (com.google.gerrit.entities.PatchSet)5