feat(项目管理): 项目用户组功能

This commit is contained in:
song-cc-rock 2023-09-04 11:11:58 +08:00 committed by fit2-zhao
parent 20de1fad25
commit 3af3fd8a4f
21 changed files with 1104 additions and 69 deletions

View File

@ -90,21 +90,21 @@ public class PermissionConstants {
/**
* 项目成员权限
*/
/*------ start: PROJECT_MEMBER ------*/
public static final String PROJECT_MEMBER_READ = "PROJECT_MEMBER:READ";
public static final String PROJECT_MEMBER_ADD = "PROJECT_MEMBER:READ+ADD";
public static final String PROJECT_MEMBER_UPDATE = "PROJECT_MEMBER:READ+UPDATE";
public static final String PROJECT_MEMBER_DELETE = "PROJECT_MEMBER:READ+DELETE";
/*------ start: PROJECT_USER ------*/
public static final String PROJECT_USER_READ = "PROJECT_USER:READ";
public static final String PROJECT_USER_ADD = "PROJECT_USER:READ+ADD";
public static final String PROJECT_USER_UPDATE = "PROJECT_USER:READ+UPDATE";
public static final String PROJECT_USER_DELETE = "PROJECT_USER:READ+DELETE";
/*------ end: PROJECT_MEMBER ------*/
/**
* 项目用户组
*/
/*------ start: PROJECT_USER_ROLE ------*/
public static final String PROJECT_USER_ROLE_READ = "PROJECT_USER_ROLE:READ";
public static final String PROJECT_USER_ROLE_ADD = "PROJECT_USER_ROLE:READ+ADD";
public static final String PROJECT_USER_ROLE_UPDATE = "PROJECT_USER_ROLE:READ+UPDATE";
public static final String PROJECT_USER_ROLE_DELETE = "PROJECT_USER_ROLE:READ+DELETE";
/*------ start: PROJECT_GROUP ------*/
public static final String PROJECT_GROUP_READ = "PROJECT_GROUP:READ";
public static final String PROJECT_GROUP_ADD = "PROJECT_GROUP:READ+ADD";
public static final String PROJECT_GROUP_UPDATE = "PROJECT_GROUP:READ+UPDATE";
public static final String PROJECT_GROUP_DELETE = "PROJECT_GROUP:READ+DELETE";
/*------ end: PROJECT_USER_ROLE ------*/
public static final String SYSTEM_AUTH_READ = "SYSTEM_AUTH:READ";

View File

@ -77,6 +77,7 @@ public class OperationLogModule {
public static final String PROJECT_MANAGEMENT = "PROJECT_MANAGEMENT"; // 项目管理
public static final String PROJECT_MANAGEMENT_PERMISSION = "PROJECT_MANAGEMENT_PERMISSION"; // 项目管理-项目与权限
public static final String PROJECT_MANAGEMENT_PERMISSION_MEMBER = "PROJECT_MANAGEMENT_PERMISSION_MEMBER";// 项目管理-项目与权限-成员
public static final String PROJECT_MANAGEMENT_PERMISSION_USER_ROLE = "PROJECT_USER_GROUP";// 项目管理-项目与权限-用户组
}

View File

@ -1,5 +1,6 @@
package io.metersphere.sdk.service;
import io.metersphere.sdk.constants.UserRoleEnum;
import io.metersphere.sdk.dto.Permission;
import io.metersphere.sdk.dto.PermissionDefinitionItem;
import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
@ -9,9 +10,11 @@ import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.PermissionCache;
import io.metersphere.sdk.util.ServiceUtils;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.User;
import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRoleExample;
import io.metersphere.system.domain.UserRoleRelation;
import io.metersphere.system.mapper.UserMapper;
import io.metersphere.system.mapper.UserRoleMapper;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
@ -36,6 +39,8 @@ public class BaseUserRoleService {
@Resource
private UserRoleMapper userRoleMapper;
@Resource
private UserMapper userMapper;
@Resource
protected BaseUserRolePermissionService baseUserRolePermissionService;
@Resource
protected BaseUserRoleRelationService baseUserRoleRelationService;
@ -240,4 +245,38 @@ public class BaseUserRoleService {
baseUserRoleRelationService.batchInsert(addRelations);
}
/**
* 校验同名用户组是否存在
* @param userRole 用户组
*/
public void checkNewRoleExist(UserRole userRole) {
UserRoleExample example = new UserRoleExample();
UserRoleExample.Criteria criteria = example.createCriteria().andNameEqualTo(userRole.getName())
.andScopeIdIn(Arrays.asList(userRole.getScopeId(), UserRoleEnum.GLOBAL.toString()))
.andTypeEqualTo(userRole.getType());
if (userRole.getId() != null) {
criteria.andIdNotEqualTo(userRole.getId());
}
List<UserRole> userRoles = userRoleMapper.selectByExample(example);
if (CollectionUtils.isNotEmpty(userRoles)) {
throw new MSException(Translator.get("user_role_exist"));
}
}
/**
* 校验用户与用户组是否存在
* @param userId 用户ID
* @param roleId 用户组ID
*/
public void checkMemberParam(String userId, String roleId) {
User user = userMapper.selectByPrimaryKey(userId);
if (user == null) {
throw new MSException(Translator.get("user_not_exist"));
}
UserRole userRole = userRoleMapper.selectByPrimaryKey(roleId);
if (userRole == null) {
throw new MSException(Translator.get("user_role_not_exist"));
}
}
}

View File

@ -162,6 +162,7 @@ global_user_role_exist_error=global user role already exists
global_user_role_relation_system_permission_error=no global user role relation system permission
global_user_role_limit_error=At least one user group is required
organization_user_role_permission_error=no organization user role permission
project_user_role_permission_error=no project user role permission
user_role_exist=User role already exists
user_role_not_exist=User role not exist
user_role_not_edit=User role can not edit

View File

@ -161,6 +161,7 @@ global_user_role_exist_error=全局用户组已存在
global_user_role_relation_system_permission_error=没有权限操作非系统级别用户组
global_user_role_limit_error=至少需要有一个用户组
organization_user_role_permission_error=没有权限操作非组织用户组
project_user_role_permission_error=没有权限操作非项目用户组
user_role_exist=用户组已存在
user_role_not_exist=用户组不存在
user_role_not_edit=用户组无法编辑

View File

@ -161,6 +161,7 @@ global_user_role_exist_error=全局用戶組已存在
global_user_role_relation_system_permission_error=沒有權限操作非系統級別用戶組
global_user_role_limit_error=至少需要有一个用户组
organization_user_role_permission_error=沒有權限操作非組織用戶組
project_user_role_permission_error=沒有權限操作非項目用戶組
user_role_exist=用戶組已存在
user_role_not_exist=用戶組不存在
user_role_not_edit=用戶組無法編輯

View File

@ -39,7 +39,7 @@ public class ProjectMemberController {
@PostMapping("/list")
@Operation(summary = "项目管理-成员-列表查询")
@RequiresPermissions(PermissionConstants.PROJECT_MEMBER_READ)
@RequiresPermissions(PermissionConstants.PROJECT_USER_READ)
public Pager<List<ProjectUserDTO>> listMember(@Validated @RequestBody ProjectMemberRequest request) {
Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize(), true);
return PageUtils.setPageInfo(page, projectMemberService.listMember(request));
@ -47,7 +47,7 @@ public class ProjectMemberController {
@GetMapping("/get-member/option/{projectId}")
@Operation(summary = "项目管理-成员-获取成员下拉选项")
@RequiresPermissions(PermissionConstants.PROJECT_MEMBER_ADD)
@RequiresPermissions(PermissionConstants.PROJECT_USER_READ)
public List<UserExtend> getMemberOption(@PathVariable String projectId,
@Schema(description = "查询关键字,根据邮箱和用户名查询")
@RequestParam(value = "keyword", required = false) String keyword) {
@ -56,21 +56,21 @@ public class ProjectMemberController {
@GetMapping("/get-role/option/{projectId}")
@Operation(summary = "项目管理-成员-获取用户组下拉选项")
@RequiresPermissions(PermissionConstants.PROJECT_MEMBER_ADD)
@RequiresPermissions(PermissionConstants.PROJECT_USER_READ)
public List<OptionDTO> getRoleOption(@PathVariable String projectId) {
return projectMemberService.getRoleOption(projectId);
}
@PostMapping("/add")
@Operation(summary = "项目管理-成员-添加成员")
@RequiresPermissions(PermissionConstants.PROJECT_MEMBER_ADD)
@RequiresPermissions(PermissionConstants.PROJECT_USER_ADD)
public void addMember(@RequestBody ProjectMemberAddRequest request) {
projectMemberService.addMember(request, SessionUtils.getUserId());
}
@PostMapping("/update")
@Operation(summary = "项目管理-成员-编辑成员")
@RequiresPermissions(PermissionConstants.PROJECT_MEMBER_UPDATE)
@RequiresPermissions(PermissionConstants.PROJECT_USER_UPDATE)
public void updateMember(@RequestBody ProjectMemberEditRequest request) {
projectMemberService.updateMember(request, SessionUtils.getUserId());
}
@ -81,21 +81,21 @@ public class ProjectMemberController {
@Parameter(name = "projectId", description = "项目ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED)),
@Parameter(name = "userId", description = "成员ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED))
})
@RequiresPermissions(PermissionConstants.PROJECT_MEMBER_DELETE)
@RequiresPermissions(PermissionConstants.PROJECT_USER_DELETE)
public void removeMember(@PathVariable String projectId, @PathVariable String userId) {
projectMemberService.removeMember(projectId, userId, SessionUtils.getUserId());
}
@PostMapping("/add-role")
@Operation(summary = "项目管理-成员-批量添加至用户组")
@RequiresPermissions(PermissionConstants.PROJECT_MEMBER_UPDATE)
@RequiresPermissions(PermissionConstants.PROJECT_USER_UPDATE)
public void addMemberRole(@RequestBody ProjectMemberAddRequest request) {
projectMemberService.addRole(request, SessionUtils.getUserId());
}
@PostMapping("/batch/remove")
@Operation(summary = "项目管理-成员-批量从项目移除")
@RequiresPermissions(PermissionConstants.PROJECT_MEMBER_DELETE)
@RequiresPermissions(PermissionConstants.PROJECT_USER_DELETE)
public void batchRemove(@RequestBody ProjectMemberBatchDeleteRequest request) {
projectMemberService.batchRemove(request, SessionUtils.getUserId());
}

View File

@ -0,0 +1,130 @@
package io.metersphere.project.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.metersphere.project.request.ProjectUserRoleEditRequest;
import io.metersphere.project.request.ProjectUserRoleMemberEditRequest;
import io.metersphere.project.request.ProjectUserRoleMemberRequest;
import io.metersphere.project.service.ProjectUserRoleLogService;
import io.metersphere.project.service.ProjectUserRoleService;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.dto.PermissionDefinitionItem;
import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
import io.metersphere.sdk.log.annotation.Log;
import io.metersphere.sdk.log.constants.OperationLogType;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.PageUtils;
import io.metersphere.sdk.util.Pager;
import io.metersphere.sdk.util.SessionUtils;
import io.metersphere.system.domain.User;
import io.metersphere.system.domain.UserRole;
import io.metersphere.system.dto.UserExtend;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Tag(name = "项目管理-项目与权限-用户组")
@RestController
@RequestMapping("/user/role/project")
public class ProjectUserRoleController {
@Resource
ProjectUserRoleService projectUserRoleService;
@GetMapping("/list/{projectId}")
@Operation(summary = "项目管理-项目与权限-用户组-获取用户组列表")
@Parameter(name = "projectId", description = "当前项目ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED))
@RequiresPermissions(PermissionConstants.PROJECT_GROUP_READ)
public List<UserRole> list(@PathVariable String projectId) {
return projectUserRoleService.list(projectId);
}
@PostMapping("/add")
@Operation(summary = "项目管理-项目与权限-用户组-添加用户组")
@RequiresPermissions(PermissionConstants.PROJECT_GROUP_ADD)
@Log(type = OperationLogType.ADD, expression = "#msClass.addLog(#request)", msClass = ProjectUserRoleLogService.class)
public UserRole add(@Validated @RequestBody ProjectUserRoleEditRequest request) {
UserRole userRole = new UserRole();
userRole.setCreateUser(SessionUtils.getUserId());
BeanUtils.copyBean(userRole, request);
return projectUserRoleService.add(userRole);
}
@PostMapping("/update")
@Operation(summary = "项目管理-项目与权限-用户组-修改用户组")
@RequiresPermissions(PermissionConstants.PROJECT_GROUP_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.updateLog(#request)", msClass = ProjectUserRoleLogService.class)
public UserRole update(@Validated @RequestBody ProjectUserRoleEditRequest request) {
UserRole userRole = new UserRole();
BeanUtils.copyBean(userRole, request);
return projectUserRoleService.update(userRole);
}
@GetMapping("/delete/{id}")
@Operation(summary = "项目管理-项目与权限-用户组-删除用户组")
@RequiresPermissions(PermissionConstants.PROJECT_GROUP_DELETE)
@Parameter(name = "id", description = "用户组ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED))
@Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#id)", msClass = ProjectUserRoleLogService.class)
public void delete(@PathVariable String id) {
projectUserRoleService.delete(id, SessionUtils.getUserId());
}
@GetMapping("/permission/setting/{id}")
@Operation(summary = "项目管理-项目与权限-用户组-获取用户组对应的权限配置")
@Parameter(name = "id", description = "用户组ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED))
@RequiresPermissions(PermissionConstants.PROJECT_GROUP_READ)
public List<PermissionDefinitionItem> getPermissionSetting(@PathVariable String id) {
return projectUserRoleService.getPermissionSetting(id);
}
@PostMapping("/permission/update")
@Operation(summary = "项目管理-项目与权限-用户组-修改用户组对应的权限配置")
@RequiresPermissions(PermissionConstants.PROJECT_GROUP_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.updatePermissionSettingLog(#request)", msClass = ProjectUserRoleLogService.class)
public void updatePermissionSetting(@Validated @RequestBody PermissionSettingUpdateRequest request) {
projectUserRoleService.updatePermissionSetting(request);
}
@GetMapping("/get-member/option/{projectId}/{roleId}")
@Operation(summary = "项目管理-项目与权限-用户组-获取成员下拉选项")
@Parameters({
@Parameter(name = "projectId", description = "当前项目ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED)),
@Parameter(name = "roleId", description = "用户组ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED))
})
@RequiresPermissions(value = {PermissionConstants.PROJECT_GROUP_READ})
public List<UserExtend> getMember(@PathVariable String projectId, @PathVariable String roleId) {
return projectUserRoleService.getMember(projectId, roleId);
}
@PostMapping("/list-member")
@Operation(summary = "项目管理-项目与权限-用户组-获取成员列表")
@RequiresPermissions(value = {PermissionConstants.PROJECT_GROUP_READ})
public Pager<List<User>> listMember(@Validated @RequestBody ProjectUserRoleMemberRequest request) {
Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize());
return PageUtils.setPageInfo(page, projectUserRoleService.listMember(request));
}
@PostMapping("/add-member")
@Operation(summary = "项目管理-项目与权限-用户组-添加用户组成员")
@RequiresPermissions(PermissionConstants.PROJECT_GROUP_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.editMemberLog(#request)", msClass = ProjectUserRoleLogService.class)
public void addMember(@Validated @RequestBody ProjectUserRoleMemberEditRequest request) {
projectUserRoleService.addMember(request, SessionUtils.getUserId());
}
@PostMapping("/remove-member")
@Operation(summary = "项目管理-项目与权限-用户组-删除用户组成员")
@RequiresPermissions(PermissionConstants.PROJECT_GROUP_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.editMemberLog(#request)", msClass = ProjectUserRoleLogService.class)
public void removeMember(@Validated @RequestBody ProjectUserRoleMemberEditRequest request) {
projectUserRoleService.removeMember(request);
}
}

View File

@ -0,0 +1,20 @@
package io.metersphere.project.mapper;
import io.metersphere.project.request.ProjectUserRoleMemberRequest;
import io.metersphere.system.domain.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author song-cc-rock
*/
public interface ExtProjectUserRoleMapper {
/**
* 获取项目成员列表
* @param request 请求参数
* @return 项目成员列表
*/
List<User> listProjectRoleMember(@Param("request") ProjectUserRoleMemberRequest request);
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.metersphere.project.mapper.ExtProjectUserRoleMapper">
<select id="listProjectRoleMember" resultType="io.metersphere.system.domain.User">
select u.*
from user_role_relation urr left join user u on urr.user_id = u.id
where u.deleted = 0 and urr.source_id = #{request.projectId}
and urr.role_id = #{request.userRoleId}
<if test="request.keyword != null and request.keyword != ''">
and u.name like concat('%', #{request.keyword}, '%')
</if>
</select>
</mapper>

View File

@ -0,0 +1,33 @@
package io.metersphere.project.request;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = false)
public class ProjectUserRoleEditRequest implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "组ID")
@NotBlank(message = "{user_role.id.not_blank}", groups = {Updated.class})
@Size(min = 1, max = 50, message = "{user_role.id.length_range}", groups = {Updated.class})
private String id;
@Schema(description = "组名称", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{user_role.name.not_blank}", groups = {Created.class, Updated.class})
@Size(min = 1, max = 255, message = "{user_role.name.length_range}", groups = {Created.class, Updated.class})
private String name;
@Schema(description = "应用范围", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{user_role.scope_id.not_blank}", groups = {Created.class, Updated.class})
@Size(min = 1, max = 50, message = "{user_role.scope_id.length_range}", groups = {Created.class, Updated.class})
private String scopeId;
}

View File

@ -0,0 +1,30 @@
package io.metersphere.project.request;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.util.List;
@Data
@EqualsAndHashCode(callSuper = false)
public class ProjectUserRoleMemberEditRequest implements Serializable {
@Schema(description = "组ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{user_role.id.not_blank}")
@Size(min = 1, max = 50, message = "{user_role.id.length_range}")
private String userRoleId;
@Schema(description = "项目ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{project.id.not_blank}")
@Size(min = 1, max = 50, message = "{project.id.length_range}")
private String projectId;
@Schema(description = "成员ID集合", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "{user.id.not_blank}")
private List<String> userIds;
}

View File

@ -0,0 +1,23 @@
package io.metersphere.project.request;
import io.metersphere.sdk.dto.BasePageRequest;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
public class ProjectUserRoleMemberRequest extends BasePageRequest {
@Schema(description = "组ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{user_role.id.not_blank}")
@Size(min = 1, max = 50, message = "{user_role.id.length_range}")
private String userRoleId;
@Schema(description = "项目ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{project.id.not_blank}")
@Size(min = 1, max = 50, message = "{project.id.length_range}")
private String projectId;
}

View File

@ -0,0 +1,138 @@
package io.metersphere.project.service;
import io.metersphere.project.domain.Project;
import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.project.request.ProjectUserRoleEditRequest;
import io.metersphere.project.request.ProjectUserRoleMemberEditRequest;
import io.metersphere.sdk.constants.OperationLogConstants;
import io.metersphere.sdk.dto.LogDTO;
import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
import io.metersphere.sdk.log.constants.OperationLogModule;
import io.metersphere.sdk.log.constants.OperationLogType;
import io.metersphere.sdk.util.JSON;
import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRoleExample;
import io.metersphere.system.mapper.UserRoleMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author song-cc-rock
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class ProjectUserRoleLogService {
@Resource
private UserRoleMapper userRoleMapper;
@Resource
private ProjectMapper projectMapper;
/**
* 新增项目-用户组
* @param request 接口请求参数
* @return 日志详情
*/
public LogDTO addLog(ProjectUserRoleEditRequest request) {
Project project = getProject(request.getScopeId());
LogDTO dto = new LogDTO(
project.getId(),
project.getOrganizationId(),
OperationLogConstants.SYSTEM,
null,
OperationLogType.ADD.name(),
OperationLogModule.PROJECT_MANAGEMENT_PERMISSION_USER_ROLE,
request.getName());
dto.setOriginalValue(JSON.toJSONBytes(request.getName()));
return dto;
}
/**
* 更新项目-用户组
* @param request 接口请求参数
* @return 日志详情
*/
public LogDTO updateLog(ProjectUserRoleEditRequest request) {
Project project = getProject(request.getScopeId());
LogDTO dto = new LogDTO(
project.getId(),
project.getOrganizationId(),
OperationLogConstants.SYSTEM,
null,
OperationLogType.UPDATE.name(),
OperationLogModule.PROJECT_MANAGEMENT_PERMISSION_USER_ROLE,
request.getName());
UserRoleExample example = new UserRoleExample();
example.createCriteria().andIdEqualTo(request.getId());
UserRole userRole = userRoleMapper.selectByExample(example).get(0);
dto.setOriginalValue(JSON.toJSONBytes(userRole.getName()));
dto.setModifiedValue(JSON.toJSONBytes(request.getName()));
return dto;
}
/**
* 删除项目-用户组
* @param id 接口请求参数
* @return 日志详情
*/
public LogDTO deleteLog(String id) {
UserRole userRole = userRoleMapper.selectByPrimaryKey(id);
Project project = getProject(userRole.getScopeId());
LogDTO dto = new LogDTO(
project.getId(),
project.getOrganizationId(),
OperationLogConstants.SYSTEM,
null,
OperationLogType.DELETE.name(),
OperationLogModule.PROJECT_MANAGEMENT_PERMISSION_USER_ROLE,
userRole.getName());
dto.setOriginalValue(JSON.toJSONBytes(userRole.getName()));
return dto;
}
/**
* 更新项目-用户组-权限
* @param request 接口请求参数
* @return 日志详情
*/
public LogDTO updatePermissionSettingLog(PermissionSettingUpdateRequest request) {
LogDTO dto = getLog(request.getUserRoleId());
dto.setType(OperationLogType.UPDATE.name());
dto.setOriginalValue(JSON.toJSONBytes(request));
return dto;
}
/**
* 更新项目-用户组-成员
* @param request 接口请求参数
* @return 日志详情
*/
public LogDTO editMemberLog(ProjectUserRoleMemberEditRequest request) {
LogDTO dto = getLog(request.getUserRoleId());
dto.setType(OperationLogType.UPDATE.name());
dto.setModifiedValue(JSON.toJSONBytes(request));
return dto;
}
private LogDTO getLog(String roleId) {
UserRole userRole = userRoleMapper.selectByPrimaryKey(roleId);
Project project = getProject(userRole.getScopeId());
return new LogDTO(
project.getId(),
project.getOrganizationId(),
OperationLogConstants.SYSTEM,
null,
null,
OperationLogModule.PROJECT_MANAGEMENT_PERMISSION_USER_ROLE,
userRole.getName());
}
private Project getProject(String id) {
return projectMapper.selectByPrimaryKey(id);
}
}

View File

@ -0,0 +1,194 @@
package io.metersphere.project.service;
import io.metersphere.project.mapper.ExtProjectUserRoleMapper;
import io.metersphere.project.request.ProjectUserRoleMemberEditRequest;
import io.metersphere.project.request.ProjectUserRoleMemberRequest;
import io.metersphere.sdk.constants.InternalUserRole;
import io.metersphere.sdk.constants.UserRoleEnum;
import io.metersphere.sdk.constants.UserRoleType;
import io.metersphere.sdk.dto.PermissionDefinitionItem;
import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.service.BaseUserRoleService;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.*;
import io.metersphere.system.dto.UserExtend;
import io.metersphere.system.mapper.UserMapper;
import io.metersphere.system.mapper.UserRoleMapper;
import io.metersphere.system.mapper.UserRoleRelationMapper;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
import static io.metersphere.system.controller.result.SystemResultCode.NO_PROJECT_USER_ROLE_PERMISSION;
/**
* 项目-用户组与权限
* @author song-cc-rock
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class ProjectUserRoleService extends BaseUserRoleService {
@Resource
UserMapper userMapper;
@Resource
UserRoleMapper userRoleMapper;
@Resource
UserRoleRelationMapper userRoleRelationMapper;
@Resource
ExtProjectUserRoleMapper extProjectUserRoleMapper;
public List<UserRole> list(String projectId) {
UserRoleExample example = new UserRoleExample();
example.createCriteria().andTypeEqualTo(UserRoleType.PROJECT.name())
.andScopeIdIn(Arrays.asList(projectId, UserRoleEnum.GLOBAL.toString()));
return userRoleMapper.selectByExample(example);
}
@Override
public UserRole add(UserRole userRole) {
userRole.setInternal(false);
userRole.setType(UserRoleType.PROJECT.name());
checkNewRoleExist(userRole);
return super.add(userRole);
}
@Override
public UserRole update(UserRole userRole) {
UserRole oldRole = get(userRole.getId());
// 非像项目用户组不允许修改, 内置用户组不允许修改
checkProjectUserRole(oldRole);
checkInternalUserRole(oldRole);
userRole.setType(UserRoleType.PROJECT.name());
checkNewRoleExist(userRole);
return super.update(userRole);
}
public void delete(String roleId, String currentUserId) {
UserRole userRole = get(roleId);
// 非项目用户组不允许删除, 内置用户组不允许删除
checkProjectUserRole(userRole);
super.delete(userRole, InternalUserRole.PROJECT_MEMBER.getValue(), currentUserId, userRole.getScopeId());
}
public List<UserExtend> getMember(String projectId, String roleId) {
List<UserExtend> userExtends = new ArrayList<>();
// 查询项目下所有用户关系
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andSourceIdEqualTo(projectId);
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectByExample(example);
if (CollectionUtils.isNotEmpty(userRoleRelations)) {
Map<String, List<String>> userRoleMap = userRoleRelations.stream().collect(Collectors.groupingBy(UserRoleRelation::getUserId,
Collectors.mapping(UserRoleRelation::getRoleId, Collectors.toList())));
userRoleMap.forEach((k, v) -> {
UserExtend userExtend = new UserExtend();
userExtend.setId(k);
v.forEach(roleItem -> {
if (StringUtils.equals(roleItem, roleId)) {
// 该用户已存在用户组关系, 设置为选中状态
userExtend.setCheckRoleFlag(true);
}
});
userExtends.add(userExtend);
});
// 设置用户信息, 用户不存在或者已删除, 则不展示
List<String> userIds = userExtends.stream().map(UserExtend::getId).toList();
UserExample userExample = new UserExample();
userExample.createCriteria().andIdIn(userIds).andDeletedEqualTo(false);
List<User> users = userMapper.selectByExample(userExample);
if (CollectionUtils.isNotEmpty(users)) {
Map<String, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));
userExtends.removeIf(userExtend -> {
if (userMap.containsKey(userExtend.getId())) {
BeanUtils.copyBean(userExtend, userMap.get(userExtend.getId()));
return false;
}
return true;
});
} else {
userExtends.clear();
}
}
return userExtends;
}
public List<User> listMember(ProjectUserRoleMemberRequest request) {
return extProjectUserRoleMapper.listProjectRoleMember(request);
}
public void addMember(ProjectUserRoleMemberEditRequest request, String createUserId) {
request.getUserIds().forEach(userId -> {
checkMemberParam(userId, request.getUserRoleId());
UserRoleRelation relation = new UserRoleRelation();
relation.setId(UUID.randomUUID().toString());
relation.setUserId(userId);
relation.setRoleId(request.getUserRoleId());
relation.setSourceId(request.getProjectId());
relation.setCreateTime(System.currentTimeMillis());
relation.setCreateUser(createUserId);
relation.setOrganizationId(request.getProjectId());
userRoleRelationMapper.insert(relation);
});
}
public void removeMember(ProjectUserRoleMemberEditRequest request) {
String removeUserId = request.getUserIds().get(0);
checkMemberParam(removeUserId, request.getUserRoleId());
// 移除项目-用户组的成员, 若成员只存在该项目下唯一用户组, 则提示不能移除
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andUserIdEqualTo(removeUserId)
.andRoleIdNotEqualTo(request.getUserRoleId())
.andSourceIdEqualTo(request.getProjectId());
if (userRoleRelationMapper.countByExample(example) == 0) {
throw new MSException(Translator.get("at_least_one_user_role_require"));
}
example.clear();
example.createCriteria().andUserIdEqualTo(removeUserId)
.andRoleIdEqualTo(request.getUserRoleId())
.andSourceIdEqualTo(request.getProjectId());
userRoleRelationMapper.deleteByExample(example);
}
public List<PermissionDefinitionItem> getPermissionSetting(String id) {
UserRole userRole = get(id);
if (userRole == null) {
throw new MSException(Translator.get("user_role_not_exist"));
}
checkProjectUserRole(userRole);
return getPermissionSetting(userRole);
}
@Override
public void updatePermissionSetting(PermissionSettingUpdateRequest request) {
UserRole userRole = get(request.getUserRoleId());
checkProjectUserRole(userRole);
checkInternalUserRole(userRole);
super.updatePermissionSetting(request);
}
@Override
public UserRole get(String id) {
UserRole userRole = userRoleMapper.selectByPrimaryKey(id);
if (userRole == null) {
throw new MSException(Translator.get("user_role_not_exist"));
}
return userRole;
}
/**
* 校验是否项目下用户组
* @param userRole 用户组
*/
private void checkProjectUserRole(UserRole userRole) {
if (!UserRoleType.PROJECT.name().equals(userRole.getType())) {
throw new MSException(NO_PROJECT_USER_ROLE_PERMISSION);
}
}
}

View File

@ -72,7 +72,7 @@ public class ProjectMemberControllerTests extends BaseTest {
|| StringUtils.contains(projectUserDTO.getPhone(), request.getKeyword()));
// 权限校验
request.setProjectId(DEFAULT_PROJECT_ID);
requestPostPermissionTest(PermissionConstants.PROJECT_MEMBER_READ, LIST_MEMBER, request);
requestPostPermissionTest(PermissionConstants.PROJECT_USER_READ, LIST_MEMBER, request);
}
@Test
@ -113,7 +113,7 @@ public class ProjectMemberControllerTests extends BaseTest {
// 项目成员为空
this.requestGet(GET_MEMBER + "/default-project-member-test-2", status().isOk());
// 权限校验
requestGetPermissionTest(PermissionConstants.PROJECT_MEMBER_ADD, GET_MEMBER + "/" + DEFAULT_PROJECT_ID);
requestGetPermissionTest(PermissionConstants.PROJECT_USER_READ, GET_MEMBER + "/" + DEFAULT_PROJECT_ID);
}
@Test
@ -121,7 +121,7 @@ public class ProjectMemberControllerTests extends BaseTest {
public void testGetRoleOption() throws Exception {
this.requestGet(GET_ROLE + "/default-project-member-test", status().isOk());
// 权限校验
requestGetPermissionTest(PermissionConstants.PROJECT_MEMBER_ADD, GET_ROLE + "/" + DEFAULT_PROJECT_ID);
requestGetPermissionTest(PermissionConstants.PROJECT_USER_READ, GET_ROLE + "/" + DEFAULT_PROJECT_ID);
}
@Test
@ -136,7 +136,7 @@ public class ProjectMemberControllerTests extends BaseTest {
checkLog("default-project-member-user-1", OperationLogType.ADD);
// 权限校验
request.setProjectId(DEFAULT_PROJECT_ID);
requestPostPermissionTest(PermissionConstants.PROJECT_MEMBER_ADD, ADD_MEMBER, request);
requestPostPermissionTest(PermissionConstants.PROJECT_USER_ADD, ADD_MEMBER, request);
}
@Test
@ -175,7 +175,7 @@ public class ProjectMemberControllerTests extends BaseTest {
checkLog("default-project-member-user-1", OperationLogType.UPDATE);
// 权限校验
request.setProjectId(DEFAULT_PROJECT_ID);
requestPostPermissionTest(PermissionConstants.PROJECT_MEMBER_UPDATE, UPDATE_MEMBER, request);
requestPostPermissionTest(PermissionConstants.PROJECT_USER_UPDATE, UPDATE_MEMBER, request);
}
@Test
@ -195,7 +195,7 @@ public class ProjectMemberControllerTests extends BaseTest {
// 日志
checkLog("default-project-member-user-1", OperationLogType.DELETE);
// 权限校验
requestGetPermissionTest(PermissionConstants.PROJECT_MEMBER_DELETE, REMOVE_MEMBER + "/" + DEFAULT_PROJECT_ID + "/default-project-member-user-1");
requestGetPermissionTest(PermissionConstants.PROJECT_USER_DELETE, REMOVE_MEMBER + "/" + DEFAULT_PROJECT_ID + "/default-project-member-user-1");
}
@Test
@ -216,7 +216,7 @@ public class ProjectMemberControllerTests extends BaseTest {
checkLog("default-project-member-user-2", OperationLogType.UPDATE);
// 权限校验
request.setProjectId(DEFAULT_PROJECT_ID);
requestPostPermissionTest(PermissionConstants.PROJECT_MEMBER_UPDATE, ADD_ROLE, request);
requestPostPermissionTest(PermissionConstants.PROJECT_USER_UPDATE, ADD_ROLE, request);
}
@Test
@ -240,7 +240,7 @@ public class ProjectMemberControllerTests extends BaseTest {
checkLog("default-project-member-user-1", OperationLogType.DELETE);
// 权限校验
request.setProjectId(DEFAULT_PROJECT_ID);
requestPostPermissionTest(PermissionConstants.PROJECT_MEMBER_DELETE, BATCH_REMOVE_MEMBER, request);
requestPostPermissionTest(PermissionConstants.PROJECT_USER_DELETE, BATCH_REMOVE_MEMBER, request);
}
@Test

View File

@ -0,0 +1,431 @@
package io.metersphere.project.controller;
import io.metersphere.project.request.ProjectUserRoleEditRequest;
import io.metersphere.project.request.ProjectUserRoleMemberEditRequest;
import io.metersphere.project.request.ProjectUserRoleMemberRequest;
import io.metersphere.sdk.base.BaseTest;
import io.metersphere.sdk.constants.InternalUserRole;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.controller.handler.ResultHolder;
import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
import io.metersphere.sdk.service.BaseUserRolePermissionService;
import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.Pager;
import io.metersphere.system.domain.User;
import io.metersphere.system.domain.UserRole;
import io.metersphere.system.request.OrganizationUserRoleEditRequest;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.*;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static io.metersphere.sdk.controller.handler.result.CommonResultCode.INTERNAL_USER_ROLE_PERMISSION;
import static io.metersphere.system.controller.result.SystemResultCode.NO_PROJECT_USER_ROLE_PERMISSION;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ProjectUserRoleControllerTests extends BaseTest {
@Resource
private MockMvc mockMvc;
@Resource
private BaseUserRolePermissionService baseUserRolePermissionService;
public static final String PROJECT_USER_ROLE_LIST = "/user/role/project/list";
public static final String PROJECT_USER_ROLE_ADD = "/user/role/project/add";
public static final String PROJECT_USER_ROLE_UPDATE = "/user/role/project/update";
public static final String PROJECT_USER_ROLE_DELETE = "/user/role/project/delete";
public static final String PROJECT_USER_ROLE_PERMISSION_SETTING = "/user/role/project/permission/setting";
public static final String PROJECT_USER_ROLE_PERMISSION_UPDATE = "/user/role/project/permission/update";
public static final String PROJECT_USER_ROLE_GET_MEMBER_OPTION = "/user/role/project/get-member/option";
public static final String PROJECT_USER_ROLE_LIST_MEMBER = "/user/role/project/list-member";
public static final String PROJECT_USER_ROLE_ADD_MEMBER = "/user/role/project/add-member";
public static final String PROJECT_USER_ROLE_REMOVE_MEMBER = "/user/role/project/remove-member";
@Test
@Order(0)
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "/dml/init_project_user_role.sql")
public void testProjectUserRoleListSuccess() throws Exception {
String projectId = "default-project-2";
MvcResult mvcResult = this.responseGet(PROJECT_USER_ROLE_LIST + "/" + projectId);
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
// 返回请求正常
Assertions.assertNotNull(resultHolder);
// 返回总条数是否为init_project_user_role.sql中的数据总数
Assertions.assertFalse(JSON.parseArray(JSON.toJSONString(resultHolder.getData())).isEmpty());
// 权限校验
requestGetPermissionTest(PermissionConstants.PROJECT_GROUP_READ, PROJECT_USER_ROLE_LIST + "/" + DEFAULT_PROJECT_ID);
}
@Test
@Order(1)
public void testProjectUserRoleAddSuccess() throws Exception {
ProjectUserRoleEditRequest request = new ProjectUserRoleEditRequest();
request.setName("default-pro-role-5");
request.setScopeId("default-project-2");
this.requestPost(PROJECT_USER_ROLE_ADD, request);
// 验证是否添加成功
String projectId = "default-project-2";
MvcResult mvcResult = this.responseGet(PROJECT_USER_ROLE_LIST + "/" + projectId);
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
// 返回请求正常
Assertions.assertNotNull(resultHolder);
// 返回总条数是否为init_project_user_role.sql中的数据总数
Assertions.assertFalse(JSON.parseArray(JSON.toJSONString(resultHolder.getData())).isEmpty());
// 权限校验
requestPostPermissionTest(PermissionConstants.PROJECT_GROUP_ADD, PROJECT_USER_ROLE_ADD, request);
}
@Test
@Order(2)
public void testProjectUserRoleAddError() throws Exception {
ProjectUserRoleEditRequest request = new ProjectUserRoleEditRequest();
// 同名用户组已存在
request.setName("default-pro-role-2");
request.setScopeId("default-project-2");
this.requestPost(PROJECT_USER_ROLE_ADD, request, status().is5xxServerError());
}
@Test
@Order(3)
public void testProjectUserRoleUpdateError() throws Exception {
ProjectUserRoleEditRequest request = new ProjectUserRoleEditRequest();
// 用户组不存在
request.setId("default-pro-role-id-10");
this.requestPost(PROJECT_USER_ROLE_UPDATE, request, status().is5xxServerError());
// 非项目下用户组异常
request = new ProjectUserRoleEditRequest();
request.setId(InternalUserRole.ADMIN.getValue());
this.requestPost(PROJECT_USER_ROLE_UPDATE, request).andExpect(jsonPath("$.code").value(NO_PROJECT_USER_ROLE_PERMISSION.getCode()));
// 非内置用户组异常
request = new ProjectUserRoleEditRequest();
request.setId(InternalUserRole.PROJECT_ADMIN.getValue());
this.requestPost(PROJECT_USER_ROLE_UPDATE, request).andExpect(jsonPath("$.code").value(INTERNAL_USER_ROLE_PERMISSION.getCode()));
// 用户组名称已存在
request = new ProjectUserRoleEditRequest();
request.setId("default-pro-role-id-2");
request.setName("项目管理员");
request.setScopeId("default-project-2");
this.requestPost(PROJECT_USER_ROLE_UPDATE, request, status().is5xxServerError());
}
@Test
@Order(4)
public void testProjectUserRoleUpdateSuccess() throws Exception {
OrganizationUserRoleEditRequest request = new OrganizationUserRoleEditRequest();
request.setId("default-pro-role-id-2");
request.setName("default-pro-role-x");
request.setScopeId("default-project-2");
this.requestPost(PROJECT_USER_ROLE_UPDATE, request, status().isOk());
// 验证是否修改成功
String projectId = "default-project-2";
MvcResult mvcResult = this.responseGet(PROJECT_USER_ROLE_LIST + "/" + projectId);
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
// 返回请求正常
Assertions.assertNotNull(resultHolder);
// 返回总条数是否包含修改后的数据
List<UserRole> userRoles = JSON.parseArray(JSON.toJSONString(resultHolder.getData()), UserRole.class);
Assertions.assertTrue(userRoles.stream().anyMatch(userRole -> "default-pro-role-x".equals(userRole.getName())));
// 权限校验
requestPostPermissionTest(PermissionConstants.PROJECT_GROUP_UPDATE, PROJECT_USER_ROLE_UPDATE, request);
}
@Test
@Order(5)
public void testProjectUserRoleDeleteError() throws Exception {
// 用户组不存在
this.requestGet(PROJECT_USER_ROLE_DELETE + "/default-pro-role-id-10", status().is5xxServerError());
// 非项目下用户组异常
this.requestGet(PROJECT_USER_ROLE_DELETE + "/" + InternalUserRole.ADMIN.getValue()).andExpect(jsonPath("$.code").value(NO_PROJECT_USER_ROLE_PERMISSION.getCode()));
// 非内置用户组异常
this.requestGet(PROJECT_USER_ROLE_DELETE + "/" + InternalUserRole.PROJECT_ADMIN.getValue()).andExpect(jsonPath("$.code").value(INTERNAL_USER_ROLE_PERMISSION.getCode()));
}
@Test
@Order(6)
public void testProjectUserRoleDeleteSuccess() throws Exception {
this.requestGet(PROJECT_USER_ROLE_DELETE + "/default-pro-role-id-2", status().isOk());
// 权限校验
requestGetPermissionTest(PermissionConstants.PROJECT_GROUP_DELETE, PROJECT_USER_ROLE_DELETE + "/default-pro-role-id-2");
}
@Test
@Order(7)
public void testProjectUserRolePermissionSettingSuccess() throws Exception {
MvcResult mvcResult = this.responseGet(PROJECT_USER_ROLE_PERMISSION_SETTING + "/default-pro-role-id-3");
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
// 返回请求正常
Assertions.assertNotNull(resultHolder);
// 返回总条数是否为init_project_user_role.sql中的数据总数
Assertions.assertEquals(1, JSON.parseArray(JSON.toJSONString(resultHolder.getData())).size());
// 权限校验
requestGetPermissionTest(PermissionConstants.PROJECT_GROUP_READ, PROJECT_USER_ROLE_PERMISSION_SETTING + "/default-pro-role-id-3");
}
@Test
@Order(8)
public void testProjectUserRolePermissionSettingError() throws Exception {
// 用户组不存在
this.requestGet(PROJECT_USER_ROLE_PERMISSION_SETTING + "/default-pro-role-id-10", status().is5xxServerError());
// 非项目下用户组异常
this.requestGet(PROJECT_USER_ROLE_PERMISSION_SETTING + "/" + InternalUserRole.ADMIN.getValue())
.andExpect(jsonPath("$.code").value(NO_PROJECT_USER_ROLE_PERMISSION.getCode()));
}
@Test
@Order(9)
public void testProjectUserRolePermissionUpdateSuccess() throws Exception {
PermissionSettingUpdateRequest request = getPermissionSettingUpdateRequest();
request.setUserRoleId("default-pro-role-id-3");
this.requestPost(PROJECT_USER_ROLE_PERMISSION_UPDATE, request, status().isOk());
// 返回权限勾选PROJECT_GROUP:ADD
Set<String> permissionIds = baseUserRolePermissionService.getPermissionIdSetByRoleId(request.getUserRoleId());
Set<String> requestPermissionIds = request.getPermissions().stream()
.filter(PermissionSettingUpdateRequest.PermissionUpdateRequest::getEnable)
.map(PermissionSettingUpdateRequest.PermissionUpdateRequest::getId)
.collect(Collectors.toSet());
// 校验请求成功数据
Assertions.assertEquals(requestPermissionIds, permissionIds);
// 权限校验
requestPostPermissionTest(PermissionConstants.PROJECT_GROUP_UPDATE, PROJECT_USER_ROLE_PERMISSION_UPDATE, request);
}
@Test
@Order(10)
public void testProjectUserRolePermissionUpdateError() throws Exception {
// 用户组不存在
PermissionSettingUpdateRequest request = getPermissionSettingUpdateRequest();
request.setUserRoleId("default-pro-role-id-10");
this.requestPost(PROJECT_USER_ROLE_PERMISSION_UPDATE, request, status().is5xxServerError());
// 非项目下用户组异常
request.setUserRoleId(InternalUserRole.ADMIN.getValue());
this.requestPost(PROJECT_USER_ROLE_PERMISSION_UPDATE, request)
.andExpect(jsonPath("$.code").value(NO_PROJECT_USER_ROLE_PERMISSION.getCode()));
// 内置用户组异常
request.setUserRoleId(InternalUserRole.PROJECT_ADMIN.getValue());
this.requestPost(PROJECT_USER_ROLE_PERMISSION_UPDATE, request)
.andExpect(jsonPath("$.code").value(INTERNAL_USER_ROLE_PERMISSION.getCode()));
}
@Test
@Order(11)
public void testProjectUserRoleListMemberSuccess() throws Exception {
ProjectUserRoleMemberRequest request = new ProjectUserRoleMemberRequest();
request.setProjectId("default-project-2");
request.setUserRoleId("default-pro-role-id-3");
request.setKeyword("admin");
request.setCurrent(1);
request.setPageSize(10);
MvcResult mvcResult = this.responsePost(PROJECT_USER_ROLE_LIST_MEMBER, request);
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
// 返回请求正常
Assertions.assertNotNull(resultHolder);
Pager<?> pageData = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), Pager.class);
// 返回值不为空
Assertions.assertNotNull(pageData);
// 返回值的页码和当前页码相同
Assertions.assertEquals(pageData.getCurrent(), request.getCurrent());
// 返回的数据量不超过规定要返回的数据量相同
Assertions.assertTrue(JSON.parseArray(JSON.toJSONString(pageData.getList())).size() <= request.getPageSize());
// 返回值中取出第一条数据, 并判断是否包含关键字
List<User> userList = JSON.parseArray(JSON.toJSONString(pageData.getList()), User.class);
if(CollectionUtils.isNotEmpty(userList)) {
User user = userList.get(0);
Assertions.assertTrue(StringUtils.contains(user.getName(), request.getKeyword())
|| StringUtils.contains(user.getId(), request.getKeyword()));
}
// 权限校验
request.setProjectId(DEFAULT_PROJECT_ID);
requestPostPermissionTest(PermissionConstants.PROJECT_GROUP_READ, PROJECT_USER_ROLE_LIST_MEMBER, request);
}
@Test
@Order(12)
public void testProjectUserRoleListMemberError() throws Exception {
ProjectUserRoleMemberRequest request = new ProjectUserRoleMemberRequest();
request.setProjectId("default-project-2");
request.setUserRoleId("default-pro-role-id-3");
request.setCurrent(0);
request.setPageSize(10);
// 页码有误
this.requestPost(PROJECT_USER_ROLE_LIST_MEMBER, request, status().isBadRequest());
request = new ProjectUserRoleMemberRequest();
request.setProjectId("default-project-2");
request.setUserRoleId("default-pro-role-id-3");
request.setCurrent(1);
request.setPageSize(1);
// 页数有误
this.requestPost(PROJECT_USER_ROLE_LIST_MEMBER, request, status().isBadRequest());
}
@Test
@Order(13)
public void testProjectUserRoleAddMemberSuccess() throws Exception {
ProjectUserRoleMemberEditRequest request = new ProjectUserRoleMemberEditRequest();
request.setProjectId("default-project-2");
request.setUserRoleId("default-pro-role-id-3");
request.setUserIds(List.of("admin"));
this.requestPost(PROJECT_USER_ROLE_ADD_MEMBER, request, status().isOk());
// 权限校验
request.setProjectId(DEFAULT_PROJECT_ID);
requestPostPermissionTest(PermissionConstants.PROJECT_GROUP_UPDATE, PROJECT_USER_ROLE_ADD_MEMBER, request);
}
@Test
@Order(14)
public void testProjectUserRoleAddMemberError() throws Exception {
ProjectUserRoleMemberEditRequest request = new ProjectUserRoleMemberEditRequest();
request.setProjectId("default-project-2");
request.setUserIds(List.of("admin-x"));
request.setUserRoleId("default-pro-role-id-3");
// 用户不存在
this.requestPost(PROJECT_USER_ROLE_ADD_MEMBER, request, status().is5xxServerError());
request = new ProjectUserRoleMemberEditRequest();
request.setProjectId("default-project-2");
request.setUserIds(List.of("admin"));
request.setUserRoleId("default-pro-role-id-x");
// 用户组不存在
this.requestPost(PROJECT_USER_ROLE_ADD_MEMBER, request, status().is5xxServerError());
}
@Test
@Order(15)
public void testProjectUserRoleGetMemberOption() throws Exception {
// 组织下存在已删除用户
this.responseGet(PROJECT_USER_ROLE_GET_MEMBER_OPTION + "/default-project-2/default-pro-role-id-4");
// 组织下用户都已删除
this.responseGet(PROJECT_USER_ROLE_GET_MEMBER_OPTION + "/default-project-4/default-pro-role-id-3");
// 组织下无用户
this.responseGet(PROJECT_USER_ROLE_GET_MEMBER_OPTION + "/default-project-3/default-pro-role-id-3");
}
@Test
@Order(16)
public void testProjectUserRoleRemoveMemberSuccess() throws Exception {
ProjectUserRoleMemberEditRequest request = new ProjectUserRoleMemberEditRequest();
request.setProjectId("default-project-2");
request.setUserRoleId("default-pro-role-id-4");
request.setUserIds(List.of("admin"));
this.requestPost(PROJECT_USER_ROLE_ADD_MEMBER, request, status().isOk());
// 成员项目用户组存在多个, 移除成功
this.requestPost(PROJECT_USER_ROLE_REMOVE_MEMBER, request, status().isOk());
// 权限校验
request.setProjectId(DEFAULT_PROJECT_ID);
requestPostPermissionTest(PermissionConstants.PROJECT_GROUP_UPDATE, PROJECT_USER_ROLE_REMOVE_MEMBER, request);
}
@Test
@Order(17)
public void testProjectUserRoleRemoveMemberError() throws Exception {
ProjectUserRoleMemberEditRequest request = new ProjectUserRoleMemberEditRequest();
request.setProjectId("default-project-2");
request.setUserIds(List.of("admin-x"));
request.setUserRoleId("default-pro-role-id-3");
// 用户不存在
this.requestPost(PROJECT_USER_ROLE_REMOVE_MEMBER, request, status().is5xxServerError());
request = new ProjectUserRoleMemberEditRequest();
request.setProjectId("default-project-2");
request.setUserIds(List.of("admin"));
request.setUserRoleId("default-pro-role-id-x");
// 用户组不存在
this.requestPost(PROJECT_USER_ROLE_REMOVE_MEMBER, request, status().is5xxServerError());
request = new ProjectUserRoleMemberEditRequest();
request.setProjectId("default-project-2");
request.setUserRoleId("default-pro-role-id-3");
request.setUserIds(List.of("admin"));
// 成员用户组只有一个, 移除失败
this.requestPost(PROJECT_USER_ROLE_REMOVE_MEMBER, request, status().is5xxServerError());
}
@Test
@Order(18)
public void testProjectUserRoleDeleteOnlyMemberSuccess() throws Exception {
ProjectUserRoleMemberEditRequest request = new ProjectUserRoleMemberEditRequest();
request.setProjectId("default-project-2");
request.setUserRoleId("default-pro-role-id-4");
request.setUserIds(List.of("default-pro-admin-user"));
this.requestPost(PROJECT_USER_ROLE_ADD_MEMBER, request, status().isOk());
// 移除用户组, 且存在成员仅有该用户组
this.requestGet(PROJECT_USER_ROLE_DELETE + "/default-pro-role-id-3", status().isOk());
}
private PermissionSettingUpdateRequest getPermissionSettingUpdateRequest(){
PermissionSettingUpdateRequest request = new PermissionSettingUpdateRequest();
request.setPermissions(new ArrayList<>() {
{
// 取消PROJECT_GROUP:READ权限
add(new PermissionSettingUpdateRequest.PermissionUpdateRequest("PROJECT_GROUP:READ", false));
// 添加PROJECT_GROUP:ADD, PROJECT_GROUP:UPDATE权限
add(new PermissionSettingUpdateRequest.PermissionUpdateRequest("PROJECT_GROUP:READ+ADD", true));
add(new PermissionSettingUpdateRequest.PermissionUpdateRequest("PROJECT_GROUP:READ+UPDATE", true));
}
});
return request;
}
private void requestPost(String url, Object param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
private MvcResult responsePost(String url, Object param) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
}
private void requestGet(String url, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
private MvcResult responseGet(String url) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andReturn();
}
}

View File

@ -0,0 +1,19 @@
# 项目用户组数据准备
INSERT INTO project (id, num, organization_id, name, description, create_user, update_user, create_time, update_time) VALUE
('default-project-1', null, 'default-organization-1', '默认项目-1', '系统默认创建的项目-1', 'admin', 'admin', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000);
INSERT INTO project (id, num, organization_id, name, description, create_user, update_user, create_time, update_time) VALUE
('default-project-2', null, 'default-organization-2', '默认项目-2', '系统默认创建的项目-2', 'admin', 'admin', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000);
INSERT INTO user(id, name, email, password, create_time, update_time, language, last_organization_id, phone, source, last_project_id, create_user, update_user) VALUE
('default-pro-admin-user', 'default-pro-admin-1', 'admin-default-pro-user@metersphere.io', MD5('metersphere'), UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin');
INSERT INTO user_role(id, name, description, internal, type, create_time, update_time, create_user, scope_id) VALUES
('default-pro-role-id-1', 'default-pro-role-1', 'XXX', FALSE, 'PROJECT', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'default-project-2'),
('default-pro-role-id-2', 'default-pro-role-2', 'XXX', FALSE, 'PROJECT', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'default-project-2'),
('default-pro-role-id-3', 'default-pro-role-3', 'XXX', FALSE, 'PROJECT', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'default-project-2'),
('default-pro-role-id-4', 'default-pro-role-4', 'XXX', FALSE, 'PROJECT', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'default-project-2');
INSERT INTO user_role_permission (id, role_id, permission_id) VALUE
(uuid(), 'default-org-role-id-3', 'PROJECT_USER_GROUP:READ');
INSERT INTO user_role_relation (id, user_id, role_id, source_id, organization_id, create_time, create_user) VALUES
(UUID(), 'default-pro-admin-user', 'default-pro-role-id-3', 'default-project-2', 'default-project-2', UNIX_TIMESTAMP() * 1000, 'admin'),
(UUID(), 'default-pro-admin-user', 'default-pro-role-id-4', 'default-project-2', 'default-project-2', UNIX_TIMESTAMP() * 1000, 'admin'),
(UUID(), 'default-admin-user-x', 'default-pro-role-id-4', 'default-project-2', 'default-project-2', UNIX_TIMESTAMP() * 1000, 'admin'),
(UUID(), 'default-admin-user-x', 'default-pro-role-id-3', 'default-organization-4', 'default-project-4', UNIX_TIMESTAMP() * 1000, 'admin');

View File

@ -22,7 +22,8 @@ public enum SystemResultCode implements IResultCode {
PLUGIN_EXIST(101008, "plugin.exist"),
PLUGIN_TYPE_EXIST(101009, "plugin.type.exist"),
PLUGIN_SCRIPT_EXIST(101010, "plugin.script.exist"),
PLUGIN_SCRIPT_FORMAT(101011, "plugin.script.format");
PLUGIN_SCRIPT_FORMAT(101011, "plugin.script.format"),
NO_PROJECT_USER_ROLE_PERMISSION(101012, "project_user_role_permission_error");
private final int code;
private final String message;

View File

@ -6,9 +6,7 @@ import io.metersphere.sdk.constants.UserRoleType;
import io.metersphere.sdk.dto.PermissionDefinitionItem;
import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.mapper.BaseUserMapper;
import io.metersphere.sdk.service.BaseUserRoleService;
import io.metersphere.sdk.service.BaseUserService;
import io.metersphere.sdk.uid.UUID;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.Translator;
@ -45,10 +43,6 @@ public class OrganizationUserRoleService extends BaseUserRoleService {
@Resource
UserMapper userMapper;
@Resource
BaseUserMapper baseUserMapper;
@Resource
BaseUserService baseUserService;
@Resource
UserRoleMapper userRoleMapper;
@Resource
ExtUserRoleMapper extUserRoleMapper;
@ -198,38 +192,4 @@ public class OrganizationUserRoleService extends BaseUserRoleService {
throw new MSException(NO_ORG_USER_ROLE_PERMISSION);
}
}
/**
* 校验同名用户组是否存在
* @param userRole 用户组
*/
private void checkNewRoleExist(UserRole userRole) {
UserRoleExample example = new UserRoleExample();
UserRoleExample.Criteria criteria = example.createCriteria().andNameEqualTo(userRole.getName())
.andScopeIdIn(Arrays.asList(userRole.getScopeId(), UserRoleEnum.GLOBAL.toString()))
.andTypeEqualTo(userRole.getType());
if (userRole.getId() != null) {
criteria.andIdNotEqualTo(userRole.getId());
}
List<UserRole> userRoles = userRoleMapper.selectByExample(example);
if (CollectionUtils.isNotEmpty(userRoles)) {
throw new MSException(Translator.get("user_role_exist"));
}
}
/**
* 校验用户与用户组是否存在
* @param userId 用户ID
* @param roleId 用户组ID
*/
private void checkMemberParam(String userId, String roleId) {
User user = userMapper.selectByPrimaryKey(userId);
if (user == null) {
throw new MSException(Translator.get("user_not_exist"));
}
UserRole userRole = userRoleMapper.selectByPrimaryKey(roleId);
if (userRole == null) {
throw new MSException(Translator.get("user_role_not_exist"));
}
}
}

View File

@ -387,8 +387,8 @@ public class OrganizationUserRoleControllerTests extends BaseTest {
// 取消ORGANIZATION_USER_ROLE:READ权限
add(new PermissionSettingUpdateRequest.PermissionUpdateRequest("ORGANIZATION_USER_ROLE:READ", false));
// 添加ORGANIZATION_USER_ROLE:CREATE, ORGANIZATION_USER_ROLE:UPDATE权限
add(new PermissionSettingUpdateRequest.PermissionUpdateRequest("ORGANIZATION_USER_ROLE:CREATE", true));
add(new PermissionSettingUpdateRequest.PermissionUpdateRequest("ORGANIZATION_USER_ROLE:UPDATE", true));
add(new PermissionSettingUpdateRequest.PermissionUpdateRequest("ORGANIZATION_USER_ROLE:READ+ADD", true));
add(new PermissionSettingUpdateRequest.PermissionUpdateRequest("ORGANIZATION_USER_ROLE:READ+UPDATE", true));
}
});
return request;