]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-8272 SONAR-8273 organization in WS to apply permission templates
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Sun, 16 Oct 2016 21:02:45 +0000 (23:02 +0200)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Sun, 16 Oct 2016 21:16:37 +0000 (23:16 +0200)
28 files changed:
server/sonar-server/src/main/java/org/sonar/server/permission/PermissionService.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/AddGroupAction.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/PermissionWsSupport.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/RemoveGroupAction.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/template/ApplyTemplateAction.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/template/BulkApplyTemplateAction.java
server/sonar-server/src/main/java/org/sonar/server/permission/ws/template/WsTemplateRef.java
server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/SearchAction.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/AddGroupActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/AddUserActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/RemoveGroupActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java
server/sonar-server/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java
server/sonar-server/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java
sonar-db/src/main/java/org/sonar/db/permission/PermissionRepository.java
sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplate.java [deleted file]
sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDao.java
sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicMapper.java
sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateDao.java
sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplateMapper.java
sonar-db/src/main/resources/org/sonar/db/permission/template/PermissionTemplateCharacteristicMapper.xml
sonar-db/src/main/resources/org/sonar/db/permission/template/PermissionTemplateMapper.xml
sonar-db/src/test/java/org/sonar/db/permission/PermissionRepositoryTest.java
sonar-db/src/test/java/org/sonar/db/permission/template/PermissionTemplateDaoTest.java
sonar-ws/src/main/java/org/sonarqube/ws/client/permission/ApplyTemplateWsRequest.java
sonar-ws/src/main/java/org/sonarqube/ws/client/permission/BulkApplyTemplateWsRequest.java

index 1c99f7b28a3e1b85522b2e1ffcb07b11bd3d4f1b..3ad1b779073aa64ed8d4744f5f4216d30aad2eba 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.server.permission;
 
+import java.util.Collection;
 import java.util.List;
 import javax.annotation.Nullable;
 import org.sonar.api.resources.Qualifiers;
@@ -30,11 +31,11 @@ import org.sonar.db.DbSession;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ResourceDto;
 import org.sonar.db.permission.PermissionRepository;
+import org.sonar.db.permission.template.PermissionTemplateDto;
 import org.sonar.server.component.ComponentFinder;
 import org.sonar.server.issue.index.IssueAuthorizationIndexer;
 import org.sonar.server.user.UserSession;
 
-import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdminUser;
 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdminUserByComponentKey;
 
 @ServerSide
@@ -98,20 +99,15 @@ public class PermissionService {
     return permissionRepository.wouldUserHavePermissionWithDefaultTemplate(dbSession, userId, permission, effectiveKey, qualifier);
   }
 
