The Unified and Autonomous Development Platform
Draft version of RESTful api
Robin Shenb6843d38df35
diff --git a/server-core/src/main/java/io/onedev/server/buildspec/job/DefaultJobManager.java b/server-core/src/main/java/io/onedev/server/buildspec/job/DefaultJobManager.javaindex dff33c5574..391744a453 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/job/DefaultJobManager.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/job/DefaultJobManager.java@@ -732,7 +732,7 @@ public class DefaultJobManager implements JobManager, Runnable, CodePullAuthoriz@Transactional@Override- public void resubmit(Build build, Map<String, List<String>> paramMap, String resubmitReason) {+ public void resubmit(Build build, Map<String, List<String>> paramMap, String reason) {if (build.isFinished()) {validate(build.getProject(), build.getCommitId());@@ -743,7 +743,7 @@ public class DefaultJobManager implements JobManager, Runnable, CodePullAuthorizbuild.setRunningDate(null);build.setSubmitDate(new Date());build.setSubmitter(SecurityUtils.getUser());- build.setSubmitReason(resubmitReason);+ build.setSubmitReason(reason);build.setCanceller(null);build.setCancellerName(null);diff --git a/server-core/src/main/java/io/onedev/server/buildspec/job/JobManager.java b/server-core/src/main/java/io/onedev/server/buildspec/job/JobManager.javaindex 11e0790f11..86a7bc7e8a 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/job/JobManager.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/job/JobManager.java@@ -20,7 +20,7 @@ public interface JobManager {Build submit(Project project, ObjectId commitId, String jobName,Map<String, List<String>> paramMap, SubmitReason reason);- void resubmit(Build build, Map<String, List<String>> paramMap, String resubmitReason);+ void resubmit(Build build, Map<String, List<String>> paramMap, String reason);void cancel(Build build);diff --git a/server-core/src/main/java/io/onedev/server/buildspec/job/SubmitReason.java b/server-core/src/main/java/io/onedev/server/buildspec/job/SubmitReason.javaindex ec44e67a4d..fc5ad391e6 100644--- a/server-core/src/main/java/io/onedev/server/buildspec/job/SubmitReason.java+++ b/server-core/src/main/java/io/onedev/server/buildspec/job/SubmitReason.java@@ -7,10 +7,10 @@ import io.onedev.server.model.PullRequest;public interface SubmitReason {String getRefName();-+@NullablePullRequest getPullRequest();-+String getDescription();}diff --git a/server-core/src/main/java/io/onedev/server/model/Build.java b/server-core/src/main/java/io/onedev/server/model/Build.javaindex fab5ecaef7..142de3c1a5 100644--- a/server-core/src/main/java/io/onedev/server/model/Build.java+++ b/server-core/src/main/java/io/onedev/server/model/Build.java@@ -49,6 +49,7 @@ import org.eclipse.jgit.lib.Repository;import org.eclipse.jgit.revwalk.RevCommit;import org.eclipse.jgit.revwalk.RevWalk;+import com.fasterxml.jackson.annotation.JsonIgnore;import com.google.common.base.Objects;import com.google.common.base.Preconditions;import com.google.common.collect.Lists;@@ -301,6 +302,7 @@ public class Build extends AbstractEntity implements Referenceable {private Date retryDate;+ @JsonIgnoreprivate Integer finishDay;@Column(nullable=false, length=1000)diff --git a/server-core/src/main/java/io/onedev/server/model/Milestone.java b/server-core/src/main/java/io/onedev/server/model/Milestone.javaindex d55bbce3dd..49dc00f39a 100644--- a/server-core/src/main/java/io/onedev/server/model/Milestone.java+++ b/server-core/src/main/java/io/onedev/server/model/Milestone.java@@ -37,10 +37,14 @@ public class Milestone extends AbstractEntity {public static final String PROP_ID = "id";+ public static final String PROP_PROJECT = "project";+public static final String PROP_NAME = "name";public static final String PROP_DUE_DATE = "dueDate";+ public static final String PROP_CLOSED = "closed";+@ManyToOne@JoinColumn(nullable=false)private Project project;diff --git a/server-core/src/main/java/io/onedev/server/model/PullRequest.java b/server-core/src/main/java/io/onedev/server/model/PullRequest.javaindex 1534734113..5b0d32827b 100644--- a/server-core/src/main/java/io/onedev/server/model/PullRequest.java+++ b/server-core/src/main/java/io/onedev/server/model/PullRequest.java@@ -54,6 +54,7 @@ import com.google.common.base.Preconditions;import com.google.common.collect.Lists;import io.onedev.server.OneDev;+import io.onedev.server.entitymanager.PullRequestManager;import io.onedev.server.entitymanager.UserManager;import io.onedev.server.git.GitUtils;import io.onedev.server.infomanager.PullRequestInfoManager;@@ -1099,4 +1100,82 @@ public class PullRequest extends AbstractEntity implements Referenceable, Attachreturn requiredJobs;}+ @Nullable+ public String checkMerge() {+ if (!isOpen())+ return "Pull request already closed";+ String checkError = getCheckError();+ if (checkError != null)+ return "Pull request is in error: " + checkError;+ MergePreview preview = getMergePreview();+ if (preview == null)+ return "Merge preview not calculated yet";+ if (preview.getMergeCommitHash() == null)+ return "There are merge conflicts";+ if (!isAllReviewsApproved())+ return "Waiting for approvals";+ if (!isRequiredBuildsSuccessful())+ return "Some required builds not passed";+ return null;+ }++ @Nullable+ public String checkReopen() {+ if (isOpen())+ return "Pull request already opened";+ if (getTarget().getObjectName(false) == null)+ return "Target branch no longer exists";+ if (getSourceProject() == null)+ return "Source project no longer exists";+ if (getSource().getObjectName(false) == null)+ return "Source branch no longer exists";+ PullRequestManager manager = OneDev.getInstance(PullRequestManager.class);+ PullRequest request = manager.findEffective(getTarget(), getSource());+ if (request != null) {+ if (request.isOpen())+ return "Another pull request already open for this change";+ else+ return "Change already merged";+ }++ if (GitUtils.isMergedInto(getTargetProject().getRepository(), null,+ getSource().getObjectId(), getTarget().getObjectId())) {+ return "Source branch already merged into target branch";+ }++ return null;+ }++ @Nullable+ public String checkDeleteSourceBranch() {+ if (!isMerged())+ return "Pull request not merged";+ if (getSourceProject() == null)+ return "Source project no longer exists";+ if (getSource().getObjectName(false) == null)+ return "Source branch no longer exists";+ if (getSource().isDefault())+ return "Source branch is default branch";+ MergePreview preview = getMergePreview();+ if (preview == null)+ return "Merge preview not calculated yet";+ if (!getSource().getObjectName().equals(preview.getHeadCommitHash())+ && !getSource().getObjectName().equals(preview.getMergeCommitHash())) {+ return "Change not updated yet";+ }+ PullRequestManager manager = OneDev.getInstance(PullRequestManager.class);+ if (!manager.queryOpenTo(getSource()).isEmpty())+ return "Some other pull requests are opening to this branch";+ return null;+ }++ @Nullable+ public String checkRestoreSourceBranch() {+ if (getSourceProject() == null)+ return "Source project no longer exists";+ if (getSource().getObjectName(false) != null)+ return "Source branch already exists";+ return null;+ }+}diff --git a/server-core/src/main/java/io/onedev/server/rest/BuildQuerySettingResource.java b/server-core/src/main/java/io/onedev/server/rest/BuildQuerySettingResource.javanew file mode 100644index 0000000000..b533a82f7d--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/BuildQuerySettingResource.java@@ -0,0 +1,64 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.BuildQuerySettingManager;+import io.onedev.server.model.BuildQuerySetting;+import io.onedev.server.security.SecurityUtils;++@Path("/build-query-settings")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class BuildQuerySettingResource {++ private final BuildQuerySettingManager querySettingManager;++ @Inject+ public BuildQuerySettingResource(BuildQuerySettingManager querySettingManager) {+ this.querySettingManager = querySettingManager;+ }++ @Path("/{querySettingId}")+ @GET+ public BuildQuerySetting get(@PathParam("querySettingId") Long querySettingId) {+ BuildQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return querySetting;+ }++ @POST+ public Long save(@NotNull BuildQuerySetting querySetting) {+ if (!SecurityUtils.canAccess(querySetting.getProject())+ || !SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }+ querySettingManager.save(querySetting);+ return querySetting.getId();+ }++ @Path("/{querySettingId}")+ @DELETE+ public Response delete(@PathParam("querySettingId") Long querySettingId) {+ BuildQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ querySettingManager.delete(querySetting);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/BuildResource.java b/server-core/src/main/java/io/onedev/server/rest/BuildResource.javanew file mode 100644index 0000000000..16b92e22e2--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/BuildResource.java@@ -0,0 +1,113 @@+package io.onedev.server.rest;++import java.util.Collection;+import java.util.List;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.QueryParam;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.BuildManager;+import io.onedev.server.model.Build;+import io.onedev.server.model.BuildDependence;+import io.onedev.server.model.BuildParam;+import io.onedev.server.rest.jersey.InvalidParamException;+import io.onedev.server.search.entity.build.BuildQuery;+import io.onedev.server.security.SecurityUtils;++@Path("/builds")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class BuildResource {++ private final BuildManager buildManager;++ @Inject+ public BuildResource(BuildManager buildManager) {+ this.buildManager = buildManager;+ }++ @Path("/{buildId}")+ @GET+ public Build get(@PathParam("buildId") Long buildId) {+ Build build = buildManager.load(buildId);+ if (!SecurityUtils.canAccess(build))+ throw new UnauthorizedException();+ return build;+ }++ @Path("/{buildId}/params")+ @GET+ public Collection<BuildParam> getParams(@PathParam("buildId") Long buildId) {+ Build build = buildManager.load(buildId);+ if (!SecurityUtils.canAccess(build))+ throw new UnauthorizedException();+ return build.getParams();+ }++ @Path("/{buildId}/dependencies")+ @GET+ public Collection<BuildDependence> getDependencies(@PathParam("buildId") Long buildId) {+ Build build = buildManager.load(buildId);+ if (!SecurityUtils.canAccess(build))+ throw new UnauthorizedException();+ return build.getDependencies();+ }++ @Path("/{buildId}/dependents")+ @GET+ public Collection<BuildDependence> getDependents(@PathParam("buildId") Long buildId) {+ Build build = buildManager.load(buildId);+ if (!SecurityUtils.canAccess(build))+ throw new UnauthorizedException();+ return build.getDependents();+ }++ @Path("/{buildId}/fixed-issue-numbers")+ @GET+ public Collection<Long> getFixedIssueNumbers(@PathParam("buildId") Long buildId) {+ Build build = buildManager.load(buildId);+ if (!SecurityUtils.canAccess(build))+ throw new UnauthorizedException();+ return build.getFixedIssueNumbers();+ }++ @GET+ public List<Build> query(@QueryParam("query") String query, @QueryParam("offset") int offset,+ @QueryParam("count") int count) {++ if (count > RestConstants.PAGE_SIZE)+ throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);++ BuildQuery parsedQuery;+ try {+ parsedQuery = BuildQuery.parse(null, query, true, true);+ } catch (Exception e) {+ throw new InvalidParamException("Error parsing query", e);+ }++ return buildManager.query(null, parsedQuery, offset, count);+ }++ @Path("/{buildId}")+ @DELETE+ public Response delete(@PathParam("buildId") Long buildId) {+ Build build = buildManager.load(buildId);+ if (!SecurityUtils.canManage(build))+ throw new UnauthorizedException();+ buildManager.delete(build);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/CodeCommentQuerySettingResource.java b/server-core/src/main/java/io/onedev/server/rest/CodeCommentQuerySettingResource.javanew file mode 100644index 0000000000..957878934a--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/CodeCommentQuerySettingResource.java@@ -0,0 +1,64 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.CodeCommentQuerySettingManager;+import io.onedev.server.model.CodeCommentQuerySetting;+import io.onedev.server.security.SecurityUtils;++@Path("/code-comment-query-settings")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class CodeCommentQuerySettingResource {++ private final CodeCommentQuerySettingManager querySettingManager;++ @Inject+ public CodeCommentQuerySettingResource(CodeCommentQuerySettingManager querySettingManager) {+ this.querySettingManager = querySettingManager;+ }++ @Path("/{querySettingId}")+ @GET+ public CodeCommentQuerySetting get(@PathParam("querySettingId") Long querySettingId) {+ CodeCommentQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return querySetting;+ }++ @POST+ public Long save(@NotNull CodeCommentQuerySetting querySetting) {+ if (!SecurityUtils.canAccess(querySetting.getProject())+ || !SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }+ querySettingManager.save(querySetting);+ return querySetting.getId();+ }++ @Path("/{querySettingId}")+ @DELETE+ public Response delete(@PathParam("querySettingId") Long querySettingId) {+ CodeCommentQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ querySettingManager.delete(querySetting);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/CodeCommentReplyResource.java b/server-core/src/main/java/io/onedev/server/rest/CodeCommentReplyResource.javanew file mode 100644index 0000000000..6e2f2b3285--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/CodeCommentReplyResource.java@@ -0,0 +1,65 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.CodeCommentReplyManager;+import io.onedev.server.model.CodeCommentReply;+import io.onedev.server.security.SecurityUtils;++@Path("/code-comment-replies")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class CodeCommentReplyResource {++ private final CodeCommentReplyManager replyManager;++ @Inject+ public CodeCommentReplyResource(CodeCommentReplyManager replyManager) {+ this.replyManager = replyManager;+ }++ @Path("/{replyId}")+ @GET+ public CodeCommentReply get(@PathParam("commentId") Long replyId) {+ CodeCommentReply reply = replyManager.load(replyId);+ if (!SecurityUtils.canReadCode(reply.getComment().getProject()))+ throw new UnauthorizedException();+ return reply;+ }++ @POST+ public Long save(@NotNull CodeCommentReply reply) {+ if (!SecurityUtils.canReadCode(reply.getComment().getProject()) ||+ !SecurityUtils.isAdministrator() && !reply.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }++ replyManager.save(reply);+ return reply.getId();+ }++ @Path("/{replyId}")+ @DELETE+ public Response delete(@PathParam("replyId") Long replyId) {+ CodeCommentReply reply = replyManager.load(replyId);+ if (!SecurityUtils.canModifyOrDelete(reply))+ throw new UnauthorizedException();+ replyManager.delete(reply);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/CodeCommentResource.java b/server-core/src/main/java/io/onedev/server/rest/CodeCommentResource.javanew file mode 100644index 0000000000..0038c8f280--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/CodeCommentResource.java@@ -0,0 +1,133 @@+package io.onedev.server.rest;++import java.util.Collection;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.QueryParam;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.CodeCommentManager;+import io.onedev.server.entitymanager.ProjectManager;+import io.onedev.server.entitymanager.PullRequestManager;+import io.onedev.server.model.CodeComment;+import io.onedev.server.model.CodeCommentReply;+import io.onedev.server.model.Project;+import io.onedev.server.model.PullRequest;+import io.onedev.server.rest.jersey.InvalidParamException;+import io.onedev.server.search.entity.codecomment.CodeCommentQuery;+import io.onedev.server.security.SecurityUtils;++@Path("/code-comments")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class CodeCommentResource {++ private final CodeCommentManager commentManager;++ private final ProjectManager projectManager;++ private final PullRequestManager pullRequestManager;++ @Inject+ public CodeCommentResource(CodeCommentManager commentManager, ProjectManager projectManager,+ PullRequestManager pullRequestManager) {+ this.commentManager = commentManager;+ this.projectManager = projectManager;+ this.pullRequestManager = pullRequestManager;+ }++ @Path("/{commentId}")+ @GET+ public CodeComment get(@PathParam("commentId") Long commentId) {+ CodeComment comment = commentManager.load(commentId);+ if (!SecurityUtils.canReadCode(comment.getProject()))+ throw new UnauthorizedException();+ return comment;+ }++ @Path("/{commentId}/replies")+ @GET+ public Collection<CodeCommentReply> getReplies(@PathParam("commentId") Long commentId) {+ CodeComment comment = commentManager.load(commentId);+ if (!SecurityUtils.canReadCode(comment.getProject()))+ throw new UnauthorizedException();+ return comment.getReplies();+ }++ @GET+ public Collection<CodeComment> query(@QueryParam("projectId") Long projectId,+ @QueryParam("pullRequestId") Long pullRequestId, @QueryParam("query") String query,+ @QueryParam("offset") int offset, @QueryParam("count") int count) {++ if (count > RestConstants.PAGE_SIZE)+ throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);++ Project project;+ if (projectId != null)+ project = projectManager.load(projectId);+ else+ project = null;++ PullRequest pullRequest;+ if (pullRequestId != null)+ pullRequest = pullRequestManager.load(pullRequestId);+ else+ pullRequest = null;++ if (project == null && pullRequest != null)+ project = pullRequest.getProject();++ if (project == null)+ throw new InvalidParamException("Either projectId or pullRequestId should be specified");++ if (!SecurityUtils.canReadCode(project))+ throw new UnauthorizedException();++ if (pullRequest != null && !pullRequest.getProject().equals(project))+ throw new InvalidParamException("Specified pull request does not belong to specified project");++ CodeCommentQuery parsedQuery;+ try {+ parsedQuery = CodeCommentQuery.parse(null, query);+ } catch (Exception e) {+ throw new InvalidParamException("Error parsing query", e);+ }++ return commentManager.query(project, pullRequest, parsedQuery, offset, count);+ }++ @POST+ public Long save(@NotNull CodeComment comment) {+ if (!SecurityUtils.canReadCode(comment.getProject()) ||+ !SecurityUtils.isAdministrator() && !comment.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }++ commentManager.save(comment);+ return comment.getId();+ }++ @Path("/{commentId}")+ @DELETE+ public Response delete(@PathParam("commentId") Long commentId) {+ CodeComment comment = commentManager.load(commentId);+ if (!SecurityUtils.canModifyOrDelete(comment))+ throw new UnauthorizedException();+ commentManager.delete(comment);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/CommitQuerySettingResource.java b/server-core/src/main/java/io/onedev/server/rest/CommitQuerySettingResource.javanew file mode 100644index 0000000000..93b330d429--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/CommitQuerySettingResource.java@@ -0,0 +1,64 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.CommitQuerySettingManager;+import io.onedev.server.model.CommitQuerySetting;+import io.onedev.server.security.SecurityUtils;++@Path("/commit-query-settings")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class CommitQuerySettingResource {++ private final CommitQuerySettingManager querySettingManager;++ @Inject+ public CommitQuerySettingResource(CommitQuerySettingManager querySettingManager) {+ this.querySettingManager = querySettingManager;+ }++ @Path("/{querySettingId}")+ @GET+ public CommitQuerySetting get(@PathParam("querySettingId") Long querySettingId) {+ CommitQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return querySetting;+ }++ @POST+ public Long save(@NotNull CommitQuerySetting querySetting) {+ if (!SecurityUtils.canAccess(querySetting.getProject())+ || !SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }+ querySettingManager.save(querySetting);+ return querySetting.getId();+ }++ @Path("/{querySettingId}")+ @DELETE+ public Response delete(@PathParam("querySettingId") Long querySettingId) {+ CommitQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ querySettingManager.delete(querySetting);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/GroupAuthorizationResource.java b/server-core/src/main/java/io/onedev/server/rest/GroupAuthorizationResource.javanew file mode 100644index 0000000000..0c5a575d33--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/GroupAuthorizationResource.java@@ -0,0 +1,60 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.GroupAuthorizationManager;+import io.onedev.server.model.GroupAuthorization;+import io.onedev.server.security.SecurityUtils;++@Path("/group-authorizations")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class GroupAuthorizationResource {++ private final GroupAuthorizationManager authorizationManager;++ @Inject+ public GroupAuthorizationResource(GroupAuthorizationManager authorizationManager) {+ this.authorizationManager = authorizationManager;+ }++ @Path("/{authorizationId}")+ @GET+ public GroupAuthorization get(@PathParam("authorizationId") Long authorizationId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return authorizationManager.load(authorizationId);+ }++ @POST+ public Long save(@NotNull GroupAuthorization authorization) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ authorizationManager.save(authorization);+ return authorization.getId();+ }++ @Path("/{authorizationId}")+ @DELETE+ public Response delete(@PathParam("authorizationId") Long authorizationId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ authorizationManager.delete(authorizationManager.load(authorizationId));+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/GroupResource.java b/server-core/src/main/java/io/onedev/server/rest/GroupResource.javanew file mode 100644index 0000000000..11be029a83--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/GroupResource.java@@ -0,0 +1,103 @@+package io.onedev.server.rest;++import java.util.Collection;+import java.util.List;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.QueryParam;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;+import org.hibernate.criterion.MatchMode;+import org.hibernate.criterion.Restrictions;++import io.onedev.server.entitymanager.GroupManager;+import io.onedev.server.model.Group;+import io.onedev.server.model.GroupAuthorization;+import io.onedev.server.model.Membership;+import io.onedev.server.persistence.dao.EntityCriteria;+import io.onedev.server.rest.jersey.InvalidParamException;+import io.onedev.server.security.SecurityUtils;++@Path("/groups")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class GroupResource {++ private final GroupManager groupManager;++ @Inject+ public GroupResource(GroupManager groupManager) {+ this.groupManager = groupManager;+ }++ @Path("/{groupId}")+ @GET+ public Group get(@PathParam("groupId") Long groupId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return groupManager.load(groupId);+ }++ @Path("/{groupId}/authorizations")+ @GET+ public Collection<GroupAuthorization> getAuthorizations(@PathParam("groupId") Long groupId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return groupManager.load(groupId).getAuthorizations();+ }++ @Path("/{groupId}/memberships")+ @GET+ public Collection<Membership> getMemberships(@PathParam("groupId") Long groupId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return groupManager.load(groupId).getMemberships();+ }++ @GET+ public List<Group> query(@QueryParam("name") String name, @QueryParam("offset") int offset,+ @QueryParam("count") int count) {++ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();++ if (count > RestConstants.PAGE_SIZE)+ throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);++ EntityCriteria<Group> criteria = EntityCriteria.of(Group.class);+ if (name != null)+ criteria.add(Restrictions.ilike("name", name.replace('*', '%'), MatchMode.EXACT));++ return groupManager.query(criteria, offset, count);+ }++ @POST+ public Long save(@NotNull Group group) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ groupManager.save(group, (String) group.getCustomData());+ return group.getId();+ }++ @Path("/{groupId}")+ @DELETE+ public Response delete(@PathParam("groupId") Long groupId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ groupManager.delete(groupManager.load(groupId));+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/IssueCommentResource.java b/server-core/src/main/java/io/onedev/server/rest/IssueCommentResource.javanew file mode 100644index 0000000000..ba73b52ca4--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/IssueCommentResource.java@@ -0,0 +1,65 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.IssueCommentManager;+import io.onedev.server.model.IssueComment;+import io.onedev.server.security.SecurityUtils;++@Path("/issue-comments")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class IssueCommentResource {++ private final IssueCommentManager commentManager;++ @Inject+ public IssueCommentResource(IssueCommentManager commentManager) {+ this.commentManager = commentManager;+ }++ @Path("/{commentId}")+ @GET+ public IssueComment get(@PathParam("commentId") Long commentId) {+ IssueComment comment = commentManager.load(commentId);+ if (!SecurityUtils.canAccess(comment.getIssue().getProject()))+ throw new UnauthorizedException();+ return comment;+ }++ @POST+ public Long save(@NotNull IssueComment comment) {+ if (!SecurityUtils.canAccess(comment.getIssue().getProject()) ||+ !SecurityUtils.isAdministrator() && !comment.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }++ commentManager.save(comment);+ return comment.getId();+ }++ @Path("/{commentId}")+ @DELETE+ public Response delete(@PathParam("commentId") Long commentId) {+ IssueComment comment = commentManager.load(commentId);+ if (!SecurityUtils.canModifyOrDelete(comment))+ throw new UnauthorizedException();+ commentManager.delete(comment);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/IssueQuerySettingResource.java b/server-core/src/main/java/io/onedev/server/rest/IssueQuerySettingResource.javanew file mode 100644index 0000000000..d470b2d4bf--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/IssueQuerySettingResource.java@@ -0,0 +1,64 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.IssueQuerySettingManager;+import io.onedev.server.model.IssueQuerySetting;+import io.onedev.server.security.SecurityUtils;++@Path("/issue-query-settings")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class IssueQuerySettingResource {++ private final IssueQuerySettingManager querySettingManager;++ @Inject+ public IssueQuerySettingResource(IssueQuerySettingManager querySettingManager) {+ this.querySettingManager = querySettingManager;+ }++ @Path("/{querySettingId}")+ @GET+ public IssueQuerySetting get(@PathParam("querySettingId") Long querySettingId) {+ IssueQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return querySetting;+ }++ @POST+ public Long save(@NotNull IssueQuerySetting querySetting) {+ if (!SecurityUtils.canAccess(querySetting.getProject())+ || !SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }+ querySettingManager.save(querySetting);+ return querySetting.getId();+ }++ @Path("/{querySettingId}")+ @DELETE+ public Response delete(@PathParam("querySettingId") Long querySettingId) {+ IssueQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ querySettingManager.delete(querySetting);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/IssueResource.java b/server-core/src/main/java/io/onedev/server/rest/IssueResource.javanew file mode 100644index 0000000000..e8e86b78fd--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/IssueResource.java@@ -0,0 +1,431 @@+package io.onedev.server.rest;++import java.io.Serializable;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Date;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.stream.Collectors;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.Valid;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.QueryParam;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthenticatedException;+import org.apache.shiro.authz.UnauthorizedException;+import org.hibernate.validator.constraints.NotEmpty;++import io.onedev.server.entitymanager.IssueChangeManager;+import io.onedev.server.entitymanager.IssueManager;+import io.onedev.server.entitymanager.MilestoneManager;+import io.onedev.server.entitymanager.ProjectManager;+import io.onedev.server.entitymanager.SettingManager;+import io.onedev.server.model.Issue;+import io.onedev.server.model.IssueChange;+import io.onedev.server.model.IssueComment;+import io.onedev.server.model.IssueField;+import io.onedev.server.model.IssueVote;+import io.onedev.server.model.IssueWatch;+import io.onedev.server.model.Milestone;+import io.onedev.server.model.Project;+import io.onedev.server.model.PullRequest;+import io.onedev.server.model.User;+import io.onedev.server.model.support.issue.field.spec.FieldSpec;+import io.onedev.server.rest.jersey.InvalidParamException;+import io.onedev.server.search.entity.issue.IssueQuery;+import io.onedev.server.security.SecurityUtils;++@Path("/issues")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class IssueResource {++ private final SettingManager settingManager;++ private final IssueManager issueManager;++ private final IssueChangeManager issueChangeManager;++ private final MilestoneManager milestoneManager;++ private final ProjectManager projectManager;++ @Inject+ public IssueResource(SettingManager settingManager, IssueManager issueManager,+ IssueChangeManager issueChangeManager, MilestoneManager milestoneManager,+ ProjectManager projectManager) {+ this.settingManager = settingManager;+ this.issueManager = issueManager;+ this.issueChangeManager = issueChangeManager;+ this.milestoneManager = milestoneManager;+ this.projectManager = projectManager;+ }++ @Path("/{issueId}")+ @GET+ public Issue get(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canAccess(issue.getProject()))+ throw new UnauthorizedException();+ return issue;+ }++ @Path("/{issueId}/fields")+ @GET+ public Collection<IssueField> getFields(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canAccess(issue.getProject()))+ throw new UnauthorizedException();+ return issue.getFields();+ }++ @Path("/{issueId}/changes")+ @GET+ public Collection<IssueChange> getChanges(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canAccess(issue.getProject()))+ throw new UnauthorizedException();+ return issue.getChanges();+ }++ @Path("/{issueId}/comments")+ @GET+ public Collection<IssueComment> getComments(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canAccess(issue.getProject()))+ throw new UnauthorizedException();+ return issue.getComments();+ }++ @Path("/{issueId}/votes")+ @GET+ public Collection<IssueVote> getVotes(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canAccess(issue.getProject()))+ throw new UnauthorizedException();+ return issue.getVotes();+ }++ @Path("/{issueId}/watches")+ @GET+ public Collection<IssueWatch> getWatches(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canAccess(issue.getProject()))+ throw new UnauthorizedException();+ return issue.getWatches();+ }++ @Path("/{issueId}/pull-requests")+ @GET+ public Collection<PullRequest> getPullRequests(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canReadCode(issue.getProject()))+ throw new UnauthorizedException();+ return issue.getPullRequests();+ }++ @Path("/{issueId}/commits")+ @GET+ public Collection<String> getCommits(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canReadCode(issue.getProject()))+ throw new UnauthorizedException();+ return issue.getCommits().stream().map(it->it.name()).collect(Collectors.toList());+ }++ @GET+ public List<Issue> query(@QueryParam("query") String query, @QueryParam("offset") int offset,+ @QueryParam("count") int count) {++ if (count > RestConstants.PAGE_SIZE)+ throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);++ IssueQuery parsedQuery;+ try {+ parsedQuery = IssueQuery.parse(null, query, true, true, false, false, false);+ } catch (Exception e) {+ throw new InvalidParamException("Error parsing query", e);+ }++ return issueManager.query(null, parsedQuery, offset, count, false);+ }++ @POST+ public Long open(@NotNull @Valid IssueOpenData data) {+ User user = SecurityUtils.getUser();+ if (user == null)+ throw new UnauthenticatedException();++ Project project = projectManager.load(data.getProjectId());+ if (!SecurityUtils.canAccess(project))+ throw new UnauthorizedException();++ Milestone milestone;+ if (data.getMilestoneId() != null) {+ if (!SecurityUtils.canScheduleIssues(project))+ throw new UnauthorizedException();+ milestone = milestoneManager.load(data.getMilestoneId());+ if (!milestone.getProject().equals(project))+ throw new InvalidParamException("Milestone is not defined in current project");+ } else {+ milestone = null;+ }++ Issue issue = new Issue();+ issue.setTitle(data.getTitle());+ issue.setDescription(data.getDescription());+ issue.setProject(project);+ issue.setSubmitDate(new Date());+ issue.setSubmitter(user);+ issue.setState(settingManager.getIssueSetting().getInitialStateSpec().getName());+ issue.setMilestone(milestone);++ for (Map.Entry<String, String> entry: data.fields.entrySet()) {+ FieldSpec fieldSpec = settingManager.getIssueSetting().getFieldSpec(entry.getKey());+ if (fieldSpec != null) {+ IssueField field = new IssueField();+ field.setIssue(issue);+ field.setName(entry.getKey());+ field.setValue(entry.getValue());+ field.setType(fieldSpec.getType());+ field.setOrdinal(issue.getFieldOrdinal(field.getName(), field.getValue()));+ issue.getFields().add(field);+ }+ }+ issueManager.open(issue);+ return issue.getId();+ }++ @Path("/{issueId}/title")+ @POST+ public Response setTitle(@PathParam("issueId") Long issueId, @NotEmpty String title) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canModify(issue))+ throw new UnauthorizedException();+ issueChangeManager.changeTitle(issue, title);+ return Response.ok().build();+ }++ @Path("/{issueId}/description")+ @POST+ public Response setDescription(@PathParam("issueId") Long issueId, String description) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canModify(issue))+ throw new UnauthorizedException();+ issueChangeManager.changeDescription(issue, description);+ return Response.ok().build();+ }++ @Path("/{issueId}/milestone")+ @POST+ public Response setMilestone(@PathParam("issueId") Long issueId, Long milestoneId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canScheduleIssues(issue.getProject()))+ throw new UnauthorizedException();+ Milestone milestone;+ if (milestoneId != null) {+ milestone = milestoneManager.load(milestoneId);+ if (!milestone.getProject().equals(issue.getProject()))+ throw new InvalidParamException("Milestone is not defined in current project");+ } else {+ milestone = null;+ }+ issueChangeManager.changeMilestone(issue, milestone);+ return Response.ok().build();+ }++ @Path("/{issueId}/fields")+ @POST+ public Response setFields(@PathParam("issueId") Long issueId, @NotNull Map<String, String> fields) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canManageIssues(issue.getProject()))+ throw new UnauthorizedException();++ Map<String, List<String>> fieldLists = new HashMap<>();+ for (Map.Entry<String, String> entry: fields.entrySet()) {+ List<String> values = fieldLists.get(entry.getKey());+ if (values == null) {+ values = new ArrayList<>();+ fieldLists.put(entry.getKey(), values);+ }+ values.add(entry.getValue());+ }++ Map<String, Object> fieldObjs = new HashMap<>();+ for (Map.Entry<String, List<String>> entry: fieldLists.entrySet()) {+ FieldSpec fieldSpec = settingManager.getIssueSetting().getFieldSpec(entry.getKey());+ if (fieldSpec != null)+ fieldObjs.put(entry.getKey(), fieldSpec.convertToObject(entry.getValue()));+ }++ issueChangeManager.changeFields(issue, fieldObjs);+ return Response.ok().build();+ }++ @Path("/{issueId}/state-transitions")+ @POST+ public Response transitState(@PathParam("issueId") Long issueId, @NotNull @Valid StateTransitionData data) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canManageIssues(issue.getProject()))+ throw new UnauthorizedException();++ issueChangeManager.changeState(issue, data.getState(), getFieldObjs(data.getFields()),+ data.getRemoveFields(), data.getComment());+ return Response.ok().build();+ }++ private Map<String, Object> getFieldObjs(Map<String, String> fields) {+ Map<String, List<String>> fieldLists = new HashMap<>();+ for (Map.Entry<String, String> entry: fields.entrySet()) {+ List<String> values = fieldLists.get(entry.getKey());+ if (values == null) {+ values = new ArrayList<>();+ fieldLists.put(entry.getKey(), values);+ }+ values.add(entry.getValue());+ }++ Map<String, Object> fieldObjs = new HashMap<>();+ for (Map.Entry<String, List<String>> entry: fieldLists.entrySet()) {+ FieldSpec fieldSpec = settingManager.getIssueSetting().getFieldSpec(entry.getKey());+ if (fieldSpec != null)+ fieldObjs.put(entry.getKey(), fieldSpec.convertToObject(entry.getValue()));+ }++ return fieldObjs;+ }++ @Path("/{issueId}")+ @DELETE+ public Response delete(@PathParam("issueId") Long issueId) {+ Issue issue = issueManager.load(issueId);+ if (!SecurityUtils.canManageIssues(issue.getProject()))+ throw new UnauthorizedException();+ issueManager.delete(issue);+ return Response.ok().build();+ }++ public static class IssueOpenData implements Serializable {++ private static final long serialVersionUID = 1L;++ private Long projectId;++ private String title;++ private String description;++ private Long milestoneId;++ private Map<String, String> fields = new HashMap<>();++ @NotNull+ public Long getProjectId() {+ return projectId;+ }++ public void setProjectId(Long projectId) {+ this.projectId = projectId;+ }++ @NotNull+ public String getTitle() {+ return title;+ }++ public void setTitle(String title) {+ this.title = title;+ }++ public String getDescription() {+ return description;+ }++ public void setDescription(String description) {+ this.description = description;+ }++ public Long getMilestoneId() {+ return milestoneId;+ }++ public void setMilestoneId(Long milestoneId) {+ this.milestoneId = milestoneId;+ }++ @NotNull+ public Map<String, String> getFields() {+ return fields;+ }++ public void setFields(Map<String, String> fields) {+ this.fields = fields;+ }++ }++ public static class StateTransitionData implements Serializable {++ private static final long serialVersionUID = 1L;++ private String state;++ private Map<String, String> fields = new HashMap<>();++ private Collection<String> removeFields = new HashSet<>();++ private String comment;++ @NotEmpty+ public String getState() {+ return state;+ }++ public void setState(String state) {+ this.state = state;+ }++ @NotNull+ public Map<String, String> getFields() {+ return fields;+ }++ public void setFields(Map<String, String> fields) {+ this.fields = fields;+ }++ @NotNull+ public Collection<String> getRemoveFields() {+ return removeFields;+ }++ public void setRemoveFields(Collection<String> removeFields) {+ this.removeFields = removeFields;+ }++ public String getComment() {+ return comment;+ }++ public void setComment(String comment) {+ this.comment = comment;+ }++ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/IssueVoteResource.java b/server-core/src/main/java/io/onedev/server/rest/IssueVoteResource.javanew file mode 100644index 0000000000..9b04aacd45--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/IssueVoteResource.java@@ -0,0 +1,65 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.IssueVoteManager;+import io.onedev.server.model.IssueVote;+import io.onedev.server.security.SecurityUtils;++@Path("/issue-votes")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class IssueVoteResource {++ private final IssueVoteManager voteManager;++ @Inject+ public IssueVoteResource(IssueVoteManager voteManager) {+ this.voteManager = voteManager;+ }++ @Path("/{voteId}")+ @GET+ public IssueVote get(@PathParam("voteId") Long voteId) {+ IssueVote vote = voteManager.load(voteId);+ if (!SecurityUtils.canAccess(vote.getIssue().getProject()))+ throw new UnauthorizedException();+ return vote;+ }++ @POST+ public Long save(@NotNull IssueVote vote) {+ if (!SecurityUtils.canAccess(vote.getIssue().getProject())+ || !SecurityUtils.isAdministrator() && !vote.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }+ voteManager.save(vote);+ return vote.getId();+ }++ @Path("/{voteId}")+ @DELETE+ public Response delete(@PathParam("voteId") Long voteId) {+ IssueVote vote = voteManager.load(voteId);+ if (!SecurityUtils.isAdministrator() && !vote.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();++ voteManager.delete(vote);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/IssueWatchResource.java b/server-core/src/main/java/io/onedev/server/rest/IssueWatchResource.javanew file mode 100644index 0000000000..480de51fb9--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/IssueWatchResource.java@@ -0,0 +1,65 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.IssueWatchManager;+import io.onedev.server.model.IssueWatch;+import io.onedev.server.security.SecurityUtils;++@Path("/issue-watches")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class IssueWatchResource {++ private final IssueWatchManager watchManager;++ @Inject+ public IssueWatchResource(IssueWatchManager watchManager) {+ this.watchManager = watchManager;+ }++ @Path("/{watchId}")+ @GET+ public IssueWatch get(@PathParam("watchId") Long watchId) {+ IssueWatch watch = watchManager.load(watchId);+ if (!SecurityUtils.canAccess(watch.getIssue().getProject()))+ throw new UnauthorizedException();+ return watch;+ }++ @POST+ public Long save(@NotNull IssueWatch watch) {+ if (!SecurityUtils.canAccess(watch.getIssue().getProject())+ || !SecurityUtils.isAdministrator() && !watch.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }+ watchManager.save(watch);+ return watch.getId();+ }++ @Path("/{watchId}")+ @DELETE+ public Response delete(@PathParam("watchId") Long watchId) {+ IssueWatch watch = watchManager.load(watchId);+ if (!SecurityUtils.isAdministrator() && !watch.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();++ watchManager.delete(watch);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/JobRunResource.java b/server-core/src/main/java/io/onedev/server/rest/JobRunResource.javanew file mode 100644index 0000000000..f1a48ade58--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/JobRunResource.java@@ -0,0 +1,233 @@+package io.onedev.server.rest;++import java.io.Serializable;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.Valid;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;+import org.eclipse.jgit.lib.ObjectId;+import org.hibernate.validator.constraints.NotEmpty;++import io.onedev.server.buildspec.job.JobManager;+import io.onedev.server.buildspec.job.SubmitReason;+import io.onedev.server.entitymanager.BuildManager;+import io.onedev.server.entitymanager.ProjectManager;+import io.onedev.server.entitymanager.PullRequestManager;+import io.onedev.server.model.Build;+import io.onedev.server.model.Project;+import io.onedev.server.model.PullRequest;+import io.onedev.server.security.SecurityUtils;+import io.onedev.server.util.validation.annotation.CommitHash;++@Path("/job-runs")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class JobRunResource {++ private final JobManager jobManager;++ private final BuildManager buildManager;++ private final ProjectManager projectManager;++ private final PullRequestManager pullRequestManager;++ @Inject+ public JobRunResource(JobManager jobManager, BuildManager buildManager,+ ProjectManager projectManager, PullRequestManager pullRequestManager) {+ this.jobManager = jobManager;+ this.buildManager = buildManager;+ this.projectManager = projectManager;+ this.pullRequestManager = pullRequestManager;+ }++ @POST+ public Long save(@NotNull @Valid JobRun jobRun) {+ Project project = projectManager.load(jobRun.projectId);+ if (!SecurityUtils.canRunJob(project, jobRun.jobName))+ throw new UnauthorizedException();++ SubmitReason reason = new SubmitReason() {++ @Override+ public String getRefName() {+ return jobRun.refName;+ }++ @Override+ public PullRequest getPullRequest() {+ if (jobRun.pullRequestId != null)+ return pullRequestManager.load(jobRun.pullRequestId);+ else+ return null;+ }++ @Override+ public String getDescription() {+ return jobRun.reason;+ }++ };+ return jobManager.submit(project, ObjectId.fromString(jobRun.commitHash),+ jobRun.jobName, jobRun.params, reason).getId();+ }++ @Path("/rerun")+ @POST+ public Response save(@NotNull @Valid JobRerun jobRerun) {+ Build build = buildManager.load(jobRerun.buildId);+ if (!SecurityUtils.canRunJob(build.getProject(), build.getJobName()))+ throw new UnauthorizedException();+ jobManager.resubmit(build, jobRerun.params, jobRerun.reason);+ return Response.ok().build();+ }++ @Path("/{buildId}")+ @DELETE+ public Response delete(@PathParam("buildId") Long buildId) {+ Build build = buildManager.load(buildId);+ if (!SecurityUtils.canRunJob(build.getProject(), build.getJobName()))+ throw new UnauthorizedException();+ if (!build.isFinished())+ jobManager.cancel(build);+ return Response.ok().build();+ }++ public static class JobRun implements Serializable {++ private static final long serialVersionUID = 1L;++ private Long projectId;++ private String commitHash;++ private String jobName;++ private Map<String, List<String>> params = new HashMap<>();++ private String refName;++ private Long pullRequestId;++ private String reason;++ @NotNull+ public Long getProjectId() {+ return projectId;+ }++ public void setProjectId(Long projectId) {+ this.projectId = projectId;+ }++ @CommitHash+ @NotEmpty+ public String getCommitHash() {+ return commitHash;+ }++ public void setCommitHash(String commitHash) {+ this.commitHash = commitHash;+ }++ @NotEmpty+ public String getJobName() {+ return jobName;+ }++ public void setJobName(String jobName) {+ this.jobName = jobName;+ }++ @NotNull+ public Map<String, List<String>> getParams() {+ return params;+ }++ public void setParams(Map<String, List<String>> params) {+ this.params = params;+ }++ @NotEmpty+ public String getRefName() {+ return refName;+ }++ public void setRefName(String refName) {+ this.refName = refName;+ }++ public Long getPullRequestId() {+ return pullRequestId;+ }++ public void setPullRequestId(Long pullRequestId) {+ this.pullRequestId = pullRequestId;+ }++ @NotEmpty+ public String getReason() {+ return reason;+ }++ public void setReason(String reason) {+ this.reason = reason;+ }++ }++ public static class JobRerun implements Serializable {++ private static final long serialVersionUID = 1L;++ private Long buildId;++ private Map<String, List<String>> params = new HashMap<>();++ private String reason;++ @NotNull+ public Long getBuildId() {+ return buildId;+ }++ public void setBuildId(Long buildId) {+ this.buildId = buildId;+ }++ @NotNull+ public Map<String, List<String>> getParams() {+ return params;+ }++ public void setParams(Map<String, List<String>> params) {+ this.params = params;+ }++ @NotEmpty+ public String getReason() {+ return reason;+ }++ public void setReason(String reason) {+ this.reason = reason;+ }++ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/MembershipResource.java b/server-core/src/main/java/io/onedev/server/rest/MembershipResource.javanew file mode 100644index 0000000000..0f3ca5e1b7--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/MembershipResource.java@@ -0,0 +1,60 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.MembershipManager;+import io.onedev.server.model.Membership;+import io.onedev.server.security.SecurityUtils;++@Path("/memberships")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class MembershipResource {++ private final MembershipManager membershipManager;++ @Inject+ public MembershipResource(MembershipManager membershipManager) {+ this.membershipManager = membershipManager;+ }++ @Path("/{membershipId}")+ @GET+ public Membership get(@PathParam("membershipId") Long membershipId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return membershipManager.load(membershipId);+ }++ @POST+ public Long save(@NotNull Membership membership) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ membershipManager.save(membership);+ return membership.getId();+ }++ @Path("/{membershipId}")+ @DELETE+ public Response delete(@PathParam("membershipId") Long membershipId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ membershipManager.delete(membershipManager.load(membershipId));+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/MilestoneResource.java b/server-core/src/main/java/io/onedev/server/rest/MilestoneResource.javanew file mode 100644index 0000000000..33baf28caf--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/MilestoneResource.java@@ -0,0 +1,62 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.MilestoneManager;+import io.onedev.server.model.Milestone;+import io.onedev.server.security.SecurityUtils;++@Path("/milestones")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class MilestoneResource {++ private final MilestoneManager milestoneManager;++ @Inject+ public MilestoneResource(MilestoneManager milestoneManager) {+ this.milestoneManager = milestoneManager;+ }++ @Path("/{milestoneId}")+ @GET+ public Milestone get(@PathParam("milestoneId") Long milestoneId) {+ Milestone milestone = milestoneManager.load(milestoneId);+ if (!SecurityUtils.canAccess(milestone.getProject()))+ throw new UnauthorizedException();+ return milestone;+ }++ @POST+ public Long save(@NotNull Milestone milestone) {+ if (!SecurityUtils.canManageIssues(milestone.getProject()))+ throw new UnauthorizedException();+ milestoneManager.save(milestone);+ return milestone.getId();+ }++ @Path("/{milestoneId}")+ @DELETE+ public Response delete(@PathParam("milestoneId") Long milestoneId) {+ Milestone milestone = milestoneManager.load(milestoneId);+ if (!SecurityUtils.canManageIssues(milestone.getProject()))+ throw new UnauthorizedException();+ milestoneManager.delete(milestone);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/ProjectResource.java b/server-core/src/main/java/io/onedev/server/rest/ProjectResource.javaindex c12813f5cf..725fde5c3e 100644--- a/server-core/src/main/java/io/onedev/server/rest/ProjectResource.java+++ b/server-core/src/main/java/io/onedev/server/rest/ProjectResource.java@@ -2,6 +2,8 @@ package io.onedev.server.rest;import java.io.Serializable;import java.util.ArrayList;+import java.util.Collection;+import java.util.Date;import java.util.List;import javax.inject.Inject;@@ -20,9 +22,14 @@ import javax.ws.rs.core.Response;import org.apache.shiro.authz.UnauthenticatedException;import org.apache.shiro.authz.UnauthorizedException;+import org.hibernate.criterion.Restrictions;+import io.onedev.server.entitymanager.MilestoneManager;import io.onedev.server.entitymanager.ProjectManager;+import io.onedev.server.model.GroupAuthorization;+import io.onedev.server.model.Milestone;import io.onedev.server.model.Project;+import io.onedev.server.model.UserAuthorization;import io.onedev.server.model.support.BranchProtection;import io.onedev.server.model.support.NamedCodeCommentQuery;import io.onedev.server.model.support.NamedCommitQuery;@@ -31,6 +38,7 @@ import io.onedev.server.model.support.WebHook;import io.onedev.server.model.support.build.ProjectBuildSetting;import io.onedev.server.model.support.issue.ProjectIssueSetting;import io.onedev.server.model.support.pullrequest.ProjectPullRequestSetting;+import io.onedev.server.persistence.dao.EntityCriteria;import io.onedev.server.rest.jersey.InvalidParamException;import io.onedev.server.search.entity.project.ProjectQuery;import io.onedev.server.security.SecurityUtils;@@ -43,9 +51,12 @@ public class ProjectResource {private final ProjectManager projectManager;+ private final MilestoneManager milestoneManager;+@Inject- public ProjectResource(ProjectManager projectManager) {+ public ProjectResource(ProjectManager projectManager, MilestoneManager milestoneManager) {this.projectManager = projectManager;+ this.milestoneManager = milestoneManager;}@Path("/{projectId}")@@ -75,16 +86,64 @@ public class ProjectResource {return setting;}+ @Path("/{projectId}/forks")+ @GET+ public Collection<Project> getForks(@PathParam("projectId") Long projectId) {+ Project project = projectManager.load(projectId);+ if (!SecurityUtils.canAccess(project))+ throw new UnauthorizedException();+ return project.getForks();+ }++ @Path("/{projectId}/group-authorizations")+ @GET+ public Collection<GroupAuthorization> getGroupAuthorizations(@PathParam("projectId") Long projectId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return projectManager.load(projectId).getGroupAuthorizations();+ }++ @Path("/{projectId}/user-authorizations")+ @GET+ public Collection<UserAuthorization> getUserAuthorizations(@PathParam("projectId") Long projectId) {+ Project project = projectManager.load(projectId);+ if (!SecurityUtils.canManage(project))+ throw new UnauthorizedException();+ return project.getUserAuthorizations();+ }++ @Path("/{projectId}/milestones")+ @GET+ public List<Milestone> queryMilestones(@PathParam("projectId") Long projectId, @QueryParam("name") String name,+ @QueryParam("dueBefore") Date dueBefore, @QueryParam("dueAfter") Date dueAfter,+ @QueryParam("closed") Boolean closed, @QueryParam("offset") int offset,+ @QueryParam("count") int count) {+ Project project = projectManager.load(projectId);+ if (!SecurityUtils.canAccess(project))+ throw new UnauthorizedException();++ if (count > RestConstants.PAGE_SIZE)+ throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);++ EntityCriteria<Milestone> criteria = EntityCriteria.of(Milestone.class);+ criteria.add(Restrictions.eq(Milestone.PROP_PROJECT, project));+ if (name != null)+ criteria.add(Restrictions.ilike(Milestone.PROP_NAME, name.replace('%', '*')));+ if (dueBefore != null)+ criteria.add(Restrictions.le(Milestone.PROP_DUE_DATE, dueBefore));+ if (dueAfter != null)+ criteria.add(Restrictions.ge(Milestone.PROP_DUE_DATE, dueAfter));+ if (closed != null)+ criteria.add(Restrictions.eq(Milestone.PROP_CLOSED, closed));++ return milestoneManager.query(criteria, offset, count);+ }+@GET- public List<Project> query(@QueryParam("query") String query, @QueryParam("offset") Integer offset,- @QueryParam("count") Integer count) {+ public List<Project> query(@QueryParam("query") String query, @QueryParam("offset") int offset,+ @QueryParam("count") int count) {- if (offset == null)- offset = 0;-- if (count == null)- count = RestConstants.PAGE_SIZE;- else if (count > RestConstants.PAGE_SIZE)+ if (count > RestConstants.PAGE_SIZE)throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);ProjectQuery parsedQuery;diff --git a/server-core/src/main/java/io/onedev/server/rest/PullRequestAssignmentResource.java b/server-core/src/main/java/io/onedev/server/rest/PullRequestAssignmentResource.javanew file mode 100644index 0000000000..2d9ea673e4--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/PullRequestAssignmentResource.java@@ -0,0 +1,73 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.commons.utils.ExplicitException;+import io.onedev.server.entitymanager.PullRequestAssignmentManager;+import io.onedev.server.model.PullRequest;+import io.onedev.server.model.PullRequestAssignment;+import io.onedev.server.security.SecurityUtils;++@Path("/pull-request-assignments")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class PullRequestAssignmentResource {++ private final PullRequestAssignmentManager assignmentManager;++ @Inject+ public PullRequestAssignmentResource(PullRequestAssignmentManager assignmentManager) {+ this.assignmentManager = assignmentManager;+ }++ @Path("/{assignmentId}")+ @GET+ public PullRequestAssignment get(@PathParam("assignmentId") Long assignmentId) {+ PullRequestAssignment assignment = assignmentManager.load(assignmentId);+ if (!SecurityUtils.canReadCode(assignment.getRequest().getProject()))+ throw new UnauthorizedException();+ return assignment;+ }++ @POST+ public Long save(PullRequestAssignment assignment) {+ PullRequest pullRequest = assignment.getRequest();+ if (!SecurityUtils.canReadCode(pullRequest.getProject()) || !SecurityUtils.canModify(pullRequest))+ throw new UnauthorizedException();++ if (pullRequest.isMerged())+ throw new ExplicitException("Pull request is merged");+ assignmentManager.addAssignee(assignment);+ return assignment.getId();+ }++ @Path("/{assignmentId}")+ @DELETE+ public Response delete(@PathParam("assignmentId") Long assignmentId) {+ PullRequestAssignment assignment = assignmentManager.load(assignmentId);++ if (!SecurityUtils.canReadCode(assignment.getRequest().getProject())+ || !SecurityUtils.canModify(assignment.getRequest())) {+ throw new UnauthorizedException();+ }+ if (assignment.getRequest().isMerged())+ throw new ExplicitException("Pull request is merged");++ assignmentManager.removeAssignee(assignment);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/PullRequestCommentResource.java b/server-core/src/main/java/io/onedev/server/rest/PullRequestCommentResource.javanew file mode 100644index 0000000000..b5b9358aa3--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/PullRequestCommentResource.java@@ -0,0 +1,65 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.PullRequestCommentManager;+import io.onedev.server.model.PullRequestComment;+import io.onedev.server.security.SecurityUtils;++@Path("/pull-request-comments")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class PullRequestCommentResource {++ private final PullRequestCommentManager commentManager;++ @Inject+ public PullRequestCommentResource(PullRequestCommentManager commentManager) {+ this.commentManager = commentManager;+ }++ @Path("/{commentId}")+ @GET+ public PullRequestComment get(@PathParam("commentId") Long commentId) {+ PullRequestComment comment = commentManager.load(commentId);+ if (!SecurityUtils.canReadCode(comment.getProject()))+ throw new UnauthorizedException();+ return comment;+ }++ @POST+ public Long save(@NotNull PullRequestComment comment) {+ if (!SecurityUtils.canReadCode(comment.getProject()) ||+ !SecurityUtils.isAdministrator() && !comment.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }++ commentManager.save(comment);+ return comment.getId();+ }++ @Path("/{commentId}")+ @DELETE+ public Response delete(@PathParam("commentId") Long commentId) {+ PullRequestComment comment = commentManager.load(commentId);+ if (!SecurityUtils.canModifyOrDelete(comment))+ throw new UnauthorizedException();+ commentManager.delete(comment);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/PullRequestQuerySettingResource.java b/server-core/src/main/java/io/onedev/server/rest/PullRequestQuerySettingResource.javanew file mode 100644index 0000000000..e96eb80a73--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/PullRequestQuerySettingResource.java@@ -0,0 +1,64 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.PullRequestQuerySettingManager;+import io.onedev.server.model.PullRequestQuerySetting;+import io.onedev.server.security.SecurityUtils;++@Path("/pull-request-query-settings")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class PullRequestQuerySettingResource {++ private final PullRequestQuerySettingManager querySettingManager;++ @Inject+ public PullRequestQuerySettingResource(PullRequestQuerySettingManager querySettingManager) {+ this.querySettingManager = querySettingManager;+ }++ @Path("/{querySettingId}")+ @GET+ public PullRequestQuerySetting get(@PathParam("querySettingId") Long querySettingId) {+ PullRequestQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return querySetting;+ }++ @POST+ public Long save(@NotNull PullRequestQuerySetting querySetting) {+ if (!SecurityUtils.canAccess(querySetting.getProject())+ || !SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }+ querySettingManager.save(querySetting);+ return querySetting.getId();+ }++ @Path("/{querySettingId}")+ @DELETE+ public Response delete(@PathParam("querySettingId") Long querySettingId) {+ PullRequestQuerySetting querySetting = querySettingManager.load(querySettingId);+ if (!SecurityUtils.isAdministrator() && !querySetting.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ querySettingManager.delete(querySetting);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/PullRequestResource.java b/server-core/src/main/java/io/onedev/server/rest/PullRequestResource.javanew file mode 100644index 0000000000..da19ee14ec--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/PullRequestResource.java@@ -0,0 +1,475 @@+package io.onedev.server.rest;++import java.io.Serializable;+import java.util.ArrayList;+import java.util.Collection;+import java.util.List;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.QueryParam;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthenticatedException;+import org.apache.shiro.authz.UnauthorizedException;+import org.eclipse.jgit.lib.ObjectId;+import org.hibernate.validator.constraints.NotEmpty;+import org.joda.time.DateTime;++import com.google.common.collect.Lists;++import io.onedev.commons.utils.ExplicitException;+import io.onedev.server.entitymanager.PullRequestChangeManager;+import io.onedev.server.entitymanager.PullRequestManager;+import io.onedev.server.entitymanager.UserManager;+import io.onedev.server.git.GitUtils;+import io.onedev.server.model.Build;+import io.onedev.server.model.PullRequest;+import io.onedev.server.model.PullRequestAssignment;+import io.onedev.server.model.PullRequestChange;+import io.onedev.server.model.PullRequestComment;+import io.onedev.server.model.PullRequestReview;+import io.onedev.server.model.PullRequestUpdate;+import io.onedev.server.model.PullRequestWatch;+import io.onedev.server.model.User;+import io.onedev.server.model.support.pullrequest.MergePreview;+import io.onedev.server.model.support.pullrequest.MergeStrategy;+import io.onedev.server.rest.jersey.InvalidParamException;+import io.onedev.server.search.entity.pullrequest.PullRequestQuery;+import io.onedev.server.security.SecurityUtils;+import io.onedev.server.util.ProjectAndBranch;++@Path("/pull-requests")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class PullRequestResource {++ private final PullRequestManager pullRequestManager;++ private final PullRequestChangeManager pullRequestChangeManager;++ private final UserManager userManager;++ @Inject+ public PullRequestResource(PullRequestManager pullRequestManager,+ PullRequestChangeManager pullRequestChangeManager, UserManager userManager) {+ this.pullRequestManager = pullRequestManager;+ this.pullRequestChangeManager = pullRequestChangeManager;+ this.userManager = userManager;+ }++ @Path("/{requestId}")+ @GET+ public PullRequest get(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest;+ }++ @Path("/{requestId}/merge-preview")+ @GET+ public MergePreview getMergePreview(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getMergePreview();+ }++ @Path("/{requestId}/assignments")+ @GET+ public Collection<PullRequestAssignment> getAssignments(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getAssignments();+ }++ @Path("/{requestId}/reviews")+ @GET+ public Collection<PullRequestReview> getReviews(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getReviews();+ }++ @Path("/{requestId}/comments")+ @GET+ public Collection<PullRequestComment> getComments(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getComments();+ }++ @Path("/{requestId}/watches")+ @GET+ public Collection<PullRequestWatch> getWatches(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getWatches();+ }++ @Path("/{requestId}/updates")+ @GET+ public Collection<PullRequestUpdate> getUpdates(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getSortedUpdates();+ }++ @Path("/{requestId}/current-builds")+ @GET+ public Collection<Build> getCurrentBuilds(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getCurrentBuilds();+ }++ @Path("/{requestId}/changes")+ @GET+ public Collection<PullRequestChange> getChanges(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getChanges();+ }++ @Path("/{requestId}/fixed-issue-numbers")+ @GET+ public Collection<Long> getFixedIssueNumbers(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))+ throw new UnauthorizedException();+ return pullRequest.getFixedIssueNumbers();+ }++ @GET+ public List<PullRequest> query(@QueryParam("query") String query, @QueryParam("offset") int offset,+ @QueryParam("count") int count) {++ if (count > RestConstants.PAGE_SIZE)+ throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);++ PullRequestQuery parsedQuery;+ try {+ parsedQuery = PullRequestQuery.parse(null, query);+ } catch (Exception e) {+ throw new InvalidParamException("Error parsing query", e);+ }++ return pullRequestManager.query(null, parsedQuery, offset, count, false, false);+ }++ @POST+ public Long open(@NotNull PullRequestOpenData data) {+ User user = SecurityUtils.getUser();+ if (user == null)+ throw new UnauthenticatedException();++ ProjectAndBranch target = new ProjectAndBranch(data.getTargetProjectId(), data.getTargetBranch());+ ProjectAndBranch source = new ProjectAndBranch(data.getSourceProjectId(), data.getSourceBranch());++ if (!SecurityUtils.canReadCode(target.getProject()) || !SecurityUtils.canReadCode(source.getProject()))+ throw new UnauthorizedException();++ if (target.equals(source))+ throw new InvalidParamException("Source and target are the same");++ PullRequest request = pullRequestManager.findLatest(target.getProject());+ if (request != null && source.equals(request.getSource()) && target.equals(request.getTarget()) && request.isOpen())+ throw new InvalidParamException("Another pull request already open for this change");++ request = pullRequestManager.findEffective(target, source);+ if (request != null) {+ if (request.isOpen())+ throw new InvalidParamException("Another pull request already open for this change");+ else+ throw new InvalidParamException("Change already merged");+ }++ request = new PullRequest();+ ObjectId baseCommitId = GitUtils.getMergeBase(+ target.getProject().getRepository(), target.getObjectId(),+ source.getProject().getRepository(), source.getObjectId());++ if (baseCommitId == null)+ throw new InvalidParamException("No common base for target and source");++ request.setTitle(data.getTitle());+ request.setTarget(target);+ request.setSource(source);+ request.setSubmitter(user);+ request.setBaseCommitHash(baseCommitId.name());+ request.setDescription(data.getDescription());+ request.setMergeStrategy(data.getMergeStrategy());++ if (request.getBaseCommitHash().equals(source.getObjectName()))+ throw new InvalidParamException("Change already merged");++ PullRequestUpdate update = new PullRequestUpdate();+ update.setDate(new DateTime(request.getSubmitDate()).plusSeconds(1).toDate());+ request.getUpdates().add(update);+ request.setUpdates(request.getUpdates());+ update.setRequest(request);+ update.setHeadCommitHash(source.getObjectName());+ update.setTargetHeadCommitHash(request.getTarget().getObjectName());+ request.getUpdates().add(update);++ pullRequestManager.checkReviews(request, Lists.newArrayList());+ for (Long reviewerId: data.getReviewerIds()) {+ User reviewer = userManager.load(reviewerId);+ if (request.getReview(reviewer) == null) {+ PullRequestReview review = new PullRequestReview();+ review.setRequest(request);+ review.setUser(reviewer);+ request.getReviews().add(review);+ }+ }++ for (Long assigneeId: data.getAssigneeIds()) {+ PullRequestAssignment assignment = new PullRequestAssignment();+ assignment.setRequest(request);+ assignment.setUser(userManager.load(assigneeId));+ request.getAssignments().add(assignment);+ }++ pullRequestManager.open(request);+ return request.getId();+ }++ @Path("/{requestId}/title")+ @POST+ public Response setTitle(@PathParam("requestId") Long requestId, @NotEmpty String title) {+ PullRequest request = pullRequestManager.load(requestId);+ if (!SecurityUtils.canModify(request))+ throw new UnauthorizedException();+ pullRequestChangeManager.changeTitle(request, title);+ return Response.ok().build();+ }++ @Path("/{requestId}/description")+ @POST+ public Response setDescription(@PathParam("requestId") Long requestId, String description) {+ PullRequest request = pullRequestManager.load(requestId);+ if (!SecurityUtils.canModify(request))+ throw new UnauthorizedException();+ pullRequestChangeManager.changeDescription(request, description);+ return Response.ok().build();+ }++ @Path("/{requestId}/merge-strategy")+ @POST+ public Response setMergeStrategy(@PathParam("requestId") Long requestId, @NotNull MergeStrategy mergeStrategy) {+ PullRequest request = pullRequestManager.load(requestId);+ if (!SecurityUtils.canModify(request))+ throw new UnauthorizedException();+ pullRequestChangeManager.changeMergeStrategy(request, mergeStrategy);+ return Response.ok().build();+ }++ @Path("/{requestId}/reopen")+ @POST+ public Response reopen(@PathParam("requestId") Long requestId, String note) {+ PullRequest request = pullRequestManager.load(requestId);+ if (!SecurityUtils.canModify(request))+ throw new UnauthorizedException();+ String errorMessage = request.checkReopen();+ if (errorMessage != null)+ throw new ExplicitException(errorMessage);++ pullRequestManager.reopen(request, note);+ return Response.ok().build();+ }++ @Path("/{requestId}/discard")+ @POST+ public Response discard(@PathParam("requestId") Long requestId, String note) {+ PullRequest request = pullRequestManager.load(requestId);+ if (!SecurityUtils.canModify(request))+ throw new UnauthorizedException();+ if (!request.isOpen())+ throw new ExplicitException("Pull request already closed");++ pullRequestManager.discard(request, note);+ return Response.ok().build();+ }++ @Path("/{requestId}/merge")+ @POST+ public Response merge(@PathParam("requestId") Long requestId, String note) {+ PullRequest request = pullRequestManager.load(requestId);+ if (!SecurityUtils.canWriteCode(request.getProject()))+ throw new UnauthorizedException();+ String errorMessage = request.checkMerge();+ if (errorMessage != null)+ throw new ExplicitException(errorMessage);++ pullRequestManager.merge(request, note);+ return Response.ok().build();+ }++ @Path("/{requestId}/delete-source-branch")+ @POST+ public Response deleteSourceBranch(@PathParam("requestId") Long requestId, String note) {+ PullRequest request = pullRequestManager.load(requestId);++ if (!SecurityUtils.canModify(request)+ || !SecurityUtils.canDeleteBranch(request.getSourceProject(), request.getSourceBranch())) {+ throw new UnauthorizedException();+ }++ String errorMessage = request.checkDeleteSourceBranch();+ if (errorMessage != null)+ throw new ExplicitException(errorMessage);++ pullRequestManager.deleteSourceBranch(request, note);+ return Response.ok().build();+ }++ @Path("/{requestId}/restore-source-branch")+ @POST+ public Response restoreSourceBranch(@PathParam("requestId") Long requestId, String note) {+ PullRequest request = pullRequestManager.load(requestId);++ if (!SecurityUtils.canModify(request) ||+ !SecurityUtils.canWriteCode(request.getSourceProject())) {+ throw new UnauthorizedException();+ }++ String errorMessage = request.checkRestoreSourceBranch();+ if (errorMessage != null)+ throw new ExplicitException(errorMessage);++ pullRequestManager.restoreSourceBranch(request, note);+ return Response.ok().build();+ }++ @Path("/{requestId}")+ @DELETE+ public Response delete(@PathParam("requestId") Long requestId) {+ PullRequest pullRequest = pullRequestManager.load(requestId);+ if (!SecurityUtils.canManagePullRequests(pullRequest.getProject()))+ throw new UnauthorizedException();+ pullRequestManager.delete(pullRequest);+ return Response.ok().build();+ }++ public static class PullRequestOpenData implements Serializable {++ private static final long serialVersionUID = 1L;++ private Long targetProjectId;++ private Long sourceProjectId;++ private String targetBranch;++ private String sourceBranch;++ private String title;++ private String description;++ private MergeStrategy mergeStrategy = MergeStrategy.CREATE_MERGE_COMMIT;++ private Collection<Long> reviewerIds = new ArrayList<>();++ private Collection<Long> assigneeIds = new ArrayList<>();++ @NotNull+ public Long getTargetProjectId() {+ return targetProjectId;+ }++ public void setTargetProjectId(Long targetProjectId) {+ this.targetProjectId = targetProjectId;+ }++ @NotNull+ public Long getSourceProjectId() {+ return sourceProjectId;+ }++ public void setSourceProjectId(Long sourceProjectId) {+ this.sourceProjectId = sourceProjectId;+ }++ @NotNull+ public String getTargetBranch() {+ return targetBranch;+ }++ public void setTargetBranch(String targetBranch) {+ this.targetBranch = targetBranch;+ }++ @NotNull+ public String getSourceBranch() {+ return sourceBranch;+ }++ public void setSourceBranch(String sourceBranch) {+ this.sourceBranch = sourceBranch;+ }++ @NotEmpty+ public String getTitle() {+ return title;+ }++ public void setTitle(String title) {+ this.title = title;+ }++ public String getDescription() {+ return description;+ }++ public void setDescription(String description) {+ this.description = description;+ }++ @NotNull+ public MergeStrategy getMergeStrategy() {+ return mergeStrategy;+ }++ public void setMergeStrategy(MergeStrategy mergeStrategy) {+ this.mergeStrategy = mergeStrategy;+ }++ @NotNull+ public Collection<Long> getReviewerIds() {+ return reviewerIds;+ }++ public void setReviewerIds(Collection<Long> reviewerIds) {+ this.reviewerIds = reviewerIds;+ }++ @NotNull+ public Collection<Long> getAssigneeIds() {+ return assigneeIds;+ }++ public void setAssigneeIds(Collection<Long> assigneeIds) {+ this.assigneeIds = assigneeIds;+ }++ }+}diff --git a/server-core/src/main/java/io/onedev/server/rest/PullRequestReviewResource.java b/server-core/src/main/java/io/onedev/server/rest/PullRequestReviewResource.javanew file mode 100644index 0000000000..75c84dd9fe--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/PullRequestReviewResource.java@@ -0,0 +1,81 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import com.google.common.collect.Lists;++import io.onedev.commons.utils.ExplicitException;+import io.onedev.server.entitymanager.PullRequestReviewManager;+import io.onedev.server.model.PullRequestReview;+import io.onedev.server.security.SecurityUtils;++@Path("/pull-request-reviews")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class PullRequestReviewResource {++ private final PullRequestReviewManager reviewManager;++ @Inject+ public PullRequestReviewResource(PullRequestReviewManager reviewManager) {+ this.reviewManager = reviewManager;+ }++ @Path("/{reviewId}")+ @GET+ public PullRequestReview get(@PathParam("reviewId") Long reviewId) {+ PullRequestReview review = reviewManager.load(reviewId);+ if (!SecurityUtils.canReadCode(review.getRequest().getProject()))+ throw new UnauthorizedException();+ return review;+ }++ @POST+ public Long save(@NotNull PullRequestReview review) {+ if (!SecurityUtils.canReadCode(review.getRequest().getProject())+ || !SecurityUtils.isAdministrator() && !review.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }++ if (review.getRequest().isMerged())+ throw new ExplicitException("Pull request is merged");++ if (review.getResult() != null)+ reviewManager.review(review);+ else+ reviewManager.addReviewer(review);+ return review.getId();+ }++ @Path("/{reviewId}")+ @DELETE+ public Response delete(@PathParam("reviewId") Long reviewId) {+ PullRequestReview review = reviewManager.load(reviewId);+ if (!SecurityUtils.canReadCode(review.getRequest().getProject())+ || !SecurityUtils.canModify(review.getRequest())) {+ throw new UnauthorizedException();+ }++ if (!reviewManager.removeReviewer(review, Lists.newArrayList())) {+ throw new ExplicitException("Reviewer '" + review.getUser().getDisplayName()+ + "' is required and can not be removed");+ }++ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/PullRequestWatchResource.java b/server-core/src/main/java/io/onedev/server/rest/PullRequestWatchResource.javanew file mode 100644index 0000000000..a51308fe2f--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/PullRequestWatchResource.java@@ -0,0 +1,65 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.PullRequestWatchManager;+import io.onedev.server.model.PullRequestWatch;+import io.onedev.server.security.SecurityUtils;++@Path("/pull-request-watches")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class PullRequestWatchResource {++ private final PullRequestWatchManager watchManager;++ @Inject+ public PullRequestWatchResource(PullRequestWatchManager watchManager) {+ this.watchManager = watchManager;+ }++ @Path("/{watchId}")+ @GET+ public PullRequestWatch get(@PathParam("watchId") Long watchId) {+ PullRequestWatch watch = watchManager.load(watchId);+ if (!SecurityUtils.canReadCode(watch.getRequest().getProject()))+ throw new UnauthorizedException();+ return watch;+ }++ @POST+ public Long save(@NotNull PullRequestWatch watch) {+ if (!SecurityUtils.canReadCode(watch.getRequest().getProject())+ || !SecurityUtils.isAdministrator() && !watch.getUser().equals(SecurityUtils.getUser())) {+ throw new UnauthorizedException();+ }+ watchManager.save(watch);+ return watch.getId();+ }++ @Path("/{watchId}")+ @DELETE+ public Response delete(@PathParam("watchId") Long watchId) {+ PullRequestWatch watch = watchManager.load(watchId);+ if (!SecurityUtils.isAdministrator() && !watch.getUser().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();++ watchManager.delete(watch);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/RoleResource.java b/server-core/src/main/java/io/onedev/server/rest/RoleResource.javanew file mode 100644index 0000000000..fe05872c04--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/RoleResource.java@@ -0,0 +1,84 @@+package io.onedev.server.rest;++import java.util.List;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.QueryParam;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;+import org.hibernate.criterion.MatchMode;+import org.hibernate.criterion.Restrictions;++import io.onedev.server.entitymanager.RoleManager;+import io.onedev.server.model.Role;+import io.onedev.server.persistence.dao.EntityCriteria;+import io.onedev.server.rest.jersey.InvalidParamException;+import io.onedev.server.security.SecurityUtils;++@Path("/roles")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class RoleResource {++ private final RoleManager roleManager;++ @Inject+ public RoleResource(RoleManager roleManager) {+ this.roleManager = roleManager;+ }++ @Path("/{roleId}")+ @GET+ public Role get(@PathParam("roleId") Long roleId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return roleManager.load(roleId);+ }++ @GET+ public List<Role> query(@QueryParam("name") String name, @QueryParam("offset") int offset,+ @QueryParam("count") int count) {++ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();++ if (count > RestConstants.PAGE_SIZE)+ throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);++ EntityCriteria<Role> criteria = EntityCriteria.of(Role.class);+ if (name != null)+ criteria.add(Restrictions.ilike("name", name.replace('*', '%'), MatchMode.EXACT));++ return roleManager.query(criteria, offset, count);+ }++ @POST+ public Long save(@NotNull Role role) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ roleManager.save(role, (String) role.getCustomData());+ return role.getId();+ }++ @Path("/{roleId}")+ @DELETE+ public Response delete(@PathParam("roleId") Long roleId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ roleManager.delete(roleManager.load(roleId));+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/SettingResource.java b/server-core/src/main/java/io/onedev/server/rest/SettingResource.javanew file mode 100644index 0000000000..bd8dccd701--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/SettingResource.java@@ -0,0 +1,268 @@+package io.onedev.server.rest;++import java.util.List;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.SettingManager;+import io.onedev.server.model.support.administration.BackupSetting;+import io.onedev.server.model.support.administration.GlobalBuildSetting;+import io.onedev.server.model.support.administration.GlobalIssueSetting;+import io.onedev.server.model.support.administration.GlobalProjectSetting;+import io.onedev.server.model.support.administration.GlobalPullRequestSetting;+import io.onedev.server.model.support.administration.GroovyScript;+import io.onedev.server.model.support.administration.MailSetting;+import io.onedev.server.model.support.administration.SecuritySetting;+import io.onedev.server.model.support.administration.SshSetting;+import io.onedev.server.model.support.administration.SystemSetting;+import io.onedev.server.model.support.administration.authenticator.Authenticator;+import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;+import io.onedev.server.model.support.administration.sso.SsoConnector;+import io.onedev.server.security.SecurityUtils;++@Path("/settings")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class SettingResource {++ private final SettingManager settingManager;++ @Inject+ public SettingResource(SettingManager settingManager) {+ this.settingManager = settingManager;+ }++ @Path("/system")+ @GET+ public SystemSetting getSystemSetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getSystemSetting();+ }++ @Path("/authenticator")+ @GET+ public Authenticator getAuthenticator() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getAuthenticator();+ }++ @Path("/backup")+ @GET+ public BackupSetting getBackupSetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getBackupSetting();+ }++ @Path("/build")+ @GET+ public GlobalBuildSetting getBuildSetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getBuildSetting();+ }++ @Path("/groovy-scripts")+ @GET+ public List<GroovyScript> getGroovyScripts() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getGroovyScripts();+ }++ @Path("/issue")+ @GET+ public GlobalIssueSetting getIssueSetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getIssueSetting();+ }++ @Path("/job-executors")+ @GET+ public List<JobExecutor> getJobExecutors() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getJobExecutors();+ }++ @Path("/mail")+ @GET+ public MailSetting getMailSetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getMailSetting();+ }++ @Path("/project")+ @GET+ public GlobalProjectSetting getProjectSetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getProjectSetting();+ }++ @Path("/pull-request")+ @GET+ public GlobalPullRequestSetting getPullRequestSetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getPullRequestSetting();+ }++ @Path("/security")+ @GET+ public SecuritySetting getSecuritySetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getSecuritySetting();+ }++ @Path("/ssh")+ @GET+ public SshSetting getSshSetting() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getSshSetting();+ }++ @Path("/sso-connectors")+ @GET+ public List<SsoConnector> getSsoConnectors() {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return settingManager.getSsoConnectors();+ }++ @Path("/system")+ @POST+ public Response setSystemSetting(@NotNull SystemSetting systemSetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveSystemSetting(systemSetting);+ return Response.ok().build();+ }++ @Path("/authenticator")+ @POST+ public Response setAuthenticator(Authenticator authenticator) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveAuthenticator(authenticator);+ return Response.ok().build();+ }++ @Path("/backup")+ @POST+ public Response setBackupSetting(BackupSetting backupSetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveBackupSetting(backupSetting);+ return Response.ok().build();+ }++ @Path("/build")+ @POST+ public Response setBuildSetting(@NotNull GlobalBuildSetting buildSetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveBuildSetting(buildSetting);+ return Response.ok().build();+ }++ @Path("/groovy-scripts")+ @POST+ public Response setGroovyScripts(@NotNull List<GroovyScript> groovyScripts) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveGroovyScripts(groovyScripts);+ return Response.ok().build();+ }++ @Path("/issue")+ @POST+ public Response setIssueSetting(@NotNull GlobalIssueSetting issueSetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveIssueSetting(issueSetting);+ return Response.ok().build();+ }++ @Path("/job-executors")+ @POST+ public Response setJobExecutors(@NotNull List<JobExecutor> jobExecutors) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveJobExecutors(jobExecutors);+ return Response.ok().build();+ }++ @Path("/mail")+ @POST+ public Response setMailSetting(MailSetting mailSetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveMailSetting(mailSetting);+ return Response.ok().build();+ }++ @Path("/project")+ @POST+ public Response setProjectSetting(@NotNull GlobalProjectSetting projectSetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveProjectSetting(projectSetting);+ return Response.ok().build();+ }++ @Path("/pull-request")+ @POST+ public Response setPullRequestSetting(@NotNull GlobalPullRequestSetting pullRequestSetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.savePullRequestSetting(pullRequestSetting);+ return Response.ok().build();+ }++ @Path("/security")+ @POST+ public Response setSecuritySetting(@NotNull SecuritySetting securitySetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveSecuritySetting(securitySetting);+ return Response.ok().build();+ }++ @Path("/ssh")+ @POST+ public Response setSshSetting(@NotNull SshSetting sshSetting) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveSshSetting(sshSetting);+ return Response.ok().build();+ }++ @Path("/sso-connectors")+ @POST+ public Response setSsoConnectors(@NotNull List<SsoConnector> ssoConnectors) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ settingManager.saveSsoConnectors(ssoConnectors);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/SshKeyResource.java b/server-core/src/main/java/io/onedev/server/rest/SshKeyResource.javanew file mode 100644index 0000000000..4d78f72aeb--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/SshKeyResource.java@@ -0,0 +1,52 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.SshKeyManager;+import io.onedev.server.model.SshKey;+import io.onedev.server.security.SecurityUtils;++@Path("/ssh-keys")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class SshKeyResource {++ private final SshKeyManager sshKeyManager;++ @Inject+ public SshKeyResource(SshKeyManager sshKeyManager) {+ this.sshKeyManager = sshKeyManager;+ }++ @Path("/{sshKeyId}")+ @GET+ public SshKey get(@PathParam("sshKeyId") Long sshKeyId) {+ SshKey sshKey = sshKeyManager.load(sshKeyId);+ if (!SecurityUtils.isAdministrator() && !sshKey.getOwner().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return sshKey;+ }++ @Path("/{sshKeyId}")+ @DELETE+ public Response delete(@PathParam("sshKeyId") Long sshKeyId) {+ SshKey sshKey = sshKeyManager.load(sshKeyId);+ if (!SecurityUtils.isAdministrator() && !sshKey.getOwner().equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ sshKeyManager.delete(sshKey);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/UserAuthorizationResource.java b/server-core/src/main/java/io/onedev/server/rest/UserAuthorizationResource.javanew file mode 100644index 0000000000..b000d64abc--- /dev/null+++ b/server-core/src/main/java/io/onedev/server/rest/UserAuthorizationResource.java@@ -0,0 +1,62 @@+package io.onedev.server.rest;++import javax.inject.Inject;+import javax.inject.Singleton;+import javax.validation.constraints.NotNull;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.GET;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++import org.apache.shiro.authz.UnauthorizedException;++import io.onedev.server.entitymanager.UserAuthorizationManager;+import io.onedev.server.model.UserAuthorization;+import io.onedev.server.security.SecurityUtils;++@Path("/user-authorizations")+@Consumes(MediaType.APPLICATION_JSON)+@Produces(MediaType.APPLICATION_JSON)+@Singleton+public class UserAuthorizationResource {++ private final UserAuthorizationManager authorizationManager;++ @Inject+ public UserAuthorizationResource(UserAuthorizationManager authorizationManager) {+ this.authorizationManager = authorizationManager;+ }++ @Path("/{authorizationId}")+ @GET+ public UserAuthorization get(@PathParam("authorizationId") Long authorizationId) {+ UserAuthorization authorization = authorizationManager.load(authorizationId);+ if (!SecurityUtils.canManage(authorization.getProject()))+ throw new UnauthorizedException();+ return authorization;+ }++ @POST+ public Long save(@NotNull UserAuthorization authorization) {+ if (!SecurityUtils.canManage(authorization.getProject()))+ throw new UnauthorizedException();+ authorizationManager.save(authorization);+ return authorization.getId();+ }++ @Path("/{authorizationId}")+ @DELETE+ public Response delete(@PathParam("authorizationId") Long authorizationId) {+ UserAuthorization authorization = authorizationManager.load(authorizationId);+ if (!SecurityUtils.canManage(authorization.getProject()))+ throw new UnauthorizedException();+ authorizationManager.delete(authorization);+ return Response.ok().build();+ }++}diff --git a/server-core/src/main/java/io/onedev/server/rest/UserResource.java b/server-core/src/main/java/io/onedev/server/rest/UserResource.javaindex 3d7c8c574e..054254fe38 100644--- a/server-core/src/main/java/io/onedev/server/rest/UserResource.java+++ b/server-core/src/main/java/io/onedev/server/rest/UserResource.java@@ -1,7 +1,12 @@package io.onedev.server.rest;+import java.io.IOException;import java.io.Serializable;+import java.security.GeneralSecurityException;+import java.security.PublicKey;import java.util.ArrayList;+import java.util.Collection;+import java.util.Date;import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;@@ -23,13 +28,28 @@ import javax.ws.rs.core.Response;import org.apache.shiro.authc.credential.PasswordService;import org.apache.shiro.authz.UnauthenticatedException;import org.apache.shiro.authz.UnauthorizedException;+import org.apache.sshd.common.config.keys.KeyUtils;import org.hibernate.criterion.MatchMode;import org.hibernate.criterion.Restrictions;import org.hibernate.validator.constraints.NotEmpty;import io.onedev.commons.utils.ExplicitException;+import io.onedev.server.entitymanager.SshKeyManager;import io.onedev.server.entitymanager.UserManager;+import io.onedev.server.model.BuildQuerySetting;+import io.onedev.server.model.CodeCommentQuerySetting;+import io.onedev.server.model.CommitQuerySetting;+import io.onedev.server.model.IssueQuerySetting;+import io.onedev.server.model.IssueVote;+import io.onedev.server.model.IssueWatch;+import io.onedev.server.model.Membership;+import io.onedev.server.model.PullRequestAssignment;+import io.onedev.server.model.PullRequestQuerySetting;+import io.onedev.server.model.PullRequestReview;+import io.onedev.server.model.PullRequestWatch;+import io.onedev.server.model.SshKey;import io.onedev.server.model.User;+import io.onedev.server.model.UserAuthorization;import io.onedev.server.model.support.NamedProjectQuery;import io.onedev.server.model.support.SsoInfo;import io.onedev.server.model.support.build.NamedBuildQuery;@@ -37,7 +57,9 @@ import io.onedev.server.model.support.issue.NamedIssueQuery;import io.onedev.server.model.support.pullrequest.NamedPullRequestQuery;import io.onedev.server.persistence.dao.EntityCriteria;import io.onedev.server.rest.jersey.InvalidParamException;+import io.onedev.server.security.CipherUtils;import io.onedev.server.security.SecurityUtils;+import io.onedev.server.ssh.SshKeyUtils;@Path("/users")@Consumes(MediaType.APPLICATION_JSON)@@ -47,11 +69,14 @@ public class UserResource {private final UserManager userManager;+ private final SshKeyManager sshKeyManager;+private final PasswordService passwordService;@Inject- public UserResource(UserManager userManager, PasswordService passwordService) {+ public UserResource(UserManager userManager, SshKeyManager sshKeyManager, PasswordService passwordService) {this.userManager = userManager;+ this.sshKeyManager = sshKeyManager;this.passwordService = passwordService;}@@ -64,6 +89,31 @@ public class UserResource {return user;}+ @Path("/me")+ @GET+ public User getMe() {+ User user = SecurityUtils.getUser();+ if (user == null)+ throw new UnauthenticatedException();+ return user;+ }++ @Path("/{userId}/authorizations")+ @GET+ public Collection<UserAuthorization> getAuthorizations(@PathParam("userId") Long userId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return userManager.load(userId).getAuthorizations();+ }++ @Path("/{userId}/memberships")+ @GET+ public Collection<Membership> getMemberships(@PathParam("userId") Long userId) {+ if (!SecurityUtils.isAdministrator())+ throw new UnauthorizedException();+ return userManager.load(userId).getMemberships();+ }+@Path("/{userId}/sso-info")@GETpublic SsoInfo getSsoInfo(@PathParam("userId") Long userId) {@@ -73,6 +123,105 @@ public class UserResource {return user.getSsoInfo();}+ @Path("/{userId}/pull-request-reviews")+ @GET+ public Collection<PullRequestReview> getPullRequestReviews(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getPullRequestReviews();+ }++ @Path("/{userId}/issue-votes")+ @GET+ public Collection<IssueVote> getIssueVotes(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getIssueVotes();+ }++ @Path("/{userId}/issue-watches")+ @GET+ public Collection<IssueWatch> getIssueWatches(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getIssueWatches();+ }++ @Path("/{userId}/project-build-query-settings")+ @GET+ public Collection<BuildQuerySetting> getProjectBuildQuerySettings(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getProjectBuildQuerySettings();+ }++ @Path("/{userId}/project-code-comment-query-settings")+ @GET+ public Collection<CodeCommentQuerySetting> getProjectCodeCommentQuerySettings(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getProjectCodeCommentQuerySettings();+ }++ @Path("/{userId}/project-commit-query-settings")+ @GET+ public Collection<CommitQuerySetting> getProjectCommitQuerySettings(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getProjectCommitQuerySettings();+ }++ @Path("/{userId}/project-issue-query-settings")+ @GET+ public Collection<IssueQuerySetting> getProjecIssueQuerySettings(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getProjectIssueQuerySettings();+ }++ @Path("/{userId}/project-pull-request-query-settings")+ @GET+ public Collection<PullRequestQuerySetting> getProjecPullRequestQuerySettings(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getProjectPullRequestQuerySettings();+ }++ @Path("/{userId}/pull-request-assignments")+ @GET+ public Collection<PullRequestAssignment> getPullRequestAssignments(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getPullRequestAssignments();+ }++ @Path("/{userId}/pull-request-watches")+ @GET+ public Collection<PullRequestWatch> getPullRequestWatches(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getPullRequestWatches();+ }++ @Path("/{userId}/ssh-keys")+ @GET+ public Collection<SshKey> getSshKeys(@PathParam("userId") Long userId) {+ User user = userManager.load(userId);+ if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))+ throw new UnauthorizedException();+ return user.getSshKeys();+ }+@Path("/{userId}/queries-and-watches")@GETpublic QueriesAndWatches getQueriesAndWatches(@PathParam("userId") Long userId) {@@ -95,18 +244,13 @@ public class UserResource {@GETpublic List<User> query(@QueryParam("name") String name, @QueryParam("fullName") String fullName,- @QueryParam("email") String email, @QueryParam("offset") Integer offset,- @QueryParam("count") Integer count) {+ @QueryParam("email") String email, @QueryParam("offset") int offset,+ @QueryParam("count") int count) {if (!SecurityUtils.isAdministrator())throw new UnauthorizedException();- if (offset == null)- offset = 0;-- if (count == null)- count = RestConstants.PAGE_SIZE;- else if (count > RestConstants.PAGE_SIZE)+ if (count > RestConstants.PAGE_SIZE)throw new InvalidParamException("Count should be less than " + RestConstants.PAGE_SIZE);EntityCriteria<User> criteria = EntityCriteria.of(User.class);@@ -125,9 +269,9 @@ public class UserResource {public Long save(@NotNull User user) {if (user.isNew()) {if (!SecurityUtils.isAdministrator()) {- throw new UnauthenticatedException();+ throw new UnauthorizedException();} else {- user.setPassword("12345");+ user.setPassword("impossible_password");userManager.save(user);}} else {@@ -141,7 +285,7 @@ public class UserResource {@Path("/{userId}/password")@POST- public Response savePassword(@PathParam("userId") Long userId, @NotEmpty String password) {+ public Response setPassword(@PathParam("userId") Long userId, @NotEmpty String password) {User user = userManager.load(userId);if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) {throw new UnauthorizedException();@@ -162,7 +306,7 @@ public class UserResource {@Path("/{userId}/sso-info")@POST- public Response saveSsoInfo(@PathParam("userId") Long userId, @NotNull SsoInfo ssoInfo) {+ public Response setSsoInfo(@PathParam("userId") Long userId, @NotNull SsoInfo ssoInfo) {if (!SecurityUtils.isAdministrator())throw new UnauthorizedException();User user = userManager.load(userId);@@ -173,7 +317,7 @@ public class UserResource {@Path("/{userId}/queries-and-watches")@POST- public Response saveQueriesAndWatches(@PathParam("userId") Long userId, @NotNull QueriesAndWatches queriesAndWatches) {+ public Response setQueriesAndWatches(@PathParam("userId") Long userId, @NotNull QueriesAndWatches queriesAndWatches) {User user = userManager.load(userId);if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser()))throw new UnauthorizedException();@@ -191,6 +335,30 @@ public class UserResource {return Response.ok().build();}+ @Path("/{userId}/ssh-keys")+ @POST+ public Long addSshKey(@PathParam("userId") Long userId, @NotNull String content) {+ User user = SecurityUtils.getUser();+ if (user == null)+ throw new UnauthenticatedException();++ SshKey sshKey = new SshKey();+ sshKey.setContent(content);+ sshKey.setDate(new Date());+ sshKey.setOwner(user);++ try {+ PublicKey pubEntry = SshKeyUtils.decodeSshPublicKey(content);+ String fingerPrint = KeyUtils.getFingerPrint(CipherUtils.DIGEST_FORMAT, pubEntry);+ sshKey.setDigest(fingerPrint);+ } catch (IOException | GeneralSecurityException e) {+ throw new RuntimeException(e);+ }++ sshKeyManager.save(sshKey);+ return sshKey.getId();+ }+@Path("/{userId}")@DELETEpublic Response delete(@PathParam("userId") Long userId) {diff --git a/server-core/src/main/java/io/onedev/server/security/realm/AbstractAuthorizingRealm.java b/server-core/src/main/java/io/onedev/server/security/realm/AbstractAuthorizingRealm.javaindex 5212cd8d0e..5d5bce7d95 100644--- a/server-core/src/main/java/io/onedev/server/security/realm/AbstractAuthorizingRealm.java+++ b/server-core/src/main/java/io/onedev/server/security/realm/AbstractAuthorizingRealm.java@@ -49,17 +49,21 @@ public abstract class AbstractAuthorizingRealm extends AuthorizingRealm {protected final SessionManager sessionManager;+ protected final SettingManager settingManager;+@SuppressWarnings("serial")private static final MetaDataKey<Map<Long, AuthorizationInfo>> AUTHORIZATION_INFOS =new MetaDataKey<Map<Long, AuthorizationInfo>>() {};@Injectpublic AbstractAuthorizingRealm(UserManager userManager, GroupManager groupManager,- ProjectManager projectManager, SessionManager sessionManager) {+ ProjectManager projectManager, SessionManager sessionManager,+ SettingManager settingManager) {this.userManager = userManager;this.groupManager = groupManager;this.projectManager = projectManager;this.sessionManager = sessionManager;+ this.settingManager = settingManager;}private Collection<Permission> getGroupPermissions(Group group, @Nullable User user) {@@ -88,9 +92,8 @@ public abstract class AbstractAuthorizingRealm extends AuthorizingRealm {public Collection<Permission> call() throws Exception {Collection<Permission> permissions = new ArrayList<>();- User user = null;if (userId != 0L) {- user = userManager.load(userId);+ User user = userManager.load(userId);if (user.isRoot() || user.isSystem())permissions.add(new SystemAdministration());permissions.add(new UserAdministration(user));@@ -99,9 +102,11 @@ public abstract class AbstractAuthorizingRealm extends AuthorizingRealm {for (UserAuthorization authorization: user.getAuthorizations())permissions.add(new ProjectPermission(authorization.getProject(), authorization.getRole()));}- for (Project project: projectManager.query()) {- if (project.getDefaultRole() != null)- permissions.add(new ProjectPermission(project, project.getDefaultRole()));+ if (userId != 0L || settingManager.getSecuritySetting().isEnableAnonymousAccess()) {+ for (Project project: projectManager.query()) {+ if (project.getDefaultRole() != null)+ permissions.add(new ProjectPermission(project, project.getDefaultRole()));+ }}return permissions;}diff --git a/server-core/src/main/java/io/onedev/server/security/realm/BearerAuthorizingRealm.java b/server-core/src/main/java/io/onedev/server/security/realm/BearerAuthorizingRealm.javaindex 6bd1eb65ee..7b24c04e40 100644--- a/server-core/src/main/java/io/onedev/server/security/realm/BearerAuthorizingRealm.java+++ b/server-core/src/main/java/io/onedev/server/security/realm/BearerAuthorizingRealm.java@@ -10,6 +10,7 @@ import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;import io.onedev.server.entitymanager.GroupManager;import io.onedev.server.entitymanager.ProjectManager;+import io.onedev.server.entitymanager.SettingManager;import io.onedev.server.entitymanager.UserManager;import io.onedev.server.persistence.SessionManager;import io.onedev.server.security.BearerAuthenticationToken;@@ -19,8 +20,9 @@ public class BearerAuthorizingRealm extends AbstractAuthorizingRealm {@Injectpublic BearerAuthorizingRealm(UserManager userManager, GroupManager groupManager,- ProjectManager projectManager, SessionManager sessionManager) {- super(userManager, groupManager, projectManager, sessionManager);+ ProjectManager projectManager, SessionManager sessionManager,+ SettingManager settingManager) {+ super(userManager, groupManager, projectManager, sessionManager, settingManager);setCredentialsMatcher(new AllowAllCredentialsMatcher());}diff --git a/server-core/src/main/java/io/onedev/server/security/realm/PasswordAuthorizingRealm.java b/server-core/src/main/java/io/onedev/server/security/realm/PasswordAuthorizingRealm.javaindex 3e51124e62..470b028023 100644--- a/server-core/src/main/java/io/onedev/server/security/realm/PasswordAuthorizingRealm.java+++ b/server-core/src/main/java/io/onedev/server/security/realm/PasswordAuthorizingRealm.java@@ -37,8 +37,6 @@ public class PasswordAuthorizingRealm extends AbstractAuthorizingRealm {private static final Logger logger = LoggerFactory.getLogger(PasswordAuthorizingRealm.class);- private final SettingManager settingManager;-private final TransactionManager transactionManager;private final MembershipManager membershipManager;@@ -51,13 +49,12 @@ public class PasswordAuthorizingRealm extends AbstractAuthorizingRealm {ProjectManager projectManager, SessionManager sessionManager,TransactionManager transactionManager, SshKeyManager sshKeyManager,PasswordService passwordService) {- super(userManager, groupManager, projectManager, sessionManager);+ super(userManager, groupManager, projectManager, sessionManager, settingManager);PasswordMatcher passwordMatcher = new PasswordMatcher();passwordMatcher.setPasswordService(passwordService);setCredentialsMatcher(passwordMatcher);- this.settingManager = settingManager;this.transactionManager = transactionManager;this.membershipManager = membershipManager;this.sshKeyManager = sshKeyManager;diff --git a/server-core/src/main/java/io/onedev/server/security/realm/SsoAuthorizingRealm.java b/server-core/src/main/java/io/onedev/server/security/realm/SsoAuthorizingRealm.javaindex 8db14aec98..6b85ef79f7 100644--- a/server-core/src/main/java/io/onedev/server/security/realm/SsoAuthorizingRealm.java+++ b/server-core/src/main/java/io/onedev/server/security/realm/SsoAuthorizingRealm.java@@ -16,6 +16,7 @@ import com.google.common.collect.Sets;import io.onedev.server.entitymanager.GroupManager;import io.onedev.server.entitymanager.MembershipManager;import io.onedev.server.entitymanager.ProjectManager;+import io.onedev.server.entitymanager.SettingManager;import io.onedev.server.entitymanager.SshKeyManager;import io.onedev.server.entitymanager.UserManager;import io.onedev.server.model.User;@@ -36,8 +37,9 @@ public class SsoAuthorizingRealm extends AbstractAuthorizingRealm {@Injectpublic SsoAuthorizingRealm(UserManager userManager, MembershipManager membershipManager,GroupManager groupManager, ProjectManager projectManager, SessionManager sessionManager,- TransactionManager transactionManager, SshKeyManager sshKeyManager) {- super(userManager, groupManager, projectManager, sessionManager);+ TransactionManager transactionManager, SshKeyManager sshKeyManager,+ SettingManager settingManager) {+ super(userManager, groupManager, projectManager, sessionManager, settingManager);setCredentialsMatcher(new AllowAllCredentialsMatcher());this.membershipManager = membershipManager;diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/PullRequestDetailPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/PullRequestDetailPage.javaindex ca8a47ff15..d598c86e90 100644--- a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/PullRequestDetailPage.java+++ b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/PullRequestDetailPage.java@@ -59,7 +59,6 @@ import io.onedev.server.entitymanager.PullRequestChangeManager;import io.onedev.server.entitymanager.PullRequestManager;import io.onedev.server.entitymanager.PullRequestReviewManager;import io.onedev.server.entitymanager.PullRequestWatchManager;-import io.onedev.server.git.GitUtils;import io.onedev.server.infomanager.UserInfoManager;import io.onedev.server.model.AbstractEntity;import io.onedev.server.model.Build;@@ -1215,14 +1214,7 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullRprivate boolean canOperate() {PullRequest request = getPullRequest();- MergePreview preview = request.getMergePreview();- return request.isOpen()- && request.getCheckError() == null- && preview != null- && preview.getMergeCommitHash() != null- && request.isAllReviewsApproved()- && request.isRequiredBuildsSuccessful()- && SecurityUtils.canWriteCode(request.getTargetProject());+ return SecurityUtils.canWriteCode(request.getProject()) && request.checkMerge() == null;}@Override@@ -1299,15 +1291,7 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullRprivate boolean canOperate() {PullRequest request = getPullRequest();- PullRequestManager pullRequestManager = OneDev.getInstance(PullRequestManager.class);- return !request.isOpen()- && SecurityUtils.canModify(request)- && request.getTarget().getObjectName(false) != null- && request.getSourceProject() != null- && request.getSource().getObjectName(false) != null- && pullRequestManager.findEffective(request.getTarget(), request.getSource()) == null- && !GitUtils.isMergedInto(request.getTargetProject().getRepository(), null,- request.getSource().getObjectId(), request.getTarget().getObjectId());+ return SecurityUtils.canModify(request) && request.checkReopen() == null;}@Override@@ -1348,18 +1332,9 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullRprivate boolean canOperate() {PullRequest request = getPullRequest();- PullRequestManager pullRequestManager = OneDev.getInstance(PullRequestManager.class);- MergePreview preview = request.getLastMergePreview();- return request.isMerged()- && request.getSourceProject() != null- && request.getSource().getObjectName(false) != null- && !request.getSource().isDefault()- && preview != null- && (request.getSource().getObjectName().equals(preview.getHeadCommitHash())- || request.getSource().getObjectName().equals(preview.getMergeCommitHash()))+ return request.checkDeleteSourceBranch() == null&& SecurityUtils.canModify(request)- && SecurityUtils.canDeleteBranch(request.getSourceProject(), request.getSourceBranch())- && pullRequestManager.queryOpenTo(request.getSource()).isEmpty();+ && SecurityUtils.canDeleteBranch(request.getSourceProject(), request.getSourceBranch());}@Override@@ -1401,8 +1376,7 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullRprivate boolean canOperate() {PullRequest request = getPullRequest();- return request.getSourceProject() != null- && request.getSource().getObjectName(false) == null+ return request.checkRestoreSourceBranch() == null&& SecurityUtils.canModify(request)&& SecurityUtils.canWriteCode(request.getSourceProject());}