*/
package org.sonar.server.permission.ws;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Ordering;
+import com.google.common.collect.TreeMultimap;
import java.util.List;
+import java.util.stream.Collectors;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
-import org.sonar.api.server.ws.WebService.SelectionMode;
+import org.sonar.api.utils.Paging;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.permission.OldPermissionQuery;
+import org.sonar.db.permission.PermissionQuery;
import org.sonar.db.permission.template.PermissionTemplateDto;
-import org.sonar.db.permission.UserWithPermissionDto;
+import org.sonar.db.permission.template.PermissionTemplateUserDto;
+import org.sonar.db.user.UserDto;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.WsPermissions;
-import org.sonarqube.ws.WsPermissions.OldUser;
-import org.sonarqube.ws.WsPermissions.OldUsersWsResponse;
-
-import static java.lang.String.format;
+import org.sonarqube.ws.WsPermissions.UsersWsResponse;
+
+import static org.sonar.api.server.ws.WebService.Param.PAGE;
+import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
+import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
+import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE;
+import static org.sonar.db.permission.PermissionQuery.RESULTS_MAX_SIZE;
+import static org.sonar.db.permission.PermissionQuery.SEARCH_QUERY_MIN_LENGTH;
import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdminUser;
-import static org.sonar.server.permission.ws.PermissionQueryParser.fromSelectionModeToMembership;
import static org.sonar.server.permission.ws.PermissionRequestValidator.validateProjectPermission;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createProjectPermissionParameter;
import static org.sonar.server.permission.ws.PermissionsWsParametersBuilder.createTemplateParameters;
WebService.NewAction action = context
.createAction("template_users")
.setSince("5.2")
- .setDescription(
- format("Lists the users that have been granted the specified permission as individual users rather than through group affiliation on the chosen template. <br />" +
- "If the query parameter '%s' is specified, the '%s' parameter is forced to '%s'.<br />" +
- "It requires administration permissions to access.<br />",
- Param.TEXT_QUERY, Param.SELECTED, SelectionMode.ALL.value()))
- .addPagingParams(100)
- .addSearchQuery("stas", "names")
- .addSelectionModeParam()
+ .setDescription("Lists the users with their permission as individual users rather than through group affiliation on the chosen template. <br />" +
+ "This service defaults to all users, but can be limited to users with a specific permission by providing the desired permission.<br>" +
+ "It requires administration permissions to access.<br />")
+ .addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE)
.setInternal(true)
.setResponseExample(getClass().getResource("template_users-example.json"))
.setHandler(this);
- createProjectPermissionParameter(action);
+ action.createParam(Param.TEXT_QUERY)
+ .setDescription("Limit search to user names that contain the supplied string. Must have at least %d characters.<br/>" +
+ "When this parameter is not set, only users having at least one permission are returned.", SEARCH_QUERY_MIN_LENGTH)
+ .setExampleValue("eri");
+ createProjectPermissionParameter(action).setRequired(false);
createTemplateParameters(action);
}
WsTemplateRef templateRef = WsTemplateRef.fromRequest(wsRequest);
PermissionTemplateDto template = dependenciesFinder.getTemplate(dbSession, templateRef);
- OldPermissionQuery query = buildQuery(wsRequest, template);
- WsPermissions.OldUsersWsResponse templateUsersResponse = buildResponse(dbSession, query, template);
+ PermissionQuery query = buildQuery(wsRequest, template);
+ int total = dbClient.permissionTemplateDao().countUserLoginsByQueryAndTemplate(dbSession, query, template.getId());
+ Paging paging = Paging.forPageIndex(wsRequest.mandatoryParamAsInt(PAGE)).withPageSize(wsRequest.mandatoryParamAsInt(PAGE_SIZE)).andTotal(total);
+ List<UserDto> users = findUsers(dbSession, query, template);
+ List<PermissionTemplateUserDto> permissionTemplateUsers = dbClient.permissionTemplateDao().selectUserPermissionsByTemplateIdAndUserLogins(dbSession, template.getId(),
+ users.stream().map(UserDto::getLogin).collect(Collectors.toList()));
+ WsPermissions.UsersWsResponse templateUsersResponse = buildResponse(users, permissionTemplateUsers, paging);
writeProtobuf(templateUsersResponse, wsRequest, wsResponse);
} finally {
dbClient.closeSession(dbSession);
}
}
- private static OldPermissionQuery buildQuery(Request wsRequest, PermissionTemplateDto template) {
- String permission = validateProjectPermission(wsRequest.mandatoryParam(PARAM_PERMISSION));
-
- return OldPermissionQuery.builder()
- .template(template.getUuid())
- .permission(permission)
- .membership(fromSelectionModeToMembership(wsRequest.mandatoryParam(Param.SELECTED)))
- .pageIndex(wsRequest.mandatoryParamAsInt(Param.PAGE))
- .pageSize(wsRequest.mandatoryParamAsInt(Param.PAGE_SIZE))
- .search(wsRequest.param(Param.TEXT_QUERY))
- .build();
- }
-
- private OldUsersWsResponse buildResponse(DbSession dbSession, OldPermissionQuery query, PermissionTemplateDto template) {
- List<UserWithPermissionDto> usersWithPermission = dbClient.permissionTemplateDao().selectUsers(dbSession, query, template.getId(), query.pageOffset(), query.pageSize());
- int total = dbClient.permissionTemplateDao().countUsers(dbSession, query, template.getId());
-
- OldUsersWsResponse.Builder responseBuilder = OldUsersWsResponse.newBuilder();
- for (UserWithPermissionDto userWithPermission : usersWithPermission) {
- responseBuilder.addUsers(userDtoToUserResponse(userWithPermission));
+ private static PermissionQuery buildQuery(Request wsRequest, PermissionTemplateDto template) {
+ String textQuery = wsRequest.param(TEXT_QUERY);
+ String permission = wsRequest.param(PARAM_PERMISSION);
+ PermissionQuery.Builder query = PermissionQuery.builder()
+ .setTemplate(template.getUuid())
+ .setPermission(permission != null ? validateProjectPermission(permission) : null)
+ .setPageIndex(wsRequest.mandatoryParamAsInt(PAGE))
+ .setPageSize(wsRequest.mandatoryParamAsInt(PAGE_SIZE))
+ .setSearchQuery(textQuery);
+ if (textQuery == null) {
+ query.withPermissionOnly();
}
+ return query.build();
+ }
+ private WsPermissions.UsersWsResponse buildResponse(List<UserDto> users, List<PermissionTemplateUserDto> permissionTemplateUsers, Paging paging) {
+ Multimap<Long, String> permissionsByUserId = TreeMultimap.create();
+ permissionTemplateUsers.forEach(userPermission -> permissionsByUserId.put(userPermission.getUserId(), userPermission.getPermission()));
+
+ UsersWsResponse.Builder responseBuilder = UsersWsResponse.newBuilder();
+ users.forEach(user -> {
+ WsPermissions.User.Builder userResponse = responseBuilder.addUsersBuilder()
+ .setLogin(user.getLogin())
+ .addAllPermissions(permissionsByUserId.get(user.getId()));
+ if (user.getEmail() != null) {
+ userResponse.setEmail(user.getEmail());
+ }
+ if (user.getName() != null) {
+ userResponse.setName(user.getName());
+ }
+ });
responseBuilder.getPagingBuilder()
- .setPageIndex(query.pageIndex())
- .setPageSize(query.pageSize())
- .setTotal(total)
+ .setPageIndex(paging.pageIndex())
+ .setPageSize(paging.pageSize())
+ .setTotal(paging.total())
.build();
-
return responseBuilder.build();
}
- private static OldUser userDtoToUserResponse(UserWithPermissionDto userWithPermission) {
- OldUser.Builder userBuilder = OldUser.newBuilder();
- userBuilder.setLogin(userWithPermission.getLogin());
- String email = userWithPermission.getEmail();
- if (email != null) {
- userBuilder.setEmail(email);
- }
- String name = userWithPermission.getName();
- if (name != null) {
- userBuilder.setName(name);
- }
- userBuilder.setSelected(userWithPermission.getPermission() != null);
-
- return userBuilder.build();
+ public List<UserDto> findUsers(DbSession dbSession, PermissionQuery query, PermissionTemplateDto template) {
+ List<String> orderedLogins = dbClient.permissionTemplateDao().selectUserLoginsByQueryAndTemplate(dbSession, query, template.getId());
+ return Ordering.explicit(orderedLogins).onResultOf(UserDto::getLogin).immutableSortedCopy(dbClient.userDao().selectByLogins(dbSession, orderedLogins));
}
+
}
{
"paging": {
"pageIndex": 1,
- "pageSize": 100,
+ "pageSize": 20,
"total": 2
},
"users": [
"login": "admin",
"name": "Administrator",
"email": "admin@admin.com",
- "selected": true
+ "permissions": [
+ "codeviewer"
+ ]
},
{
"login": "george.orwell",
"name": "George Orwell",
"email": "george.orwell@1984.net",
- "selected": true
+ "permissions": [
+ "admin",
+ "codeviewer"
+ ]
}
]
}
-
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
public class PermissionsWsTest {
assertThat(action.isPost()).isFalse();
assertThat(action.isInternal()).isTrue();
assertThat(action.since()).isEqualTo("5.2");
- assertThat(action.param(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION).isRequired()).isTrue();
+ assertThat(action.param(PARAM_PERMISSION).isRequired()).isFalse();
}
@Test
assertThat(action.isPost()).isFalse();
assertThat(action.isInternal()).isTrue();
assertThat(action.since()).isEqualTo("5.2");
- assertThat(action.param(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION).isRequired()).isTrue();
+ assertThat(action.param(PARAM_PERMISSION).isRequired()).isTrue();
}
private WebService.Controller controller() {
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Nullable;
-import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
-import org.sonar.api.web.UserRole;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.usergroups.ws.UserGroupFinder;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
-import org.sonarqube.ws.WsPermissions.OldUsersWsResponse;
+import org.sonarqube.ws.WsPermissions;
import static org.assertj.core.api.Assertions.assertThat;
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;
+import static org.sonar.api.web.UserRole.USER;
import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto;
import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateUserDto;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonarqube.ws.MediaTypes.PROTOBUF;
-import static org.sonarqube.ws.WsPermissions.OldUsersWsResponse.parseFrom;
-
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
+import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class TemplateUsersActionTest {
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
+
ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT, Qualifiers.VIEW, "DEV");
+
DbClient dbClient = db.getDbClient();
- final DbSession dbSession = db.getSession();
- WsActionTester ws;
+ DbSession dbSession = db.getSession();
- TemplateUsersAction underTest;
+ PermissionDependenciesFinder dependenciesFinder = new PermissionDependenciesFinder(dbClient, new ComponentFinder(dbClient), new UserGroupFinder(dbClient), resourceTypes);
- PermissionTemplateDto template1;
- PermissionTemplateDto template2;
+ TemplateUsersAction underTest = new TemplateUsersAction(dbClient, userSession, dependenciesFinder);
+ WsActionTester ws = new WsActionTester(underTest);
- @Before
- public void setUp() {
- PermissionDependenciesFinder dependenciesFinder = new PermissionDependenciesFinder(dbClient, new ComponentFinder(dbClient), new UserGroupFinder(dbClient), resourceTypes);
- underTest = new TemplateUsersAction(dbClient, userSession, dependenciesFinder);
- ws = new WsActionTester(underTest);
+ @Test
+ public void search_for_users_with_response_example() {
+ setSysAdminUser();
- userSession.login("login").setGlobalPermissions(ADMIN);
+ UserDto user1 = insertUser(new UserDto().setLogin("admin").setName("Administrator").setEmail("admin@admin.com"));
+ UserDto user2 = insertUser(new UserDto().setLogin("george.orwell").setName("George Orwell").setEmail("george.orwell@1984.net"));
+
+ PermissionTemplateDto template1 = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+
+ addUserToTemplate(newPermissionTemplateUser(CODEVIEWER, template1.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(CODEVIEWER, template1.getId(), user2.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ADMIN, template1.getId(), user2.getId()));
+
+ commit();
+
+ String result = newRequest(null, template1.getUuid()).execute().getInput();
+ assertJson(result).isSimilarTo(getClass().getResource("template_users-example.json"));
+ }
- template1 = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
- template2 = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-2"));
+ @Test
+ public void search_for_users_by_template_name() throws IOException {
+ setSysAdminUser();
UserDto user1 = insertUser(new UserDto().setLogin("login-1").setName("name-1").setEmail("email-1"));
UserDto user2 = insertUser(new UserDto().setLogin("login-2").setName("name-2").setEmail("email-2"));
UserDto user3 = insertUser(new UserDto().setLogin("login-3").setName("name-3").setEmail("email-3"));
- addUserToTemplate(newPermissionTemplateUser(UserRole.USER, template1.getId(), user1.getId()));
- addUserToTemplate(newPermissionTemplateUser(UserRole.USER, template1.getId(), user2.getId()));
- addUserToTemplate(newPermissionTemplateUser(UserRole.ISSUE_ADMIN, template1.getId(), user1.getId()));
- addUserToTemplate(newPermissionTemplateUser(UserRole.ISSUE_ADMIN, template1.getId(), user3.getId()));
- addUserToTemplate(newPermissionTemplateUser(UserRole.USER, template2.getId(), user1.getId()));
- addUserToTemplate(newPermissionTemplateUser(UserRole.USER, template2.getId(), user2.getId()));
- addUserToTemplate(newPermissionTemplateUser(UserRole.USER, template2.getId(), user3.getId()));
- addUserToTemplate(newPermissionTemplateUser(UserRole.ISSUE_ADMIN, template2.getId(), user1.getId()));
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user2.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user3.getId()));
+ PermissionTemplateDto anotherTemplate = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-2"));
+ addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate.getId(), user1.getId()));
commit();
+
+ InputStream responseStream = newRequest(null, null)
+ .setParam(PARAM_TEMPLATE_NAME, template.getName())
+ .setMediaType(PROTOBUF)
+ .execute().getInputStream();
+
+ WsPermissions.UsersWsResponse response = WsPermissions.UsersWsResponse.parseFrom(responseStream);
+ assertThat(response.getUsersList()).extracting("login").containsExactly("login-1", "login-2", "login-3");
+ assertThat(response.getUsers(0).getPermissionsList()).containsOnly("issueadmin", "user");
+ assertThat(response.getUsers(1).getPermissionsList()).containsOnly("user");
+ assertThat(response.getUsers(2).getPermissionsList()).containsOnly("issueadmin");
}
@Test
- public void search_for_users_with_response_example() {
- UserDto user1 = insertUser(new UserDto().setLogin("admin").setName("Administrator").setEmail("admin@admin.com"));
- UserDto user2 = insertUser(new UserDto().setLogin("george.orwell").setName("George Orwell").setEmail("george.orwell@1984.net"));
- addUserToTemplate(newPermissionTemplateUser(UserRole.CODEVIEWER, template1.getId(), user1.getId()));
- addUserToTemplate(newPermissionTemplateUser(UserRole.CODEVIEWER, template1.getId(), user2.getId()));
+ public void search_using_text_query() throws IOException {
+ setSysAdminUser();
+
+ UserDto user1 = insertUser(new UserDto().setLogin("login-1").setName("name-1").setEmail("email-1"));
+ UserDto user2 = insertUser(new UserDto().setLogin("login-2").setName("name-2").setEmail("email-2"));
+ UserDto user3 = insertUser(new UserDto().setLogin("login-3").setName("name-3").setEmail("email-3"));
+
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user2.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user3.getId()));
+
+ PermissionTemplateDto anotherTemplate = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-2"));
+ addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate.getId(), user1.getId()));
commit();
- String result = newRequest(UserRole.CODEVIEWER, template1.getUuid()).execute().getInput();
+ InputStream responseStream = newRequest(null, null)
+ .setParam(PARAM_TEMPLATE_NAME, template.getName())
+ .setParam(WebService.Param.TEXT_QUERY, "ame-1")
+ .setMediaType(PROTOBUF)
+ .execute().getInputStream();
- assertJson(result).isSimilarTo(getClass().getResource("template_users-example.json"));
+ WsPermissions.UsersWsResponse response = WsPermissions.UsersWsResponse.parseFrom(responseStream);
+ assertThat(response.getUsersList()).extracting("login").containsOnly("login-1");
}
@Test
- public void search_for_users_by_template_name() throws IOException {
- InputStream responseStream = newRequest(UserRole.USER, null)
- .setParam(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME, template1.getName())
- .setMediaType(PROTOBUF)
- .execute().getInputStream();
+ public void search_using_permission() throws IOException {
+ setSysAdminUser();
- OldUsersWsResponse response = parseFrom(responseStream);
+ UserDto user1 = insertUser(new UserDto().setLogin("login-1").setName("name-1").setEmail("email-1"));
+ UserDto user2 = insertUser(new UserDto().setLogin("login-2").setName("name-2").setEmail("email-2"));
+ UserDto user3 = insertUser(new UserDto().setLogin("login-3").setName("name-3").setEmail("email-3"));
+
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user2.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user3.getId()));
+
+ PermissionTemplateDto anotherTemplate = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-2"));
+ addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate.getId(), user1.getId()));
+ commit();
+ InputStream responseStream = newRequest(USER, template.getUuid())
+ .setMediaType(PROTOBUF)
+ .execute().getInputStream();
+ WsPermissions.UsersWsResponse response = WsPermissions.UsersWsResponse.parseFrom(responseStream);
assertThat(response.getUsersList()).extracting("login").containsExactly("login-1", "login-2");
+ assertThat(response.getUsers(0).getPermissionsList()).containsOnly("issueadmin", "user");
+ assertThat(response.getUsers(1).getPermissionsList()).containsOnly("user");
}
@Test
- public void search_using_text_query() throws IOException {
- InputStream responseStream = newRequest(UserRole.USER, null)
- .setParam(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME, template1.getName())
- .setParam(WebService.Param.TEXT_QUERY, "ame-1")
+ public void search_with_pagination() throws IOException {
+ setSysAdminUser();
+
+ UserDto user1 = insertUser(new UserDto().setLogin("login-1").setName("name-1").setEmail("email-1"));
+ UserDto user2 = insertUser(new UserDto().setLogin("login-2").setName("name-2").setEmail("email-2"));
+ UserDto user3 = insertUser(new UserDto().setLogin("login-3").setName("name-3").setEmail("email-3"));
+
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user2.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user3.getId()));
+
+ PermissionTemplateDto anotherTemplate = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-2"));
+ addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate.getId(), user1.getId()));
+ commit();
+
+ InputStream responseStream = newRequest(USER, null)
+ .setParam(PARAM_TEMPLATE_NAME, template.getName())
+ .setParam(WebService.Param.SELECTED, "all")
+ .setParam(WebService.Param.PAGE, "2")
+ .setParam(WebService.Param.PAGE_SIZE, "1")
.setMediaType(PROTOBUF)
.execute().getInputStream();
- OldUsersWsResponse response = parseFrom(responseStream);
-
- assertThat(response.getUsersList()).extracting("login").containsOnly("login-1");
+ WsPermissions.UsersWsResponse response = WsPermissions.UsersWsResponse.parseFrom(responseStream);
+ assertThat(response.getUsersList()).extracting("login").containsOnly("login-2");
}
@Test
- public void search_using_selected() throws IOException {
- InputStream responseStream = newRequest(UserRole.USER, null)
- .setParam(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME, template1.getName())
- .setParam(WebService.Param.SELECTED, "all")
+ public void users_are_sorted_by_name() throws IOException {
+ setSysAdminUser();
+
+ UserDto user1 = insertUser(new UserDto().setLogin("login-2").setName("name-2"));
+ UserDto user2 = insertUser(new UserDto().setLogin("login-3").setName("name-3"));
+ UserDto user3 = insertUser(new UserDto().setLogin("login-1").setName("name-1"));
+
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user1.getId()));
+ addUserToTemplate(newPermissionTemplateUser(USER, template.getId(), user2.getId()));
+ addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template.getId(), user3.getId()));
+ commit();
+
+ InputStream responseStream = newRequest(null, null)
+ .setParam(PARAM_TEMPLATE_NAME, template.getName())
.setMediaType(PROTOBUF)
.execute().getInputStream();
- OldUsersWsResponse response = OldUsersWsResponse.parseFrom(responseStream);
-
+ WsPermissions.UsersWsResponse response = WsPermissions.UsersWsResponse.parseFrom(responseStream);
assertThat(response.getUsersList()).extracting("login").containsExactly("login-1", "login-2", "login-3");
- assertThat(response.getUsers(2).getSelected()).isFalse();
}
@Test
- public void search_with_pagination() throws IOException {
- InputStream responseStream = newRequest(UserRole.USER, null)
- .setParam(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME, template1.getName())
- .setParam(WebService.Param.SELECTED, "all")
- .setParam(WebService.Param.PAGE, "2")
- .setParam(WebService.Param.PAGE_SIZE, "1")
+ public void empty_result_when_no_user_on_template() throws IOException {
+ setSysAdminUser();
+
+ UserDto user = insertUser(new UserDto().setLogin("login-1").setName("name-1").setEmail("email-1"));
+
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+
+ PermissionTemplateDto anotherTemplate = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-2"));
+ addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate.getId(), user.getId()));
+ commit();
+
+ InputStream responseStream = newRequest(null, null)
+ .setParam(PARAM_TEMPLATE_NAME, template.getName())
.setMediaType(PROTOBUF)
.execute().getInputStream();
- OldUsersWsResponse response = parseFrom(responseStream);
-
- assertThat(response.getUsersList()).extracting("login").containsOnly("login-2");
+ WsPermissions.UsersWsResponse response = WsPermissions.UsersWsResponse.parseFrom(responseStream);
+ assertThat(response.getUsersList()).isEmpty();
}
@Test
public void fail_if_not_a_project_permission() throws IOException {
+ setSysAdminUser();
+
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ commit();
+
expectedException.expect(BadRequestException.class);
+ newRequest(GlobalPermissions.PROVISIONING, template.getUuid())
+ .execute();
+ }
+
+ @Test
+ public void fail_if_no_template_param() {
+ setSysAdminUser();
- newRequest(GlobalPermissions.PROVISIONING, template1.getUuid())
+ expectedException.expect(BadRequestException.class);
+ newRequest(null, null)
.execute();
}
@Test
public void fail_if_template_does_not_exist() {
- expectedException.expect(NotFoundException.class);
+ setSysAdminUser();
- newRequest(UserRole.USER, "unknown-template-uuid")
+ expectedException.expect(NotFoundException.class);
+ newRequest(null, "unknown-template-uuid")
.execute();
}
@Test
public void fail_if_template_uuid_and_name_provided() {
- expectedException.expect(BadRequestException.class);
+ setSysAdminUser();
- newRequest(UserRole.USER, template1.getUuid())
- .setParam(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME, template1.getName())
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ commit();
+
+ expectedException.expect(BadRequestException.class);
+ newRequest(null, template.getUuid())
+ .setParam(PARAM_TEMPLATE_NAME, template.getName())
.execute();
}
@Test
public void fail_if_not_logged_in() {
- expectedException.expect(UnauthorizedException.class);
userSession.anonymous();
- newRequest(UserRole.USER, template1.getUuid()).execute();
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ commit();
+
+ expectedException.expect(UnauthorizedException.class);
+ newRequest(null, template.getUuid()).execute();
}
@Test
public void fail_if_insufficient_privileges() {
- expectedException.expect(ForbiddenException.class);
userSession.login("login");
- newRequest(UserRole.USER, template1.getUuid()).execute();
+ PermissionTemplateDto template = dbClient.permissionTemplateDao().insert(dbSession, newPermissionTemplateDto().setUuid("template-uuid-1"));
+ commit();
+
+ expectedException.expect(ForbiddenException.class);
+ newRequest(null, template.getUuid()).execute();
}
private UserDto insertUser(UserDto userDto) {
- UserDto user = dbClient.userDao().insert(dbSession, userDto.setActive(true));
- return user;
+ return dbClient.userDao().insert(dbSession, userDto.setActive(true));
}
private void addUserToTemplate(PermissionTemplateUserDto userRoleDto) {
.setUserId(userId);
}
- private TestRequest newRequest(String permission, @Nullable String templateUuid) {
+ private TestRequest newRequest(@Nullable String permission, @Nullable String templateUuid) {
TestRequest request = ws.newRequest();
- request.setParam(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION, permission);
+ if (permission != null) {
+ request.setParam(PARAM_PERMISSION, permission);
+ }
if (templateUuid != null) {
- request.setParam(org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID, templateUuid);
+ request.setParam(PARAM_TEMPLATE_ID, templateUuid);
}
-
return request;
}
+
+ private void setSysAdminUser() {
+ userSession.login("login").setGlobalPermissions(ADMIN);
+ }
}
*/
package org.sonar.db.permission.template;
+import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.sonar.db.permission.CountByProjectAndPermissionDto;
import org.sonar.db.permission.GroupWithPermissionDto;
import org.sonar.db.permission.OldPermissionQuery;
+import org.sonar.db.permission.PermissionQuery;
import org.sonar.db.permission.UserWithPermissionDto;
import static java.lang.String.format;
import static org.sonar.api.security.DefaultGroups.ANYONE;
import static org.sonar.api.web.UserRole.ADMIN;
+import static org.sonar.db.DatabaseUtils.executeLargeInputs;
import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput;
public class PermissionTemplateDao implements Dao {
this.system = system;
}
- /**
- * @return a paginated list of users.
- */
+ @Deprecated
public List<UserWithPermissionDto> selectUsers(DbSession session, OldPermissionQuery query, Long templateId, int offset, int limit) {
return mapper(session).selectUsers(query, templateId, new RowBounds(offset, limit));
}
- public int countUsers(DbSession session, OldPermissionQuery query, Long templateId) {
- return mapper(session).countUsers(query, templateId);
+ /**
+ * @return a paginated list of user logins.
+ */
+ public List<String> selectUserLoginsByQueryAndTemplate(DbSession session, PermissionQuery query, long templateId) {
+ return mapper(session).selectUserLoginsByQueryAndTemplate(query, templateId, new RowBounds(query.getPageOffset(), query.getPageSize()));
+ }
+
+ public int countUserLoginsByQueryAndTemplate(DbSession session, PermissionQuery query, long templateId) {
+ return mapper(session).countUserLoginsByQueryAndTemplate(query, templateId);
+ }
+
+ public List<PermissionTemplateUserDto> selectUserPermissionsByTemplateIdAndUserLogins(DbSession dbSession, long templateId, List<String> logins) {
+ return executeLargeInputs(logins, l -> mapper(dbSession).selectUserPermissionsByTemplateIdAndUserLogins(templateId, l));
+ }
+
+ public List<PermissionTemplateUserDto> selectUserPermissionsByTemplateId(DbSession dbSession, long templateId) {
+ return mapper(dbSession).selectUserPermissionsByTemplateIdAndUserLogins(templateId, Collections.emptyList());
}
/**
return null;
}
- List<PermissionTemplateUserDto> userPermissions = mapper.selectUserPermissionsByTemplateId(template.getId());
+ List<PermissionTemplateUserDto> userPermissions = selectUserPermissionsByTemplateId(session, template.getId());
List<PermissionTemplateGroupDto> groupPermissions = mapper.selectGroupPermissionsByTemplateId(template.getId());
PermissionTemplateCharacteristicMapper characteristicMapper = session.getMapper(PermissionTemplateCharacteristicMapper.class);
List<PermissionTemplateCharacteristicDto> characteristics = characteristicMapper.selectByTemplateId(template.getId());
public void groupsCountByTemplateIdAndPermission(DbSession dbSession, List<Long> templateIds, ResultHandler resultHandler) {
Map<String, Object> parameters = new HashMap<>(2);
parameters.put(ANYONE_GROUP_PARAMETER, ANYONE);
+
executeLargeInputsWithoutOutput(
templateIds,
partitionedTemplateIds -> {
import org.apache.ibatis.session.RowBounds;
import org.sonar.db.permission.GroupWithPermissionDto;
import org.sonar.db.permission.OldPermissionQuery;
+import org.sonar.db.permission.PermissionQuery;
import org.sonar.db.permission.UserWithPermissionDto;
/**
PermissionTemplateDto selectByUuid(String templateUuid);
- List<PermissionTemplateUserDto> selectUserPermissionsByTemplateId(long templateId);
+ List<PermissionTemplateUserDto> selectUserPermissionsByTemplateIdAndUserLogins(@Param("templateId") long templateId, @Param("logins") List<String> logins);
List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateId(long templateId);
PermissionTemplateDto selectByName(String name);
- int countUsers(@Param("query") OldPermissionQuery query, @Param("templateId") long templateId);
+ List<String> selectUserLoginsByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateId") long templateId, RowBounds rowBounds);
+
+ int countUserLoginsByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateId") long templateId);
int countGroups(@Param("query") OldPermissionQuery query, @Param("templateId") long templateId, @Param("anyoneGroup") String anyoneGroup,
@Param("projectAdminPermission") String projectAdminPermission, @Nullable @Param("groupName") String groupName);
WHERE group_id = #{groupId}
</delete>
- <select id="selectUsers" parameterType="map" resultType="UserWithPermission">
- SELECT u.login as login, u.name as name, u.email, ptu.permission_reference as permission
- <include refid="usersSelection"/>
+ <select id="selectUserLoginsByQueryAndTemplate" parameterType="map" resultType="string">
+ SELECT u.login FROM
+ (SELECT DISTINCT u.login AS login, u.name AS name
+ <include refid="userLoginsByQueryAndTemplate"/>
+ ) u
ORDER BY u.name
</select>
- <select id="countUsers" parameterType="map" resultType="int">
- SELECT count(u.login)
+ <select id="countUserLoginsByQueryAndTemplate" parameterType="map" resultType="int">
+ SELECT count(1)
+ FROM (
+ SELECT DISTINCT u.login AS login, u.name AS name
+ <include refid="userLoginsByQueryAndTemplate"/>) u
+ </select>
+
+ <sql id="userLoginsByQueryAndTemplate">
+ FROM users u
+ LEFT JOIN perm_templates_users ptu ON ptu.user_id=u.id AND ptu.template_id=#{templateId}
+ <where>
+ u.active = ${_true}
+ <if test="query.getSearchQueryToSql() != null">
+ AND lower(u.name) like #{query.searchQueryToSql} ESCAPE '/'
+ </if>
+ <if test="query.withPermissionOnly()">
+ and ptu.permission_reference is not null
+ <if test="query.getPermission()!=null">
+ and ptu.permission_reference=#{query.permission}
+ </if>
+ </if>
+ </where>
+ </sql>
+
+ <select id="selectUsers" parameterType="map" resultType="UserWithPermission">
+ SELECT u.login as login, u.name as name, u.email, ptu.permission_reference as permission
<include refid="usersSelection"/>
+ ORDER BY u.name
</select>
<sql id="usersSelection">
AND ptg.template_id=#{templateId}
<if test="!query.permission().equals(projectAdminPermission)">
- UNION
- -- Add Anyone group permission
- SELECT
+ UNION
+ -- Add Anyone group permission
+ SELECT
#{anyoneGroup} as name,
NULL as description,
(select ptg.permission_reference
AND ptg.template_id=#{templateId}
AND ptg.group_id IS NULL
</where>) as permission
- FROM groups g
+ FROM groups g
</if>
) groups
WHERE UPPER(name)=#{templateName}
</select>
- <select id="selectUserPermissionsByTemplateId" parameterType="Long" resultType="PermissionTemplateUser">
- SELECT
+ <sql id="permissionTemplateUserColumns">
ptu.id,
ptu.template_id as templateId,
ptu.permission_reference AS permission,
u.login AS userLogin,
ptu.created_at AS createdAt,
ptu.updated_at AS updatedAt
+ </sql>
+
+ <select id="selectUserPermissionsByTemplateIdAndUserLogins" parameterType="Long" resultType="PermissionTemplateUser">
+ SELECT
+ <include refid="permissionTemplateUserColumns"/>
FROM perm_templates_users ptu
INNER JOIN users u ON u.id = ptu.user_id AND u.active = ${_true}
- WHERE ptu.template_id = #{templateId}
+ <where>
+ AND ptu.template_id = #{templateId}
+ <if test="!logins.isEmpty()">
+ AND u.login IN <foreach collection="logins" open="(" close=")" item="login" separator=",">
+ #{login}
+ </foreach>
+ </if>
+ </where>
</select>
<select id="selectGroupPermissionsByTemplateId" parameterType="Long" resultType="PermissionTemplateGroup">
*/
package org.sonar.db.permission.template;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
+import java.util.Collections;
import java.util.List;
-import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
+import org.sonar.api.web.UserRole;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.permission.OldPermissionQuery;
-import org.sonar.db.permission.UserWithPermissionDto;
+import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.tuple;
+import static org.sonar.db.permission.PermissionQuery.builder;
public class UserWithPermissionTemplateDaoTest {
PermissionTemplateDao dao = dbTester.getDbClient().permissionTemplateDao();
@Test
- public void select_all_users() {
+ public void select_logins() {
dbTester.prepareDbUnit(getClass(), "users_with_permissions.xml");
- OldPermissionQuery query = OldPermissionQuery.builder().permission("user").build();
- List<UserWithPermissionDto> result = dao.selectUsers(dbSession, query, TEMPLATE_ID, 0, 10);
- assertThat(result).hasSize(3);
-
- UserWithPermissionDto user1 = result.get(0);
- assertThat(user1.getLogin()).isEqualTo("user1");
- assertThat(user1.getName()).isEqualTo("User1");
- assertThat(user1.getPermission()).isNotNull();
-
- UserWithPermissionDto user2 = result.get(1);
- assertThat(user2.getLogin()).isEqualTo("user2");
- assertThat(user2.getName()).isEqualTo("User2");
- assertThat(user2.getPermission()).isNotNull();
-
- UserWithPermissionDto user3 = result.get(2);
- assertThat(user3.getLogin()).isEqualTo("user3");
- assertThat(user3.getName()).isEqualTo("User3");
- assertThat(user3.getPermission()).isNull();
+ assertThat(dao.selectUserLoginsByQueryAndTemplate(dbSession, builder().build(), TEMPLATE_ID)).containsOnly("user1", "user2", "user3");
+ assertThat(dao.selectUserLoginsByQueryAndTemplate(dbSession, builder().withPermissionOnly().setPermission("user").build(),
+ TEMPLATE_ID)).containsOnly("user1", "user2");
}
@Test
- public void return_nothing_on_unknown_template_key() {
+ public void return_no_logins_on_unknown_template_key() {
dbTester.prepareDbUnit(getClass(), "users_with_permissions.xml");
- OldPermissionQuery query = OldPermissionQuery.builder().permission("user").build();
- List<UserWithPermissionDto> result = dao.selectUsers(dbSession, query, 999L, 0, 10);
- assertThat(result).hasSize(3);
-
- UserWithPermissionDto user1 = result.get(0);
- assertThat(user1.getPermission()).isNull();
-
- UserWithPermissionDto user2 = result.get(1);
- assertThat(user2.getPermission()).isNull();
-
- UserWithPermissionDto user3 = result.get(2);
- assertThat(user3.getPermission()).isNull();
+ assertThat(dao.selectUserLoginsByQueryAndTemplate(dbSession, builder().setPermission("user").withPermissionOnly().build(), 999L)).isEmpty();
}
@Test
- public void select_only_user_with_permission() {
+ public void select_only_logins_with_permission() {
dbTester.prepareDbUnit(getClass(), "users_with_permissions.xml");
- // user1 and user2 have permission user
- assertThat(dao.selectUsers(
+ assertThat(dao.selectUserLoginsByQueryAndTemplate(
dbSession,
- OldPermissionQuery.builder().permission("user").membership(OldPermissionQuery.IN).build(),
- TEMPLATE_ID, 0, 10)).hasSize(2);
- }
-
- @Test
- public void select_only_user_without_permission() {
- dbTester.prepareDbUnit(getClass(), "users_with_permissions.xml");
-
- // Only user3 has not the user permission
- assertThat(dao.selectUsers(
- dbSession,
- OldPermissionQuery.builder().permission("user").membership(OldPermissionQuery.OUT).build(),
- TEMPLATE_ID, 0, 10)).hasSize(1);
+ builder().setPermission("user").withPermissionOnly().build(),
+ TEMPLATE_ID)).containsOnly("user1", "user2");
}
@Test
public void select_only_enable_users() {
dbTester.prepareDbUnit(getClass(), "select_only_enable_users.xml");
- OldPermissionQuery query = OldPermissionQuery.builder().permission("user").build();
- List<UserWithPermissionDto> result = dao.selectUsers(dbSession, query, 999L, 0, 10);
- assertThat(result).hasSize(3);
+ List<String> result = dao.selectUserLoginsByQueryAndTemplate(dbSession, builder().setPermission("user").build(), TEMPLATE_ID);
+ assertThat(result).hasSize(2);
// Disabled user should not be returned
- assertThat(Iterables.find(result, new Predicate<UserWithPermissionDto>() {
- @Override
- public boolean apply(@Nullable UserWithPermissionDto input) {
- return input.getLogin().equals("disabledUser");
- }
- }, null)).isNull();
+ assertThat(result.stream().filter(input -> input.equals("disabledUser")).findFirst()).isEmpty();
}
@Test
public void search_by_user_name() {
dbTester.prepareDbUnit(getClass(), "users_with_permissions.xml");
- List<UserWithPermissionDto> result = dao.selectUsers(
- dbSession,
- OldPermissionQuery.builder().permission("user").search("SEr1").build(),
- TEMPLATE_ID, 0, 10);
- assertThat(result).hasSize(1);
- assertThat(result.get(0).getName()).isEqualTo("User1");
-
- result = dao.selectUsers(
- dbSession, OldPermissionQuery.builder().permission("user").search("user").build(), TEMPLATE_ID, 0, 10);
- assertThat(result).hasSize(3);
+ List<String> result = dao.selectUserLoginsByQueryAndTemplate(
+ dbSession, builder().withPermissionOnly().setPermission("user").setSearchQuery("SEr1").build(),
+ TEMPLATE_ID);
+ assertThat(result).containsOnly("user1");
+
+ result = dao.selectUserLoginsByQueryAndTemplate(
+ dbSession, builder().withPermissionOnly().setPermission("user").setSearchQuery("user").build(),
+ TEMPLATE_ID);
+ assertThat(result).hasSize(2);
}
@Test
public void should_be_sorted_by_user_name() {
dbTester.prepareDbUnit(getClass(), "users_with_permissions_should_be_sorted_by_user_name.xml");
- List<UserWithPermissionDto> result = dao.selectUsers(dbSession, OldPermissionQuery.builder().permission("user").build(), TEMPLATE_ID, 0, 10);
- assertThat(result).hasSize(3);
- assertThat(result.get(0).getName()).isEqualTo("User1");
- assertThat(result.get(1).getName()).isEqualTo("User2");
- assertThat(result.get(2).getName()).isEqualTo("User3");
+ assertThat(dao.selectUserLoginsByQueryAndTemplate(dbSession, builder().build(), TEMPLATE_ID)).containsOnly("user1", "user2", "user3");
}
@Test
public void should_be_paginated() {
dbTester.prepareDbUnit(getClass(), "users_with_permissions.xml");
- List<UserWithPermissionDto> result = dao.selectUsers(dbSession, OldPermissionQuery.builder().permission("user").build(), TEMPLATE_ID, 0, 2);
- assertThat(result).hasSize(2);
- assertThat(result.get(0).getName()).isEqualTo("User1");
- assertThat(result.get(1).getName()).isEqualTo("User2");
+ assertThat(dao.selectUserLoginsByQueryAndTemplate(dbSession, builder().setPageIndex(1).setPageSize(2).build(), TEMPLATE_ID)).containsOnly("user1", "user2");
+ assertThat(dao.selectUserLoginsByQueryAndTemplate(dbSession, builder().setPageIndex(2).setPageSize(2).build(), TEMPLATE_ID)).containsOnly("user3");
+ assertThat(dao.selectUserLoginsByQueryAndTemplate(dbSession, builder().setPageIndex(3).setPageSize(1).build(), TEMPLATE_ID)).containsOnly("user3");
+ }
- result = dao.selectUsers(dbSession, OldPermissionQuery.builder().permission("user").build(), TEMPLATE_ID, 1, 2);
- assertThat(result).hasSize(2);
- assertThat(result.get(0).getName()).isEqualTo("User2");
- assertThat(result.get(1).getName()).isEqualTo("User3");
+ @Test
+ public void count_users() throws Exception {
+ dbTester.prepareDbUnit(getClass(), "users_with_permissions.xml");
- result = dao.selectUsers(dbSession, OldPermissionQuery.builder().permission("user").build(), TEMPLATE_ID, 2, 1);
- assertThat(result).hasSize(1);
- assertThat(result.get(0).getName()).isEqualTo("User3");
+ assertThat(dao.countUserLoginsByQueryAndTemplate(dbSession, builder().build(), TEMPLATE_ID)).isEqualTo(3);
+ assertThat(dao.countUserLoginsByQueryAndTemplate(dbSession, builder().withPermissionOnly().setPermission("user").build(), TEMPLATE_ID)).isEqualTo(2);
}
+ @Test
+ public void select_user_permission_templates_by_template_and_logins() throws Exception {
+ dbTester.prepareDbUnit(getClass(), "users_with_permissions.xml");
+
+ assertThat(dao.selectUserPermissionsByTemplateIdAndUserLogins(dbSession, 50L, singletonList("user1")))
+ .extracting(PermissionTemplateUserDto::getUserLogin, PermissionTemplateUserDto::getPermission)
+ .containsOnly(
+ tuple("user1", UserRole.USER),
+ tuple("user1", UserRole.ADMIN),
+ tuple("user1", UserRole.CODEVIEWER)
+ );
+
+ assertThat(dao.selectUserPermissionsByTemplateIdAndUserLogins(dbSession, 50L, asList("user1", "user2", "user3")))
+ .extracting(PermissionTemplateUserDto::getUserLogin, PermissionTemplateUserDto::getPermission)
+ .containsOnly(
+ tuple("user1", UserRole.USER),
+ tuple("user1", UserRole.ADMIN),
+ tuple("user1", UserRole.CODEVIEWER),
+ tuple("user2", UserRole.USER)
+ );
+
+ assertThat(dao.selectUserPermissionsByTemplateIdAndUserLogins(dbSession, 50L, singletonList("unknown"))).isEmpty();
+ assertThat(dao.selectUserPermissionsByTemplateIdAndUserLogins(dbSession, 50L, Collections.emptyList())).isEmpty();
+ assertThat(dao.selectUserPermissionsByTemplateIdAndUserLogins(dbSession, 123L, singletonList("user1"))).isEmpty();
+ }
}
<perm_templates_users id="1" user_id="200" permission_reference="user" template_id="50"/>
<perm_templates_users id="2" user_id="200" permission_reference="admin" template_id="50"/>
<perm_templates_users id="3" user_id="200" permission_reference="codeviewer" template_id="50"/>
+ <perm_templates_users id="4" user_id="200" permission_reference="user" template_id="51"/>
- <perm_templates_users id="4" user_id="201" permission_reference="user" template_id="50"/>
+ <perm_templates_users id="5" user_id="201" permission_reference="user" template_id="50"/>
</dataset>