-  public void applyPermissionTemplate(DbSession dbSession, ApplyPermissionTemplateQuery query) {
-    if (query.getComponentKeys().size() == 1) {
-      checkProjectAdminUserByComponentKey(userSession, query.getComponentKeys().get(0));
-    } else {
-      checkGlobalAdminUser(userSession);
+  public void apply(DbSession dbSession, PermissionTemplateDto template, Collection<ComponentDto> projects) {
+    if (projects.isEmpty()) {
+      return;
     }
 
-    // TODO apply permission templates in on query instead of on on each project
-    for (String componentKey : query.getComponentKeys()) {
-      ComponentDto component = componentFinder.getByKey(dbSession, componentKey);
-      permissionRepository.applyPermissionTemplate(dbSession, query.getTemplateUuid(), component);
+    for (ComponentDto project : projects) {
+      permissionRepository.apply(dbSession, template, project, null);
     }
     dbSession.commit();
-
     indexProjectPermissions();
   }
 
index 8fe71b5e4d3b04e575a87daf532a2d397007a2bb..01374676c22e1f0625ccb1a7559da1c0ee6f8e05 100644 (file)
@@ -36,6 +36,7 @@ import static java.util.Arrays.asList;
 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createGroupIdParameter;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createGroupNameParameter;
+import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createOrganizationParameter;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createPermissionParameter;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createProjectParameters;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
@@ -68,6 +69,7 @@ public class AddGroupAction implements PermissionsWsAction {
       .setHandler(this);
 
     createPermissionParameter(action);
+    createOrganizationParameter(action);
     createGroupNameParameter(action);
     createGroupIdParameter(action);
     createProjectParameters(action);
index 239864fe868f9685b93af9a81330543feee9a91c..8ecf03009fcfcf4d74f5ab109ff332e803a8c9e6 100644 (file)
@@ -103,8 +103,9 @@ public class PermissionWsSupport {
         dbClient.permissionTemplateDao().selectByUuid(dbSession, ref.uuid()),
         "Permission template with id '%s' is not found", ref.uuid());
     } else {
+      OrganizationDto org = findOrganization(dbSession, ref.getOrganization());
       return checkFound(
-        dbClient.permissionTemplateDao().selectByName(dbSession, ref.name()),
+        dbClient.permissionTemplateDao().selectByName(dbSession, org.getUuid(), ref.name()),
         "Permission template with name '%s' is not found (case insensitive)", ref.name());
     }
   }
index cee272fe693764232dd9c4168be6fc4b4ec48457..017e9e2ed6ec960a4bc10a7031d19c43876e866c 100644 (file)
@@ -36,6 +36,7 @@ import static java.util.Arrays.asList;
 import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createGroupIdParameter;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createGroupNameParameter;
+import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createOrganizationParameter;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createPermissionParameter;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createProjectParameters;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
@@ -68,6 +69,7 @@ public class RemoveGroupAction implements PermissionsWsAction {
       .setHandler(this);
 
     createPermissionParameter(action);
+    createOrganizationParameter(action);
     createGroupNameParameter(action);
     createGroupIdParameter(action);
     createProjectParameters(action);
index 3201990c0ba91dc2d015319578bf21db6929a6dd..ac2215fe45b4f91cbc0e36bbc63c79cf65ec55d0 100644 (file)
@@ -19,6 +19,8 @@
  */
 package org.sonar.server.permission.ws.template;
 
+import java.util.Collections;
+import java.util.Optional;
 import org.sonar.api.server.ws.Request;
 import org.sonar.api.server.ws.Response;
 import org.sonar.api.server.ws.WebService;
@@ -26,13 +28,14 @@ import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.permission.template.PermissionTemplateDto;
-import org.sonar.server.permission.ApplyPermissionTemplateQuery;
 import org.sonar.server.permission.PermissionService;
+import org.sonar.server.permission.ProjectId;
 import org.sonar.server.permission.ws.PermissionWsSupport;
 import org.sonar.server.permission.ws.PermissionsWsAction;
+import org.sonar.server.user.UserSession;
 import org.sonarqube.ws.client.permission.ApplyTemplateWsRequest;
 
-import static java.util.Collections.singletonList;
+import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createProjectParameters;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createTemplateParameters;
 import static org.sonar.server.permission.ws.ProjectWsRef.newWsProjectRef;
@@ -44,11 +47,14 @@ import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_T
 
 public class ApplyTemplateAction implements PermissionsWsAction {
   private final DbClient dbClient;
+  private final UserSession userSession;
   private final PermissionService permissionService;
   private final PermissionWsSupport wsSupport;
 
-  public ApplyTemplateAction(DbClient dbClient, PermissionService permissionService, PermissionWsSupport wsSupport) {
+  public ApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionService permissionService,
+    PermissionWsSupport wsSupport) {
     this.dbClient = dbClient;
+    this.userSession = userSession;
     this.permissionService = permissionService;
     this.wsSupport = wsSupport;
   }
@@ -76,13 +82,14 @@ public class ApplyTemplateAction implements PermissionsWsAction {
 
   private void doHandle(ApplyTemplateWsRequest request) {
     try (DbSession dbSession = dbClient.openSession(false)) {
-      PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(request.getTemplateId(), request.getTemplateName()));
+      PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
+        request.getTemplateId(), request.getOrganization(), request.getTemplateName()));
+
       ComponentDto project = wsSupport.getRootComponentOrModule(dbSession, newWsProjectRef(request.getProjectId(), request.getProjectKey()));
+      ProjectId projectId = new ProjectId(project);
+      checkProjectAdmin(userSession, template.getOrganizationUuid(), Optional.of(projectId));
 
-      ApplyPermissionTemplateQuery query = ApplyPermissionTemplateQuery.create(
-        template.getUuid(),
-        singletonList(project.key()));
-      permissionService.applyPermissionTemplate(dbSession, query);
+      permissionService.apply(dbSession, template, Collections.singletonList(project));
     }
   }
 
index 1831ef391c1a1e7f44998b543eb3923654158729..ac1777a8a9b62365afe91e49ef82ae3e7ac24bd2 100644 (file)
@@ -21,8 +21,8 @@
 package org.sonar.server.permission.ws.template;
 
 import com.google.common.collect.Collections2;
-import com.google.common.collect.Lists;
 import java.util.List;
+import java.util.Optional;
 import javax.annotation.Nullable;
 import org.sonar.api.i18n.I18n;
 import org.sonar.api.resources.ResourceTypes;
@@ -33,34 +33,39 @@ import org.sonar.api.server.ws.WebService.Param;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.component.ComponentDtoFunctions;
 import org.sonar.db.component.ComponentQuery;
 import org.sonar.db.permission.template.PermissionTemplateDto;
-import org.sonar.server.permission.ApplyPermissionTemplateQuery;
 import org.sonar.server.permission.PermissionService;
+import org.sonar.server.permission.ProjectId;
 import org.sonar.server.permission.ws.PermissionWsSupport;
 import org.sonar.server.permission.ws.PermissionsWsAction;
+import org.sonar.server.user.UserSession;
 import org.sonarqube.ws.client.permission.BulkApplyTemplateWsRequest;
 
 import static org.sonar.server.component.ResourceTypeFunctions.RESOURCE_TYPE_TO_QUALIFIER;
+import static org.sonar.server.permission.PermissionPrivilegeChecker.checkProjectAdmin;
 import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createTemplateParameters;
 import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
 import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
 import static org.sonar.server.ws.WsParameterBuilder.createRootQualifierParameter;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_ORGANIZATION_KEY;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
 
 public class BulkApplyTemplateAction implements PermissionsWsAction {
+
   private final DbClient dbClient;
+  private final UserSession userSession;
   private final PermissionService permissionService;
   private final PermissionWsSupport wsSupport;
   private final I18n i18n;
   private final ResourceTypes resourceTypes;
 
-  public BulkApplyTemplateAction(DbClient dbClient, PermissionService permissionService, PermissionWsSupport wsSupport, I18n i18n,
+  public BulkApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionService permissionService, PermissionWsSupport wsSupport, I18n i18n,
     ResourceTypes resourceTypes) {
     this.dbClient = dbClient;
+    this.userSession = userSession;
     this.permissionService = permissionService;
     this.wsSupport = wsSupport;
     this.i18n = i18n;
@@ -95,20 +100,19 @@ public class BulkApplyTemplateAction implements PermissionsWsAction {
 
   private void doHandle(BulkApplyTemplateWsRequest request) {
     try (DbSession dbSession = dbClient.openSession(false)) {
-      PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(request.getTemplateId(), request.getTemplateName()));
+      PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
+        request.getTemplateId(), request.getOrganization(), request.getTemplateName()));
       ComponentQuery componentQuery = ComponentQuery.builder()
         .setNameOrKeyQuery(request.getQuery())
         .setQualifiers(qualifiers(request.getQualifier()))
         .build();
-      List<ComponentDto> rootComponents = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
-      if (rootComponents.isEmpty()) {
-        return;
-      }
+      List<ComponentDto> projects = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
 
-      ApplyPermissionTemplateQuery query = ApplyPermissionTemplateQuery.create(
-        template.getUuid(),
-        Lists.transform(rootComponents, ComponentDtoFunctions.toKey()));
-      permissionService.applyPermissionTemplate(dbSession, query);
+      for (ComponentDto project : projects) {
+        ProjectId projectId = new ProjectId(project);
+        checkProjectAdmin(userSession, template.getOrganizationUuid(), Optional.of(projectId));
+      }
+      permissionService.apply(dbSession, template, projects);
     }
   }
 
@@ -121,6 +125,7 @@ public class BulkApplyTemplateAction implements PermissionsWsAction {
   private static BulkApplyTemplateWsRequest toBulkApplyTemplateWsRequest(Request request) {
     return new BulkApplyTemplateWsRequest()
       .setTemplateId(request.param(PARAM_TEMPLATE_ID))
+      .setOrganization(request.param(PARAM_ORGANIZATION_KEY))
       .setTemplateName(request.param(PARAM_TEMPLATE_NAME))
       .setQualifier(request.param(PARAM_QUALIFIER))
       .setQuery(request.param(Param.TEXT_QUERY));
index 3b30329d67dba31e09ad7401bcad63241a35cbbd..596319f093cf39057583887c5e48f4844a0e1386 100644 (file)
@@ -24,33 +24,38 @@ import javax.annotation.Nullable;
 import org.sonar.api.server.ws.Request;
 
 import static org.sonar.server.ws.WsUtils.checkRequest;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_ORGANIZATION_KEY;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
 
 /**
- * Template from a WS request. Guaranties the template id or the template name is provided, not both.
+ * Reference to a template as defined by WS request. Guaranties one of template id or
+ * template name is provided, not both.
  */
 public class WsTemplateRef {
 
   private final String uuid;
+  private final String organization;
   private final String name;
 
-  private WsTemplateRef(@Nullable String uuid, @Nullable String name) {
+  private WsTemplateRef(@Nullable String uuid, @Nullable String organization, @Nullable String name) {
     checkRequest(uuid != null ^ name != null, "Template name or template id must be provided, not both.");
 
     this.uuid = uuid;
+    this.organization = organization;
     this.name = name;
   }
 
   public static WsTemplateRef fromRequest(Request wsRequest) {
     String uuid = wsRequest.param(PARAM_TEMPLATE_ID);
+    String organization = wsRequest.param(PARAM_ORGANIZATION_KEY);
     String name = wsRequest.param(PARAM_TEMPLATE_NAME);
 
-    return new WsTemplateRef(uuid, name);
+    return new WsTemplateRef(uuid, organization, name);
   }
 
-  public static WsTemplateRef newTemplateRef(@Nullable String uuid, @Nullable String name) {
-    return new WsTemplateRef(uuid, name);
+  public static WsTemplateRef newTemplateRef(@Nullable String uuid, @Nullable String organization, @Nullable String name) {
+    return new WsTemplateRef(uuid, organization, name);
   }
 
   @CheckForNull
@@ -58,6 +63,11 @@ public class WsTemplateRef {
     return this.uuid;
   }
 
+  @CheckForNull
+  public String getOrganization() {
+    return this.organization;
+  }
+
   @CheckForNull
   public String name() {
     return this.name;
index e5deb2e92e25b2f993fd81ffe4d3c110075bbbf1..947a4431c268564b353d2d390c5256d0bc72d489 100644 (file)
@@ -64,7 +64,7 @@ public class SearchAction implements UserGroupsWsAction {
   public void define(NewController context) {
     WebService.NewAction action = context.createAction("search")
       .setDescription("Search for user groups.<br>" +
-        "Requires to be logged.")
+        "Requires to be logged in.")
       .setHandler(this)
       .setResponseExample(getClass().getResource("example-search.json"))
       .setSince("5.2")
index d5b8674f865abf44158f7516ac4f18af5cb9b1fc..cbd1c3419199c48882fe7bd23ec187b8ceda4873 100644 (file)
@@ -21,7 +21,6 @@ package org.sonar.server.permission.ws;
 
 import org.junit.Test;
 import org.sonar.api.web.UserRole;
-import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.component.ComponentTesting;
 import org.sonar.db.organization.OrganizationDto;
@@ -308,12 +307,4 @@ public class AddGroupActionTest extends BasePermissionWsTest<AddGroupAction> {
   private WsTester.TestRequest newRequest() {
     return wsTester.newPostRequest(CONTROLLER, ACTION);
   }
-
-  private void loginAsAdminOnDefaultOrganization() {
-    loginAsAdmin(db.getDefaultOrganization());
-  }
-
-  private void loginAsAdmin(OrganizationDto org) {
-    userSession.login().addOrganizationPermission(org.getUuid(), GlobalPermissions.SYSTEM_ADMIN);
-  }
 }
index 20cf09ab0986aff9855a133dfcd90d55a8e22eea..0cea454d95687206a915b66745c6aedb19b1729f 100644 (file)
@@ -23,7 +23,6 @@ import org.junit.Before;
 import org.junit.Test;
 import org.sonar.api.web.UserRole;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.user.UserDto;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
@@ -59,7 +58,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
 
   @Test
   public void add_permission_to_user() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
     wsTester.newPostRequest(CONTROLLER, ACTION)
       .setParam(PARAM_USER_LOGIN, user.getLogin())
       .setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
@@ -72,7 +71,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
   public void add_permission_to_project_referenced_by_its_id() throws Exception {
     ComponentDto project = db.components().insertProject();
 
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
     wsTester.newPostRequest(CONTROLLER, ACTION)
       .setParam(PARAM_USER_LOGIN, user.getLogin())
       .setParam(PARAM_PROJECT_ID, project.uuid())
@@ -87,7 +86,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
   public void add_permission_to_project_referenced_by_its_key() throws Exception {
     ComponentDto project = db.components().insertProject();
 
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
     wsTester.newPostRequest(CONTROLLER, ACTION)
       .setParam(PARAM_USER_LOGIN, user.getLogin())
       .setParam(PARAM_PROJECT_KEY, project.getKey())
@@ -102,7 +101,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
   public void add_permission_to_view() throws Exception {
     ComponentDto view = db.components().insertComponent(newView("view-uuid").setKey("view-key"));
 
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
     wsTester.newPostRequest(CONTROLLER, ACTION)
       .setParam(PARAM_USER_LOGIN, user.getLogin())
       .setParam(PARAM_PROJECT_ID, view.uuid())
@@ -115,7 +114,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
 
   @Test
   public void fail_when_project_uuid_is_unknown() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(NotFoundException.class);
 
@@ -128,7 +127,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
 
   @Test
   public void fail_when_project_permission_without_project() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(BadRequestException.class);
 
@@ -141,7 +140,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
   @Test
   public void fail_when_component_is_not_a_project() throws Exception {
     db.components().insertComponent(newFileDto(newProjectDto("project-uuid"), null, "file-uuid"));
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(BadRequestException.class);
 
@@ -154,7 +153,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
 
   @Test
   public void fail_when_get_request() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(ServerException.class);
 
@@ -166,7 +165,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
 
   @Test
   public void fail_when_user_login_is_missing() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(IllegalArgumentException.class);
 
@@ -177,7 +176,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
 
   @Test
   public void fail_when_permission_is_missing() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(NotFoundException.class);
 
@@ -189,7 +188,7 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
   @Test
   public void fail_when_project_uuid_and_project_key_are_provided() throws Exception {
     db.components().insertProject();
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Project id or project key can be provided, not both.");
@@ -245,12 +244,4 @@ public class AddUserActionTest extends BasePermissionWsTest<AddUserAction> {
 
     assertThat(db.users().selectUserPermissions(user, project)).containsOnly(ISSUE_ADMIN);
   }
-
-  private void loginAsAdmin() {
-    loginAsOrganizationAdmin(db.getDefaultOrganization());
-  }
-
-  private void loginAsOrganizationAdmin(OrganizationDto org) {
-    userSession.login().addOrganizationPermission(org.getUuid(), SYSTEM_ADMIN);
-  }
 }
index 88e35336c9ab3c29ea7d10d8bc322676d6dd6f3e..1d5bf92010019ab8be1a5c87fa0a4cff841ba9cc 100644 (file)
@@ -27,6 +27,7 @@ import org.sonar.api.utils.System2;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbTester;
 import org.sonar.db.component.ResourceTypesRule;
+import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.permission.template.PermissionTemplateDto;
 import org.sonar.db.permission.template.PermissionTemplateTesting;
 import org.sonar.server.component.ComponentFinder;
@@ -40,6 +41,8 @@ import org.sonar.server.usergroups.ws.GroupWsSupport;
 import org.sonar.server.ws.WsTester;
 
 import static org.mockito.Mockito.mock;
+import static org.sonar.core.permission.GlobalPermissions.SYSTEM_ADMIN;
+import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
 
 public abstract class BasePermissionWsTest<A extends PermissionsWsAction> {
 
@@ -81,7 +84,29 @@ public abstract class BasePermissionWsTest<A extends PermissionsWsAction> {
   }
 
   protected PermissionTemplateDto insertTemplate() {
-    PermissionTemplateDto dto = db.getDbClient().permissionTemplateDao().insert(db.getSession(), PermissionTemplateTesting.newPermissionTemplateDto());
+    PermissionTemplateDto dto = PermissionTemplateTesting.newPermissionTemplateDto()
+      .setOrganizationUuid(db.getDefaultOrganization().getUuid());
+    dto = db.getDbClient().permissionTemplateDao().insert(db.getSession(), dto);
+    db.commit();
+    return dto;
+  }
+
+  protected void loginAsAdminOnDefaultOrganization() {
+    loginAsAdmin(db.getDefaultOrganization());
+  }
+
+  protected void loginAsAdmin(OrganizationDto org) {
+    userSession.login().addOrganizationPermission(org.getUuid(), SYSTEM_ADMIN);
+  }
+
+  protected PermissionTemplateDto selectTemplateInDefaultOrganization(String name) {
+    return db.getDbClient().permissionTemplateDao().selectByName(db.getSession(), db.getDefaultOrganization().getUuid(), name);
+  }
+
+  protected PermissionTemplateDto addTemplateToDefaultOrganization() {
+    PermissionTemplateDto dto = newPermissionTemplateDto()
+      .setOrganizationUuid(db.getDefaultOrganization().getUuid());
+    db.getDbClient().permissionTemplateDao().insert(db.getSession(), dto);
     db.commit();
     return dto;
   }
index 46a2e2aff5cd143cbd507a55d5e97c77a3f8b574..6a8961bfcbe3c78120ae37351e00d8ead81bdfe3 100644 (file)
@@ -23,7 +23,6 @@ import org.junit.Before;
 import org.junit.Test;
 import org.sonar.api.web.UserRole;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.user.GroupDto;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
@@ -66,7 +65,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
   public void remove_permission_using_group_name() throws Exception {
     db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
     db.users().insertPermissionOnGroup(aGroup, PROVISIONING);
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     newRequest()
       .setParam(PARAM_GROUP_NAME, aGroup.getName())
@@ -80,7 +79,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
   public void remove_permission_using_group_id() throws Exception {
     db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
     db.users().insertPermissionOnGroup(aGroup, PROVISIONING);
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     newRequest()
       .setParam(PARAM_GROUP_ID, aGroup.getId().toString())
@@ -96,7 +95,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
     db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
     db.users().insertProjectPermissionOnGroup(aGroup, ADMIN, project);
     db.users().insertProjectPermissionOnGroup(aGroup, ISSUE_ADMIN, project);
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     newRequest()
       .setParam(PARAM_GROUP_NAME, aGroup.getName())
@@ -114,7 +113,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
     db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
     db.users().insertProjectPermissionOnGroup(aGroup, ADMIN, view);
     db.users().insertProjectPermissionOnGroup(aGroup, ISSUE_ADMIN, view);
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     newRequest()
       .setParam(PARAM_GROUP_NAME, aGroup.getName())
@@ -132,7 +131,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
     db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
     db.users().insertProjectPermissionOnGroup(aGroup, ADMIN, project);
     db.users().insertProjectPermissionOnGroup(aGroup, ISSUE_ADMIN, project);
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     newRequest()
       .setParam(PARAM_GROUP_NAME, aGroup.getName())
@@ -148,7 +147,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
   public void fail_to_remove_last_admin_permission() throws Exception {
     db.users().insertPermissionOnGroup(aGroup, SYSTEM_ADMIN);
     db.users().insertPermissionOnGroup(aGroup, PROVISIONING);
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Last group with permission 'admin'. Permission cannot be removed.");
@@ -161,7 +160,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
 
   @Test
   public void fail_when_project_does_not_exist() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(NotFoundException.class);
     expectedException.expectMessage("Project id 'unknown-project-uuid' not found");
@@ -175,7 +174,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
 
   @Test
   public void fail_when_project_project_permission_without_project() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Invalid global permission 'issueadmin'. Valid values are [admin, profileadmin, gateadmin, scan, provisioning]");
@@ -189,7 +188,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
   @Test
   public void fail_when_component_is_not_a_project() throws Exception {
     ComponentDto file = db.components().insertComponent(newFileDto(newProjectDto(), null, "file-uuid"));
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Component 'KEY_file-uuid' (id: file-uuid) must be a project or a module.");
@@ -203,7 +202,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
 
   @Test
   public void fail_when_get_request() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(ServerException.class);
     expectedException.expectMessage("HTTP method POST is required");
@@ -216,7 +215,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
 
   @Test
   public void fail_when_group_name_is_missing() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Group name or group id must be provided");
@@ -228,7 +227,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
 
   @Test
   public void fail_when_permission_name_and_id_are_missing() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(IllegalArgumentException.class);
     expectedException.expectMessage("The 'permission' parameter is missing");
@@ -240,7 +239,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
 
   @Test
   public void fail_when_group_id_does_not_exist() throws Exception {
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(NotFoundException.class);
     expectedException.expectMessage("No group with id '42'");
@@ -254,7 +253,7 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
   @Test
   public void fail_when_project_uuid_and_project_key_are_provided() throws Exception {
     ComponentDto project = db.components().insertProject();
-    loginAsAdmin();
+    loginAsAdminOnDefaultOrganization();
 
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Project id or project key can be provided, not both.");
@@ -315,13 +314,4 @@ public class RemoveGroupActionTest extends BasePermissionWsTest<RemoveGroupActio
   private WsTester.TestRequest newRequest() {
     return wsTester.newPostRequest(CONTROLLER, ACTION);
   }
-
-  private void loginAsAdmin() {
-    loginAsOrganizationAdmin(db.getDefaultOrganization());
-  }
-
-  private void loginAsOrganizationAdmin(OrganizationDto org) {
-    userSession.login().addOrganizationPermission(org.getUuid(), SYSTEM_ADMIN);
-  }
-
 }
index 3f4458013afeebafddf9834314919ac000be5962..bc3cf9b1eb00607df68b952c26d678fc066ca5f8 100644 (file)
@@ -37,7 +37,6 @@ import org.sonar.server.component.ComponentFinder;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
 import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.exceptions.UnauthorizedException;
 import org.sonar.server.issue.index.IssueAuthorizationIndexer;
 import org.sonar.server.permission.PermissionService;
 import org.sonar.server.permission.ws.BasePermissionWsTest;
@@ -46,6 +45,7 @@ import org.sonar.server.ws.WsTester;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
+import static org.sonar.core.permission.GlobalPermissions.SYSTEM_ADMIN;
 import static org.sonar.db.component.ComponentTesting.newProjectDto;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.CONTROLLER;
 import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID;
@@ -71,13 +71,11 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
     PermissionRepository repository = new PermissionRepository(db.getDbClient(), new MapSettings());
     ComponentFinder componentFinder = new ComponentFinder(db.getDbClient());
     PermissionService permissionService = new PermissionService(db.getDbClient(), repository, issueAuthorizationIndexer, userSession, componentFinder);
-    return new ApplyTemplateAction(db.getDbClient(), permissionService, newPermissionWsSupport());
+    return new ApplyTemplateAction(db.getDbClient(), userSession, permissionService, newPermissionWsSupport());
   }
 
   @Before
   public void setUp() {
-    loginAsAdmin();
-
     user1 = db.users().insertUser("user-login-1");
     user2 = db.users().insertUser("user-login-2");
     OrganizationDto defaultOrg = defaultOrganizationProvider.getDto();
@@ -106,6 +104,8 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
 
   @Test
   public void apply_template_with_project_uuid() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     newRequest(template1.getUuid(), project.uuid(), null);
 
     assertTemplate1AppliedToProject();
@@ -114,6 +114,8 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
 
   @Test
   public void apply_template_with_project_uuid_by_template_name() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     wsTester.newPostRequest(CONTROLLER, ACTION)
       .setParam(PARAM_TEMPLATE_NAME, template1.getName().toUpperCase())
       .setParam(PARAM_PROJECT_ID, project.uuid())
@@ -124,6 +126,8 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
 
   @Test
   public void apply_template_with_project_key() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     newRequest(template1.getUuid(), null, project.key());
 
     assertTemplate1AppliedToProject();
@@ -131,6 +135,8 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
 
   @Test
   public void fail_when_unknown_template() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     expectedException.expect(NotFoundException.class);
     expectedException.expectMessage("Permission template with id 'unknown-template-uuid' is not found");
 
@@ -139,6 +145,8 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
 
   @Test
   public void fail_when_unknown_project_uuid() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     expectedException.expect(NotFoundException.class);
     expectedException.expectMessage("Project id 'unknown-project-uuid' not found");
 
@@ -147,6 +155,8 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
 
   @Test
   public void fail_when_unknown_project_key() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     expectedException.expect(NotFoundException.class);
     expectedException.expectMessage("Project key 'unknown-project-key' not found");
 
@@ -155,6 +165,8 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
 
   @Test
   public void fail_when_template_is_not_provided() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     expectedException.expect(BadRequestException.class);
 
     newRequest(null, project.uuid(), null);
@@ -162,6 +174,8 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
 
   @Test
   public void fail_when_project_uuid_and_key_not_provided() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Project id or project key can be provided, not both.");
 
@@ -169,15 +183,9 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
   }
 
   @Test
-  public void fail_when_anonymous() throws Exception {
-    expectedException.expect(UnauthorizedException.class);
-    userSession.anonymous();
-
-    newRequest(template1.getUuid(), project.uuid(), null);
-  }
+  public void fail_when_not_admin_of_organization() throws Exception {
+    userSession.login().addOrganizationPermission("otherOrg", SYSTEM_ADMIN);
 
-  @Test
-  public void fail_when_insufficient_privileges() throws Exception {
     expectedException.expect(ForbiddenException.class);
     userSession.login().setGlobalPermissions(GlobalPermissions.SCAN_EXECUTION);
 
@@ -226,8 +234,4 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest<ApplyTemplateA
     PermissionQuery query = PermissionQuery.builder().setPermission(permission).setComponentUuid(project.uuid()).build();
     return db.getDbClient().userPermissionDao().selectLogins(db.getSession(), query);
   }
-
-  private void loginAsAdmin() {
-    userSession.login("login").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
-  }
 }
index 3a94b5eee9e892bcef869c66e5affd24134dd62f..42e07716760a4f8f22a23a172e800fc62eb45b68 100644 (file)
@@ -25,7 +25,6 @@ import org.junit.Test;
 import org.sonar.api.config.MapSettings;
 import org.sonar.api.server.ws.WebService.Param;
 import org.sonar.api.web.UserRole;
-import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.db.component.ComponentDto;
 import org.sonar.db.organization.OrganizationDto;
 import org.sonar.db.permission.PermissionQuery;
@@ -69,13 +68,11 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT
     PermissionRepository repository = new PermissionRepository(db.getDbClient(), new MapSettings());
     ComponentFinder componentFinder = new ComponentFinder(db.getDbClient());
     PermissionService permissionService = new PermissionService(db.getDbClient(), repository, issueAuthorizationIndexer, userSession, componentFinder);
-    return new BulkApplyTemplateAction(db.getDbClient(), permissionService, newPermissionWsSupport(), new I18nRule(), newRootResourceTypes());
+    return new BulkApplyTemplateAction(db.getDbClient(), userSession, permissionService, newPermissionWsSupport(), new I18nRule(), newRootResourceTypes());
   }
 
   @Before
   public void setUp() {
-    loginAsAdmin();
-
     user1 = db.users().insertUser("user-login-1");
     user2 = db.users().insertUser("user-login-2");
     OrganizationDto defaultOrg = defaultOrganizationProvider.getDto();
@@ -105,6 +102,7 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT
     db.users().insertProjectPermissionOnUser(user2, UserRole.ADMIN, developer);
     db.users().insertProjectPermissionOnGroup(group1, UserRole.ADMIN, developer);
     db.users().insertProjectPermissionOnGroup(group2, UserRole.ADMIN, developer);
+    loginAsAdminOnDefaultOrganization();
 
     newRequest().setParam(PARAM_TEMPLATE_ID, template1.getUuid()).execute();
 
@@ -116,6 +114,7 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT
   @Test
   public void bulk_apply_template_by_template_name() throws Exception {
     ComponentDto project = db.components().insertComponent(newProjectDto());
+    loginAsAdminOnDefaultOrganization();
 
     newRequest().setParam(PARAM_TEMPLATE_NAME, template1.getName()).execute();
 
@@ -126,6 +125,7 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT
   public void apply_template_by_qualifier() throws Exception {
     ComponentDto project = db.components().insertComponent(newProjectDto());
     ComponentDto view = db.components().insertComponent(newView());
+    loginAsAdminOnDefaultOrganization();
 
     newRequest()
       .setParam(PARAM_TEMPLATE_ID, template1.getUuid())
@@ -145,6 +145,7 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT
     ComponentDto projectUntouched = newProjectDto().setKey("new-sonar").setName("project-name");
     db.components().insertProjectAndSnapshot(projectUntouched);
     db.components().indexAllComponents();
+    loginAsAdminOnDefaultOrganization();
 
     newRequest()
       .setParam(PARAM_TEMPLATE_ID, template1.getUuid())
@@ -158,6 +159,8 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT
 
   @Test
   public void fail_if_no_template_parameter() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     expectedException.expect(BadRequestException.class);
     expectedException.expectMessage("Template name or template id must be provided, not both.");
 
@@ -166,6 +169,8 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT
 
   @Test
   public void fail_if_template_name_is_incorrect() throws Exception {
+    loginAsAdminOnDefaultOrganization();
+
     expectedException.expect(NotFoundException.class);
     expectedException.expectMessage("Permission template with id 'unknown-template-uuid' is not found");
 
@@ -214,8 +219,4 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest<BulkApplyT
   private WsTester.TestRequest newRequest() {
     return wsTester.newPostRequest(CONTROLLER, ACTION);
   }
-
-  private void loginAsAdmin() {
-    userSession.login().setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
-  }
 }
index f177a22012dfbe96dcafb42753e694d03730c5ec..68e95989fe7817c25e85bf6413fdf5d0bf95c306 100644 (file)
@@ -179,6 +179,7 @@ public class SearchTemplatesActionTest {
 
   private PermissionTemplateDto insertProjectTemplate() {
     return insertTemplate(newPermissionTemplateDto()
+      .setOrganizationUuid(db.getDefaultOrganization().getUuid())
       .setUuid(UUID_EXAMPLE_01)
       .setName("Default template for Projects")
       .setDescription("Template for new projects")
@@ -189,6 +190,7 @@ public class SearchTemplatesActionTest {
 
   private PermissionTemplateDto insertViewsTemplate() {
     return insertTemplate(newPermissionTemplateDto()
+      .setOrganizationUuid(db.getDefaultOrganization().getUuid())
       .setUuid(UUID_EXAMPLE_02)
       .setName("Default template for Views")
       .setDescription("Template for new views")
@@ -199,6 +201,7 @@ public class SearchTemplatesActionTest {
 
   private PermissionTemplateDto insertDeveloperTemplate() {
     return insertTemplate(newPermissionTemplateDto()
+      .setOrganizationUuid(db.getDefaultOrganization().getUuid())
       .setUuid(UUID_EXAMPLE_03)
       .setName("Default template for Developers")
       .setKeyPattern(".*sonar.developer.*")
index 8371102990a7eeba4d91064d21db17c1d583deae..4b8c441ee456c7d090ecbaa943043bbcc87aaca0 100644 (file)
@@ -31,7 +31,7 @@ import org.sonar.api.utils.log.LoggerLevel;
 import org.sonar.api.web.UserRole;
 import org.sonar.db.DbTester;
 import org.sonar.db.loadedtemplate.LoadedTemplateDto;
-import org.sonar.db.permission.template.PermissionTemplate;
+import org.sonar.db.permission.template.PermissionTemplateDto;
 import org.sonar.db.permission.template.PermissionTemplateGroupDto;
 import org.sonar.server.organization.DefaultOrganizationProvider;
 import org.sonar.server.organization.DefaultOrganizationProviderRule;
@@ -66,10 +66,10 @@ public class RegisterPermissionTemplatesTest {
 
     underTest.start();
 
-    PermissionTemplate defaultTemplate = selectTemplate();
-    assertThat(defaultTemplate.getTemplate().getName()).isEqualTo("Default template");
+    PermissionTemplateDto defaultTemplate = selectTemplate();
+    assertThat(defaultTemplate.getName()).isEqualTo("Default template");
 
-    List<PermissionTemplateGroupDto> groupPermissions = defaultTemplate.getGroupPermissions();
+    List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissions(defaultTemplate);
     assertThat(groupPermissions).hasSize(4);
     expectGroupPermission(groupPermissions, UserRole.ADMIN, DefaultGroups.ADMINISTRATORS);
     expectGroupPermission(groupPermissions, UserRole.ISSUE_ADMIN, DefaultGroups.ADMINISTRATORS);
@@ -77,7 +77,7 @@ public class RegisterPermissionTemplatesTest {
     expectGroupPermission(groupPermissions, UserRole.USER, DefaultGroups.ANYONE);
 
     // template is marked as default
-    verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, defaultTemplate.getTemplate().getUuid());
+    verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, defaultTemplate.getUuid());
 
     assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
   }
@@ -86,16 +86,16 @@ public class RegisterPermissionTemplatesTest {
   public void ignore_administrators_permissions_if_group_does_not_exist() {
     underTest.start();
 
-    PermissionTemplate defaultTemplate = selectTemplate();
-    assertThat(defaultTemplate.getTemplate().getName()).isEqualTo("Default template");
+    PermissionTemplateDto defaultTemplate = selectTemplate();
+    assertThat(defaultTemplate.getName()).isEqualTo("Default template");
 
-    List<PermissionTemplateGroupDto> groupPermissions = defaultTemplate.getGroupPermissions();
+    List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissions(defaultTemplate);
     assertThat(groupPermissions).hasSize(2);
     expectGroupPermission(groupPermissions, UserRole.CODEVIEWER, DefaultGroups.ANYONE);
     expectGroupPermission(groupPermissions, UserRole.USER, DefaultGroups.ANYONE);
 
     // marked as default
-    verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, defaultTemplate.getTemplate().getUuid());
+    verify(settings).saveProperty(DEFAULT_TEMPLATE_PROPERTY, defaultTemplate.getUuid());
 
     assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Cannot setup default permission for group: sonar-administrators");
   }
@@ -125,8 +125,12 @@ public class RegisterPermissionTemplatesTest {
     db.getDbClient().loadedTemplateDao().insert(new LoadedTemplateDto(DEFAULT_TEMPLATE_KEY, LoadedTemplateDto.PERMISSION_TEMPLATE_TYPE));
   }
 
-  private PermissionTemplate selectTemplate() {
-    return db.getDbClient().permissionTemplateDao().selectByUuidWithUserAndGroupPermissions(db.getSession(), DEFAULT_TEMPLATE_KEY);
+  private PermissionTemplateDto selectTemplate() {
+    return db.getDbClient().permissionTemplateDao().selectByUuid(db.getSession(), DEFAULT_TEMPLATE_KEY);
+  }
+
+  private List<PermissionTemplateGroupDto> selectGroupPermissions(PermissionTemplateDto template) {
+    return db.getDbClient().permissionTemplateDao().selectGroupPermissionsByTemplateId(db.getSession(), template.getId());
   }
 
   private void expectGroupPermission(List<PermissionTemplateGroupDto> groupPermissions, String expectedPermission,
index 05e2a39f85cdb0f10db11e8b6059f78ee7473103..86e0d81d9216630af61a89cbcaaaa256dac0e9f7 100644 (file)
@@ -25,18 +25,19 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
 import java.util.stream.Collectors;
+import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.config.Settings;
 import org.sonar.db.DbClient;
 import org.sonar.db.DbSession;
 import org.sonar.db.component.ComponentDto;
-import org.sonar.db.permission.template.PermissionTemplate;
 import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
 import org.sonar.db.permission.template.PermissionTemplateDto;
 import org.sonar.db.permission.template.PermissionTemplateGroupDto;
 import org.sonar.db.permission.template.PermissionTemplateUserDto;
 
+import static java.util.Arrays.asList;
 import static org.sonar.api.security.DefaultGroups.isAnyone;
 
 /**
@@ -56,35 +57,30 @@ public class PermissionRepository {
     this.settings = settings;
   }
 
-  public void applyPermissionTemplate(DbSession session, String templateUuid, ComponentDto project) {
-    applyPermissionTemplate(session, templateUuid, project, null);
-  }
-
-  private void applyPermissionTemplate(DbSession session, String templateUuid, ComponentDto project, @Nullable Long currentUserId) {
-    PermissionTemplate template = dbClient.permissionTemplateDao().selectPermissionTemplateWithPermissions(session, templateUuid);
+  public void apply(DbSession session, PermissionTemplateDto template, ComponentDto project, @Nullable Long currentUserId) {
     updateProjectAuthorizationDate(session, project.getId());
     dbClient.groupPermissionDao().deleteByRootComponentId(session, project.getId());
     dbClient.userPermissionDao().deleteProjectPermissions(session, project.getId());
 
-    List<PermissionTemplateUserDto> usersPermissions = template.getUserPermissions();
-    String organizationUuid = template.getTemplate().getOrganizationUuid();
+    List<PermissionTemplateUserDto> usersPermissions = dbClient.permissionTemplateDao().selectUserPermissionsByTemplateId(session, template.getId());
+    String organizationUuid = template.getOrganizationUuid();
     usersPermissions
       .forEach(up -> {
         UserPermissionDto dto = new UserPermissionDto(organizationUuid, up.getPermission(), up.getUserId(), project.getId());
         dbClient.userPermissionDao().insert(session, dto);
       });
 
-    List<PermissionTemplateGroupDto> groupsPermissions = template.getGroupPermissions();
+    List<PermissionTemplateGroupDto> groupsPermissions = dbClient.permissionTemplateDao().selectGroupPermissionsByTemplateId(session, template.getId());
     groupsPermissions.forEach(gp -> {
       GroupPermissionDto dto = new GroupPermissionDto()
-        .setOrganizationUuid(template.getTemplate().getOrganizationUuid())
+        .setOrganizationUuid(organizationUuid)
         .setGroupId(isAnyone(gp.getGroupName()) ? null : gp.getGroupId())
         .setRole(gp.getPermission())
         .setResourceId(project.getId());
       dbClient.groupPermissionDao().insert(session, dto);
     });
 
-    List<PermissionTemplateCharacteristicDto> characteristics = template.getCharacteristics();
+    List<PermissionTemplateCharacteristicDto> characteristics = dbClient.permissionTemplateCharacteristicDao().selectByTemplateIds(session, asList(template.getId()));
     if (currentUserId != null) {
       Set<String> permissionsForCurrentUserAlreadyInDb = usersPermissions.stream()
         .filter(userPermission -> currentUserId.equals(userPermission.getUserId()))
@@ -94,19 +90,12 @@ public class PermissionRepository {
         .filter(PermissionTemplateCharacteristicDto::getWithProjectCreator)
         .filter(characteristic -> !permissionsForCurrentUserAlreadyInDb.contains(characteristic.getPermission()))
         .forEach(c -> {
-          UserPermissionDto dto = new UserPermissionDto(template.getTemplate().getOrganizationUuid(), c.getPermission(), currentUserId, project.getId());
+          UserPermissionDto dto = new UserPermissionDto(organizationUuid, c.getPermission(), currentUserId, project.getId());
           dbClient.userPermissionDao().insert(session, dto);
         });
     }
   }
 
-  /**
-   * For each modification of permission on a project, update the authorization_updated_at to help ES reindex only relevant changes
-   */
-  private void updateProjectAuthorizationDate(DbSession dbSession, long projectId) {
-    dbClient.resourceDao().updateAuthorizationDate(projectId, dbSession);
-  }
-
   /**
    * Warning, this method is also used by the Developer Cockpit plugin
    */
@@ -116,49 +105,51 @@ public class PermissionRepository {
   }
 
   public void applyDefaultPermissionTemplate(DbSession dbSession, ComponentDto componentDto, @Nullable Long userId) {
-    String applicablePermissionTemplateKey = getApplicablePermissionTemplateKey(dbSession, componentDto.getKey(), componentDto.qualifier());
-    applyPermissionTemplate(dbSession, applicablePermissionTemplateKey, componentDto, userId);
+    PermissionTemplateDto template = getApplicablePermissionTemplate(dbSession, componentDto);
+    if (template == null) {
+      throw new IllegalArgumentException("Can not retrieve default permission template");
+    }
+    apply(dbSession, template, componentDto, userId);
   }
 
   /**
    * Return the permission template for the given componentKey. If no template key pattern match then consider default
    * permission template for the resource qualifier.
    */
-  private String getApplicablePermissionTemplateKey(DbSession session, final String componentKey, String qualifier) {
+  @CheckForNull
+  private PermissionTemplateDto getApplicablePermissionTemplate(DbSession dbSession, ComponentDto component) {
     // FIXME performance issue here, we should not load all templates
-    List<PermissionTemplateDto> allPermissionTemplates = dbClient.permissionTemplateDao().selectAll(session);
+    List<PermissionTemplateDto> allPermissionTemplates = dbClient.permissionTemplateDao().selectAll(dbSession);
     List<PermissionTemplateDto> matchingTemplates = new ArrayList<>();
     for (PermissionTemplateDto permissionTemplateDto : allPermissionTemplates) {
       String keyPattern = permissionTemplateDto.getKeyPattern();
-      if (StringUtils.isNotBlank(keyPattern) && componentKey.matches(keyPattern)) {
+      if (StringUtils.isNotBlank(keyPattern) && component.getKey().matches(keyPattern)) {
         matchingTemplates.add(permissionTemplateDto);
       }
     }
-    checkAtMostOneMatchForComponentKey(componentKey, matchingTemplates);
+    checkAtMostOneMatchForComponentKey(component.getKey(), matchingTemplates);
     if (matchingTemplates.size() == 1) {
-      return matchingTemplates.get(0).getUuid();
+      return matchingTemplates.get(0);
     }
-    String qualifierTemplateKey = settings.getString("sonar.permission.template." + qualifier + ".default");
+    String qualifierTemplateKey = settings.getString("sonar.permission.template." + component.qualifier() + ".default");
     if (!StringUtils.isBlank(qualifierTemplateKey)) {
-      return qualifierTemplateKey;
+      return dbClient.permissionTemplateDao().selectByUuid(dbSession, qualifierTemplateKey);
     }
 
     String defaultTemplateKey = settings.getString("sonar.permission.template.default");
     if (StringUtils.isBlank(defaultTemplateKey)) {
       throw new IllegalStateException("At least one default permission template should be defined");
     }
-    return defaultTemplateKey;
+    return dbClient.permissionTemplateDao().selectByUuid(dbSession, defaultTemplateKey);
   }
 
   public boolean wouldUserHavePermissionWithDefaultTemplate(DbSession dbSession, @Nullable Long currentUserId, String permission, String projectKey, String qualifier) {
-    String templateUuid = getApplicablePermissionTemplateKey(dbSession, projectKey, qualifier);
-    PermissionTemplateDto template = dbClient.permissionTemplateDao().selectByUuid(dbSession, templateUuid);
+    PermissionTemplateDto template = getApplicablePermissionTemplate(dbSession, new ComponentDto().setKey(projectKey).setQualifier(qualifier));
     if (template == null) {
       return false;
     }
 
     List<String> potentialPermissions = dbClient.permissionTemplateDao().selectPotentialPermissionsByUserIdAndTemplateId(dbSession, currentUserId, template.getId());
-
     return potentialPermissions.contains(permission);
   }
 
@@ -178,4 +169,11 @@ public class PermissionRepository {
         templatesNames.toString()));
     }
   }
+
+  /**
+   * For each modification of permission on a project, update the authorization_updated_at to help ES reindex only relevant changes
+   */
+  private void updateProjectAuthorizationDate(DbSession dbSession, long projectId) {
+    dbClient.resourceDao().updateAuthorizationDate(projectId, dbSession);
+  }
 }
diff --git a/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplate.java b/sonar-db/src/main/java/org/sonar/db/permission/template/PermissionTemplate.java
deleted file mode 100644 (file)
index 9f62d8a..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * SonarQube
- * Copyright (C) 2009-2016 SonarSource SA
- * mailto:contact AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
- */
-
-package org.sonar.db.permission.template;
-
-import java.util.List;
-import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto;
-import org.sonar.db.permission.template.PermissionTemplateDto;
-import org.sonar.db.permission.template.PermissionTemplateGroupDto;
-import org.sonar.db.permission.template.PermissionTemplateUserDto;
-
-public class PermissionTemplate {
-  private final PermissionTemplateDto template;
-  private final List<PermissionTemplateUserDto> userPermissions;
-  private final List<PermissionTemplateGroupDto> groupPermissions;
-  private final List<PermissionTemplateCharacteristicDto> characteristics;
-
-  public PermissionTemplate(PermissionTemplateDto template,
-    List<PermissionTemplateUserDto> userPermissions,
-    List<PermissionTemplateGroupDto> groupPermissions,
-    List<PermissionTemplateCharacteristicDto> characteristics) {
-    this.template = template;
-    this.userPermissions = userPermissions;
-    this.groupPermissions = groupPermissions;
-    this.characteristics = characteristics;
-  }
-
-  public PermissionTemplateDto getTemplate() {
-    return template;
-  }
-
-  public List<PermissionTemplateUserDto> getUserPermissions() {
-    return userPermissions;
-  }
-
-  public List<PermissionTemplateGroupDto> getGroupPermissions() {
-    return groupPermissions;
-  }
-
-  public List<PermissionTemplateCharacteristicDto> getCharacteristics() {
-    return characteristics;
-  }
-}
index 05e9ff0360f1f7039e2ce369dd10f7e713b6803b..d7be52538d7fc7134076fd92c902bfd4d28865a3 100644 (file)
@@ -30,6 +30,7 @@ import static java.util.Collections.emptyList;
 import static java.util.Objects.requireNonNull;
 
 public class PermissionTemplateCharacteristicDao implements Dao {
+
   public List<PermissionTemplateCharacteristicDto> selectByTemplateIds(DbSession dbSession, List<Long> templateIds) {
     return templateIds.isEmpty() ? emptyList() : mapper(dbSession).selectByTemplateIds(templateIds);
   }
index c2bba6f8f0b2f7065b528752412ee236b7654f65..801456402b95280230e47b9739fb4792c6b5b3c2 100644 (file)
@@ -24,8 +24,6 @@ import java.util.List;
 import org.apache.ibatis.annotations.Param;
 
 public interface PermissionTemplateCharacteristicMapper {
-  List<PermissionTemplateCharacteristicDto> selectByTemplateId(long templateId);
-
   List<PermissionTemplateCharacteristicDto> selectByTemplateIds(@Param("templateIds") List<Long> templateId);
 
   PermissionTemplateCharacteristicDto selectByPermissionAndTemplateId(@Param("permission") String permission, @Param("templateId") long templateId);
index 9e234fd7796769cb4d5401dfde28e0295558b985..8fda58aa11b4ebf1a3518d0d23c10e3ac5ea19de 100644 (file)
@@ -65,7 +65,7 @@ public class PermissionTemplateDao implements Dao {
     return executeLargeInputs(logins, l -> mapper(dbSession).selectUserPermissionsByTemplateIdAndUserLogins(templateId, l));
   }
 
-  private static List<PermissionTemplateUserDto> selectUserPermissionsByTemplateId(DbSession dbSession, long templateId) {
+  public List<PermissionTemplateUserDto> selectUserPermissionsByTemplateId(DbSession dbSession, long templateId) {
     return mapper(dbSession).selectUserPermissionsByTemplateIdAndUserLogins(templateId, Collections.emptyList());
   }
 
@@ -81,7 +81,7 @@ public class PermissionTemplateDao implements Dao {
     return executeLargeInputs(groups, g -> mapper(dbSession).selectGroupPermissionsByTemplateIdAndGroupNames(templateId, g));
   }
 
-  List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateId(DbSession dbSession, long templateId) {
+  public List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateId(DbSession dbSession, long templateId) {
     return mapper(dbSession).selectGroupPermissionsByTemplateIdAndGroupNames(templateId, Collections.emptyList());
   }
 
@@ -97,23 +97,6 @@ public class PermissionTemplateDao implements Dao {
     return mapper(session).selectByUuid(templateUuid);
   }
 
-  @CheckForNull
-  public PermissionTemplate selectByUuidWithUserAndGroupPermissions(DbSession session, String templateUuid) {
-    PermissionTemplateMapper mapper = mapper(session);
-
-    PermissionTemplateDto template = mapper.selectByUuid(templateUuid);
-    if (template == null) {
-      return null;
-    }
-
-    List<PermissionTemplateUserDto> userPermissions = selectUserPermissionsByTemplateId(session, template.getId());
-    List<PermissionTemplateGroupDto> groupPermissions = selectGroupPermissionsByTemplateId(session, template.getId());
-    PermissionTemplateCharacteristicMapper characteristicMapper = session.getMapper(PermissionTemplateCharacteristicMapper.class);
-    List<PermissionTemplateCharacteristicDto> characteristics = characteristicMapper.selectByTemplateId(template.getId());
-
-    return new PermissionTemplate(template, userPermissions, groupPermissions, characteristics);
-  }
-
   public List<PermissionTemplateDto> selectAll(DbSession session, String nameMatch) {
     String uppercaseNameMatch = toUppercaseSqlQuery(nameMatch);
     return mapper(session).selectAll(uppercaseNameMatch);
@@ -226,23 +209,8 @@ public class PermissionTemplateDao implements Dao {
     session.commit();
   }
 
-  /**
-   * Load permission template and load associated collections of users and groups permissions, and characteristics
-   */
-  public PermissionTemplate selectPermissionTemplateWithPermissions(DbSession session, String templateUuid) {
-    PermissionTemplateDto template = selectByUuid(session, templateUuid);
-    if (template == null) {
-      throw new IllegalArgumentException("Could not retrieve permission template with uuid " + templateUuid);
-    }
-    PermissionTemplate templateWithDependencies = selectByUuidWithUserAndGroupPermissions(session, template.getUuid());
-    if (templateWithDependencies == null) {
-      throw new IllegalArgumentException("Could not retrieve permissions for template with uuid " + templateUuid);
-    }
-    return templateWithDependencies;
-  }
-
-  public PermissionTemplateDto selectByName(DbSession dbSession, String name) {
-    return mapper(dbSession).selectByName(name.toUpperCase(Locale.ENGLISH));
+  public PermissionTemplateDto selectByName(DbSession dbSession, String organizationUuid, String name) {
+    return mapper(dbSession).selectByName(organizationUuid, name.toUpperCase(Locale.ENGLISH));
   }
 
   public List<String> selectPotentialPermissionsByUserIdAndTemplateId(DbSession dbSession, @Nullable Long currentUserId, long templateId) {
index 68a3615c8be2171d497640a69ea1bd93442e6679..7cd947b94f482baa72ffbc8b580201c3e7241d19 100644 (file)
@@ -58,7 +58,7 @@ public interface PermissionTemplateMapper {
 
   void deleteByGroupId(long groupId);
 
-  PermissionTemplateDto selectByName(String name);
+  PermissionTemplateDto selectByName(@Param("organizationUuid") String organizationUuid, @Param("name") String name);
 
   List<String> selectUserLoginsByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateId") long templateId, RowBounds rowBounds);
 
index 00050a13f19568a53ac5df3de5c3df5d7725fda3..13664b4293e0e3eac90f9abea565aa3fda57cd2c 100644 (file)
     ptc.updated_at as updatedAt
   </sql>
 
-  <select id="selectByTemplateId" parameterType="long" resultType="PermissionTemplateCharacteristic">
-    select
-    <include refid="columns" />
-    from perm_tpl_characteristics ptc
-    where
-    ptc.template_id = #{templateId}
-    order by id
-  </select>
-
   <select id="selectByTemplateIds" parameterType="long" resultType="PermissionTemplateCharacteristic">
     select
     <include refid="columns" />
index 13eaa7be8a3bd2ebead004b857e677ba9731923a..8d4e454219c1f473f49b1df12d1f95b5ebbe723b 100644 (file)
     ORDER BY UPPER(name), name
   </select>
 
-  <select id="selectByName" parameterType="String" resultType="PermissionTemplate">
-    SELECT
+  <select id="selectByName" parameterType="map" resultType="PermissionTemplate">
+    select
     <include refid="templateColumns"/>
-    FROM permission_templates
-    WHERE UPPER(name)=#{templateName}
+    from permission_templates
+    where
+    organization_uuid = #{organizationUuid,jdbcType=VARCHAR} and
+    upper(name) = #{name,jdbcType=VARCHAR}
   </select>
 
   <sql id="permissionTemplateUserColumns">
index ecdf59dd0b9658e42db4f3e3e235c83030eb7f70..4b8ea83df2aa4c870ac338be12ae6ce17505e5b5 100644 (file)
@@ -42,12 +42,13 @@ import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
+import static org.sonar.db.component.ComponentTesting.newProjectDto;
 import static org.sonar.db.user.GroupTesting.newGroupDto;
 
 public class PermissionRepositoryTest {
 
   private static final String DEFAULT_TEMPLATE = "default_20130101_010203";
-  private static final ComponentDto PROJECT = new ComponentDto().setId(123L).setUuid("THE_PROJECT_UUID");
+  private static final ComponentDto PROJECT = newProjectDto().setId(123L).setUuid("THE_PROJECT_UUID");
   private static final long NOW = 123456789L;
 
   @Rule
@@ -78,7 +79,8 @@ public class PermissionRepositoryTest {
     assertThat(roleDao.selectGroupPermissions(session, "Anyone", PROJECT.getId())).isEmpty();
     assertThat(dbTester.getDbClient().userPermissionDao().selectPermissionsByLogin(session, "marius", PROJECT.uuid())).isEmpty();
 
-    underTest.applyPermissionTemplate(session, "default_20130101_010203", PROJECT);
+    PermissionTemplateDto template = dbTester.getDbClient().permissionTemplateDao().selectByUuid(session, "default_20130101_010203");
+    underTest.apply(session, template, PROJECT, null);
 
     assertThat(roleDao.selectGroupPermissions(session, "sonar-administrators", PROJECT.getId())).containsOnly("admin", "issueadmin");
     assertThat(roleDao.selectGroupPermissions(session, "sonar-users", PROJECT.getId())).containsOnly("user", "codeviewer");
index d891bfda4dc0d909472798750d4b980462884122..b0d5bba35b389f0a1998bf3e7fdf1610475872e9 100644 (file)
@@ -39,10 +39,8 @@ import org.sonar.db.user.GroupDto;
 import org.sonar.db.user.UserDto;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.tuple;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
-import static org.sonar.api.security.DefaultGroups.ANYONE;
 import static org.sonar.api.web.UserRole.ADMIN;
 import static org.sonar.api.web.UserRole.CODEVIEWER;
 import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
@@ -50,7 +48,6 @@ import static org.sonar.api.web.UserRole.USER;
 import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
 import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
 import static org.sonar.db.user.GroupTesting.newGroupDto;
-import static org.sonar.db.user.UserTesting.newUserDto;
 
 public class PermissionTemplateDaoTest {
 
@@ -82,30 +79,6 @@ public class PermissionTemplateDaoTest {
     db.assertDbUnitTable(getClass(), "createPermissionTemplate-result.xml", "permission_templates", "id", "name", "description");
   }
 
-  @Test
-  public void should_select_permission_template() {
-    db.prepareDbUnit(getClass(), "selectPermissionTemplate.xml");
-
-    PermissionTemplate result = underTest.selectByUuidWithUserAndGroupPermissions(dbSession, "my_template_20130102_030405");
-
-    assertThat(result).isNotNull();
-    PermissionTemplateDto template = result.getTemplate();
-    assertThat(template.getName()).isEqualTo("my template");
-    assertThat(template.getUuid()).isEqualTo("my_template_20130102_030405");
-    assertThat(template.getDescription()).isEqualTo("my description");
-    List<PermissionTemplateUserDto> usersPermissions = result.getUserPermissions();
-    assertThat(usersPermissions).hasSize(3);
-    assertThat(usersPermissions).extracting("userId").containsOnly(1L, 2L, 1L);
-    assertThat(usersPermissions).extracting("userLogin").containsOnly("login1", "login2", "login2");
-    assertThat(usersPermissions).extracting("userName").containsOnly("user1", "user2", "user2");
-    assertThat(usersPermissions).extracting("permission").containsOnly("user_permission1", "user_permission1", "user_permission2");
-    List<PermissionTemplateGroupDto> groupsPermissions = result.getGroupPermissions();
-    assertThat(groupsPermissions).hasSize(3);
-    assertThat(groupsPermissions).extracting("groupId").containsOnly(1L, 2L, 0L);
-    assertThat(groupsPermissions).extracting("groupName").containsOnly("group1", "group2", "Anyone");
-    assertThat(groupsPermissions).extracting("permission").containsOnly("group_permission1", "group_permission1", "group_permission2");
-  }
-
   @Test
   public void should_select_permission_template_by_key() {
     db.prepareDbUnit(getClass(), "selectPermissionTemplate.xml");
@@ -206,63 +179,6 @@ public class PermissionTemplateDaoTest {
     checkTemplateTables("addNullGroupPermissionToTemplate-result.xml");
   }
 
-  @Test
-  public void new_permission_template_with_empty_user_group_characteristics() {
-    PermissionTemplateDto template = underTest.insert(dbSession, newPermissionTemplateDto().setUuid("TEMPLATE_UUID"));
-
-    PermissionTemplate result = underTest.selectByUuidWithUserAndGroupPermissions(dbSession, "TEMPLATE_UUID");
-
-    assertThat(result.getTemplate())
-      .extracting(PermissionTemplateDto::getId, PermissionTemplateDto::getUuid, PermissionTemplateDto::getName, PermissionTemplateDto::getDescription)
-      .containsExactly(template.getId(), template.getUuid(), template.getName(), template.getDescription());
-
-    assertThat(result.getUserPermissions()).isEmpty();
-    assertThat(result.getGroupPermissions()).isEmpty();
-    assertThat(result.getCharacteristics()).isEmpty();
-  }
-
-  @Test
-  public void unknown_permission_template() {
-    PermissionTemplate result = underTest.selectByUuidWithUserAndGroupPermissions(dbSession, "UNKNOWN_TEMPLATE_UUID");
-
-    assertThat(result).isNull();
-  }
-
-  @Test
-  public void permission_template_with_user_group_and_characteristics() {
-    PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("TEMPLATE_UUID"));
-    GroupDto group = db.users().insertGroup(newGroupDto());
-    UserDto user = db.users().insertUser(newUserDto());
-    templateDb.addGroupToTemplate(template.getId(), group.getId(), UserRole.ADMIN);
-    templateDb.addGroupToTemplate(template.getId(), null, UserRole.USER);
-    templateDb.addUserToTemplate(template.getId(), user.getId(), UserRole.CODEVIEWER);
-    templateDb.addProjectCreatorToTemplate(template.getId(), UserRole.USER);
-
-    PermissionTemplate result = underTest.selectByUuidWithUserAndGroupPermissions(dbSession, "TEMPLATE_UUID");
-    assertThat(result.getTemplate())
-      .extracting(PermissionTemplateDto::getId, PermissionTemplateDto::getUuid, PermissionTemplateDto::getName, PermissionTemplateDto::getDescription)
-      .containsExactly(template.getId(), template.getUuid(), template.getName(), template.getDescription());
-    assertThat(result.getCharacteristics()).hasSize(1)
-      .extracting(PermissionTemplateCharacteristicDto::getPermission, PermissionTemplateCharacteristicDto::getWithProjectCreator)
-      .containsExactly(tuple(UserRole.USER, true));
-    assertThat(result.getGroupPermissions())
-      .extracting(PermissionTemplateGroupDto::getGroupId, PermissionTemplateGroupDto::getGroupName, PermissionTemplateGroupDto::getPermission)
-      .containsOnly(
-        tuple(group.getId(), group.getName(), UserRole.ADMIN),
-        tuple(0L, ANYONE, UserRole.USER)
-      );
-    assertThat(result.getUserPermissions()).hasSize(1)
-      .extracting(PermissionTemplateUserDto::getUserId, PermissionTemplateUserDto::getUserLogin, PermissionTemplateUserDto::getPermission)
-      .containsExactly(tuple(user.getId(), user.getLogin(), UserRole.CODEVIEWER));
-  }
-
-  @Test
-  public void should_fail_on_unmatched_template() {
-    expectedException.expect(IllegalArgumentException.class);
-
-    underTest.selectPermissionTemplateWithPermissions(db.getSession(), "unmatched");
-  }
-
   @Test
   public void group_count_by_template_and_permission() {
     PermissionTemplateDto template1 = templateDb.insertTemplate();
index be8f363b56ad11abb30a44bfc60fe5a522990b79..1c08ecba04caef658840faea0a195f122c8e52fe 100644 (file)
@@ -26,6 +26,7 @@ public class ApplyTemplateWsRequest {
   private String projectId;
   private String projectKey;
   private String templateId;
+  private String organization;
   private String templateName;
 
   @CheckForNull
@@ -58,6 +59,15 @@ public class ApplyTemplateWsRequest {
     return this;
   }
 
+  @CheckForNull
+  public String getOrganization() {
+    return organization;
+  }
+
+  public ApplyTemplateWsRequest setOrganization(@Nullable String s) {
+    this.organization = s;
+    return this;
+  }
   @CheckForNull
   public String getTemplateName() {
     return templateName;
index f5271f857875c02a252013ca3bff4f06795c6a8c..d8d7934b767903236fc8f45ab3df3d0e6c41bd15 100644 (file)
@@ -25,6 +25,7 @@ import javax.annotation.Nullable;
 
 public class BulkApplyTemplateWsRequest {
   private String templateId;
+  private String organization;
   private String templateName;
   private String query;
   private String qualifier;
@@ -39,6 +40,16 @@ public class BulkApplyTemplateWsRequest {
     return this;
   }
 
+  @CheckForNull
+  public String getOrganization() {
+    return organization;
+  }
+
+  public BulkApplyTemplateWsRequest setOrganization(@Nullable String s) {
+    this.organization = s;
+    return this;
+  }
+
   @CheckForNull
   public String getTemplateName() {
     return templateName;