feat(系统设置): 组织用户组权限功能

This commit is contained in:
song-cc-rock 2023-07-11 16:33:25 +08:00 committed by 刘瑞斌
parent 6515a70886
commit af93728f3d
24 changed files with 1004 additions and 172 deletions

View File

@ -12,6 +12,28 @@ public class PermissionConstants {
public static final String SYSTEM_USER_ROLE_DELETE = "SYSTEM_USER_ROLE:READ+DELETE"; public static final String SYSTEM_USER_ROLE_DELETE = "SYSTEM_USER_ROLE:READ+DELETE";
/*------ end: SYSTEM_USER_ROLE ------*/ /*------ end: SYSTEM_USER_ROLE ------*/
/*------ start: SYSTEM_USER_ROLE_RELATION ------*/
public static final String SYSTEM_USER_ROLE_RELATION_READ = "SYSTEM_USER_ROLE_RELATION_READ:READ";
public static final String SYSTEM_USER_ROLE_RELATION_ADD = "SYSTEM_USER_ROLE_RELATION_READ:READ+ADD";
public static final String SYSTEM_USER_ROLE_RELATION_UPDATE = "SYSTEM_USER_ROLE_RELATION_READ:READ+UPDATE";
public static final String SYSTEM_USER_ROLE_RELATION_DELETE = "SYSTEM_USER_ROLE_RELATION_READ:READ+DELETE";
/*------ end: SYSTEM_USER_ROLE_RELATION ------*/
/*------ start: SYSTEM_ORGANIZATION_PROJECT ------*/
public static final String SYSTEM_ORGANIZATION_PROJECT_READ = "SYSTEM_ORGANIZATION_PROJECT:READ";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ_ADD = "SYSTEM_ORGANIZATION_PROJECT:READ+ADD";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ_UPDATE = "SYSTEM_ORGANIZATION_PROJECT:READ+UPDATE";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ_DELETE = "SYSTEM_ORGANIZATION_PROJECT:READ+DELETE";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ_RECOVER = "SYSTEM_ORGANIZATION_PROJECT:READ+RECOVER";
/*------ end: SYSTEM_ORGANIZATION_PROJECT ------*/
/*------ start: ORGANIZATION_USER_ROLE ------*/
public static final String ORGANIZATION_USER_ROLE_READ = "ORGANIZATION_USER_ROLE:READ";
public static final String ORGANIZATION_USER_ROLE_READ_ADD = "ORGANIZATION_USER_ROLE:READ+ADD";
public static final String ORGANIZATION_USER_ROLE_READ_UPDATE = "ORGANIZATION_USER_ROLE:READ+UPDATE";
public static final String ORGANIZATION_USER_ROLE_READ_DELETE = "ORGANIZATION_USER_ROLE:READ+DELETE";
/*------ end: ORGANIZATION_USER_ROLE ------*/
public static final String SYSTEM_USER_READ = "SYSTEM_USER:READ"; public static final String SYSTEM_USER_READ = "SYSTEM_USER:READ";
public static final String SYSTEM_USER_READ_ADD = "SYSTEM_USER:READ+ADD"; public static final String SYSTEM_USER_READ_ADD = "SYSTEM_USER:READ+ADD";
public static final String SYSTEM_USER_READ_IMPORT = "SYSTEM_USER:READ+IMPORT"; public static final String SYSTEM_USER_READ_IMPORT = "SYSTEM_USER:READ+IMPORT";
@ -19,12 +41,6 @@ public class PermissionConstants {
public static final String SYSTEM_USER_READ_DELETE = "SYSTEM_USER:READ+DELETE"; public static final String SYSTEM_USER_READ_DELETE = "SYSTEM_USER:READ+DELETE";
public static final String SYSTEM_USER_READ_UPDATE_PASSWORD = "SYSTEM_USER:READ+UPDATE_PASSWORD"; public static final String SYSTEM_USER_READ_UPDATE_PASSWORD = "SYSTEM_USER:READ+UPDATE_PASSWORD";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ = "SYSTEM_ORGANIZATION_PROJECT:READ";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ_ADD = "SYSTEM_ORGANIZATION_PROJECT:READ+ADD";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ_UPDATE = "SYSTEM_ORGANIZATION_PROJECT:READ+UPDATE";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ_DELETE = "SYSTEM_ORGANIZATION_PROJECT:READ+DELETE";
public static final String SYSTEM_ORGANIZATION_PROJECT_READ_RECOVER = "SYSTEM_ORGANIZATION_PROJECT:READ+RECOVER";
public static final String SYSTEM_TEST_RESOURCE_POOL_READ = "SYSTEM_TEST_RESOURCE_POOL:READ"; public static final String SYSTEM_TEST_RESOURCE_POOL_READ = "SYSTEM_TEST_RESOURCE_POOL:READ";
public static final String SYSTEM_TEST_RESOURCE_POOL_READ_ADD = "SYSTEM_TEST_RESOURCE_POOL:READ+ADD"; public static final String SYSTEM_TEST_RESOURCE_POOL_READ_ADD = "SYSTEM_TEST_RESOURCE_POOL:READ+ADD";
public static final String SYSTEM_TEST_RESOURCE_POOL_READ_UPDATE = "SYSTEM_TEST_RESOURCE_POOL:READ+UPDATE"; public static final String SYSTEM_TEST_RESOURCE_POOL_READ_UPDATE = "SYSTEM_TEST_RESOURCE_POOL:READ+UPDATE";

View File

@ -4,7 +4,9 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List; import java.util.List;
@ -22,6 +24,8 @@ public class PermissionSettingUpdateRequest {
private List<PermissionUpdateRequest> permissions; private List<PermissionUpdateRequest> permissions;
@Data @Data
@NoArgsConstructor
@AllArgsConstructor
public static class PermissionUpdateRequest { public static class PermissionUpdateRequest {
@NotBlank @NotBlank
@Schema(title = "权限ID", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(title = "权限ID", requiredMode = Schema.RequiredMode.REQUIRED)

View File

@ -26,7 +26,7 @@ cannot_delete_current_user=Cannot delete the user currently logged in
user_already_exists=The user already exists in the current member list user_already_exists=The user already exists in the current member list
cannot_remove_current=Unable to remove the currently logged in user cannot_remove_current=Unable to remove the currently logged in user
password_is_incorrect=Incorrect password or username password_is_incorrect=Incorrect password or username
user_not_exist=user does not exist\uFF1A user_not_exist=user does not exist
user_has_been_disabled=the user has been disabled. user_has_been_disabled=the user has been disabled.
excessive_attempts=Excessive attempts excessive_attempts=Excessive attempts
user_locked=the user has been locked. user_locked=the user has been locked.

View File

@ -27,7 +27,7 @@ user_already_exists=该用户已存在于当前成员列表中
cannot_remove_current=无法移除当前登录用户 cannot_remove_current=无法移除当前登录用户
login_fail=登录失败 login_fail=登录失败
password_is_incorrect=用户名或密码不正确 password_is_incorrect=用户名或密码不正确
user_not_exist=用户不存在 user_not_exist=用户不存在
user_has_been_disabled=用户已被禁用 user_has_been_disabled=用户已被禁用
excessive_attempts=操作频繁 excessive_attempts=操作频繁
user_locked=用户被锁定 user_locked=用户被锁定

View File

@ -27,7 +27,7 @@ user_already_exists=該用戶已存在於當前成員列表中
cannot_remove_current=無法移除當前登錄用戶 cannot_remove_current=無法移除當前登錄用戶
login_fail=登錄失敗 login_fail=登錄失敗
password_is_incorrect=用戶名或密碼不正確 password_is_incorrect=用戶名或密碼不正確
user_not_exist=用戶不存在 user_not_exist=用戶不存在
user_has_been_disabled=用戶已被禁用 user_has_been_disabled=用戶已被禁用
excessive_attempts=操作頻繁 excessive_attempts=操作頻繁
user_locked=用戶被鎖定 user_locked=用戶被鎖定

View File

@ -155,7 +155,13 @@ and_add_organization_admin=and add organization administrator
organization_add_member_ids_empty=organization add member cannot be empty organization_add_member_ids_empty=organization add member cannot be empty
organization_not_exist=organization does not exist organization_not_exist=organization does not exist
organization_member_not_exist=organization member does not exist organization_member_not_exist=organization member does not exist
global_user_role_permission_error=no global user role permission
global_user_role_exist_error=global user role already exists
global_user_role_relation_system_permission_error=no global user role relation system permission
organization_user_role_permission_error=no organization 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

@ -154,8 +154,10 @@ and_add_organization_admin=并添加组织管理员
organization_add_member_ids_empty=组织添加成员不能为空 organization_add_member_ids_empty=组织添加成员不能为空
organization_not_exist=组织不存在 organization_not_exist=组织不存在
organization_member_not_exist=组织成员不存在 organization_member_not_exist=组织成员不存在
# userRole
global_user_role_permission_error=没有权限操作非全局用户组 global_user_role_permission_error=没有权限操作非全局用户组
global_user_role_exist_error=全局用户组已存在 global_user_role_exist_error=全局用户组已存在
global_user_role_relation_system_permission_error=没有权限操作非系统级别用户组 global_user_role_relation_system_permission_error=没有权限操作非系统级别用户组
organization_user_role_permission_error=没有权限操作非组织用户组
user_role_exist=用户组已存在
user_role_not_exist=用户组不存在
user_role_not_edit=用户组无法编辑

View File

@ -154,3 +154,10 @@ and_add_organization_admin=並添加組織管理員
organization_add_member_ids_empty=組織添加成員不能爲空 organization_add_member_ids_empty=組織添加成員不能爲空
organization_not_exist=組織不存在 organization_not_exist=組織不存在
organization_member_not_exist=組織成員不存在 organization_member_not_exist=組織成員不存在
global_user_role_permission_error=沒有權限操作非全局用戶組
global_user_role_exist_error=全局用戶組已存在
global_user_role_relation_system_permission_error=沒有權限操作非系統級別用戶組
organization_user_role_permission_error=沒有權限操作非組織用戶組
user_role_exist=用戶組已存在
user_role_not_exist=用戶組不存在
user_role_not_edit=用戶組無法編輯

View File

@ -73,7 +73,7 @@ public class OrganizationController {
@Operation(summary = "删除组织成员") @Operation(summary = "删除组织成员")
@Parameters({ @Parameters({
@Parameter(name = "organizationId", description = "组织ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED)), @Parameter(name = "organizationId", description = "组织ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED)),
@Parameter(name = "userId", description = "用户ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED)) @Parameter(name = "userId", description = "成员ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED))
}) })
@RequiresPermissions(PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ_UPDATE) @RequiresPermissions(PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ_UPDATE)
public void removeMember(@PathVariable String organizationId, @PathVariable String userId) { public void removeMember(@PathVariable String organizationId, @PathVariable String userId) {

View File

@ -0,0 +1,106 @@
package io.metersphere.system.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.dto.PermissionDefinitionItem;
import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
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.request.OrganizationUserRoleEditRequest;
import io.metersphere.system.request.OrganizationUserRoleMemberEditRequest;
import io.metersphere.system.request.OrganizationUserRoleMemberRequest;
import io.metersphere.system.service.OrganizationUserRoleService;
import io.swagger.v3.oas.annotations.Operation;
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;
/**
* @author song-cc-rock
*/
@Tag(name = "组织-用户组与权限")
@RestController
@RequestMapping("/user/role/organization")
public class OrganizationUserRoleController {
@Resource
OrganizationUserRoleService organizationUserRoleService;
@GetMapping("/list/{organizationId}")
@Operation(summary = "获取组织用户组列表")
@RequiresPermissions(PermissionConstants.ORGANIZATION_USER_ROLE_READ)
public List<UserRole> list(@PathVariable String organizationId) {
return organizationUserRoleService.list(organizationId);
}
@PostMapping("/add")
@Operation(summary = "添加组织用户组")
@RequiresPermissions(PermissionConstants.ORGANIZATION_USER_ROLE_READ_ADD)
public UserRole add(@Validated @RequestBody OrganizationUserRoleEditRequest request) {
UserRole userRole = new UserRole();
userRole.setCreateUser(SessionUtils.getUserId());
BeanUtils.copyBean(userRole, request);
return organizationUserRoleService.add(userRole);
}
@PostMapping("/update")
@Operation(summary = "修改组织用户组")
@RequiresPermissions(PermissionConstants.ORGANIZATION_USER_ROLE_READ_UPDATE)
public UserRole update(@Validated @RequestBody OrganizationUserRoleEditRequest request) {
UserRole userRole = new UserRole();
BeanUtils.copyBean(userRole, request);
return organizationUserRoleService.update(userRole);
}
@GetMapping("/delete/{id}")
@Operation(summary = "删除组织用户组")
@RequiresPermissions(PermissionConstants.ORGANIZATION_USER_ROLE_READ_DELETE)
public void delete(@PathVariable String id) {
organizationUserRoleService.delete(id);
}
@GetMapping("/permission/setting/{id}")
@Operation(summary = "获取组织用户组对应的权限配置")
@RequiresPermissions(PermissionConstants.ORGANIZATION_USER_ROLE_READ)
public List<PermissionDefinitionItem> getPermissionSetting(@PathVariable String id) {
return organizationUserRoleService.getPermissionSetting(id);
}
@PostMapping("/permission/update")
@Operation(summary = "编辑组织用户组对应的权限配置")
@RequiresPermissions(PermissionConstants.ORGANIZATION_USER_ROLE_READ_UPDATE)
public void updatePermissionSetting(@Validated @RequestBody PermissionSettingUpdateRequest request) {
organizationUserRoleService.updatePermissionSetting(request);
}
@PostMapping("/list-member")
@Operation(summary = "获取组织用户组-成员")
@RequiresPermissions(value = {PermissionConstants.ORGANIZATION_USER_ROLE_READ, PermissionConstants.SYSTEM_USER_READ})
public Pager<List<User>> listMember(@Validated @RequestBody OrganizationUserRoleMemberRequest request) {
Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize());
return PageUtils.setPageInfo(page, organizationUserRoleService.listMember(request));
}
@PostMapping("/add-member")
@Operation(summary = "添加组织用户组成员")
@RequiresPermissions(PermissionConstants.ORGANIZATION_USER_ROLE_READ_UPDATE)
public void addMember(@Validated @RequestBody OrganizationUserRoleMemberEditRequest request) {
organizationUserRoleService.addMember(request, SessionUtils.getUserId());
}
@PostMapping("/remove-member")
@Operation(summary = "删除组织用户组成员")
@RequiresPermissions(PermissionConstants.ORGANIZATION_USER_ROLE_READ_UPDATE)
public void removeMember(@Validated @RequestBody OrganizationUserRoleMemberEditRequest request) {
organizationUserRoleService.removeMember(request);
}
}

View File

@ -12,8 +12,11 @@ public enum SystemResultCode implements IResultCode {
*/ */
GLOBAL_USER_ROLE_PERMISSION(101001, "global_user_role_permission_error"), GLOBAL_USER_ROLE_PERMISSION(101001, "global_user_role_permission_error"),
GLOBAL_USER_ROLE_EXIST(101002, "global_user_role_exist_error"), GLOBAL_USER_ROLE_EXIST(101002, "global_user_role_exist_error"),
GLOBAL_USER_ROLE_RELATION_SYSTEM_PERMISSION(101003, "global_user_role_relation_system_permission_error") GLOBAL_USER_ROLE_RELATION_SYSTEM_PERMISSION(101003, "global_user_role_relation_system_permission_error"),
; /**
* 获取/编辑组织自定义用户组如果非组织自定义用户组会返回该响应码
*/
NO_ORG_USER_ROLE_PERMISSION(101007, "organization_user_role_permission_error");
private final int code; private final int code;
private final String message; private final String message;

View File

@ -1,9 +1,13 @@
package io.metersphere.system.mapper; package io.metersphere.system.mapper;
import io.metersphere.system.domain.User;
import io.metersphere.system.request.OrganizationUserRoleMemberRequest;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
public interface ExtUserRoleMapper { public interface ExtUserRoleMapper {
List<String> selectGlobalRoleList(@Param("roleIdList") List<String> roleIdList, @Param("isSystem") boolean isSystem); List<String> selectGlobalRoleList(@Param("roleIdList") List<String> roleIdList, @Param("isSystem") boolean isSystem);
List<User> listOrganizationRoleMember(@Param("request") OrganizationUserRoleMemberRequest request);
} }

View File

@ -11,4 +11,11 @@
AND type = 'SYSTEM' AND type = 'SYSTEM'
</if> </if>
</select> </select>
<select id="listOrganizationRoleMember" resultType="io.metersphere.system.domain.User">
select u.* from user_role_relation urr left join user u on urr.user_id = u.id
where urr.source_id = #{request.organizationId}
and urr.role_id = #{request.userRoleId}
and u.name like concat('%',#{request.userName},'%')
</select>
</mapper> </mapper>

View File

@ -0,0 +1,39 @@
package io.metersphere.system.request;
import io.metersphere.sdk.constants.UserRoleType;
import io.metersphere.sdk.valid.EnumValue;
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 java.io.Serializable;
@Data
public class OrganizationUserRoleEditRequest implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(title = "组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(title = "组名称", 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(title = "应用范围", 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;
@Schema(title = "所属类型 SYSTEM ORGANIZATION PROJECT", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{user_role.type.not_blank}", groups = {Created.class, Updated.class})
@EnumValue(enumClass = UserRoleType.class, groups = {Created.class, Updated.class})
@Size(min = 1, max = 20, message = "{user_role.type.length_range}", groups = {Created.class, Updated.class})
private String type;
}

View File

@ -0,0 +1,27 @@
package io.metersphere.system.request;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.io.Serializable;
@Data
public class OrganizationUserRoleMemberEditRequest implements Serializable {
@Schema(title = "组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(title = "组织ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{organization.id.not_blank}")
@Size(min = 1, max = 50, message = "{organization.id.length_range}")
private String organizationId;
@Schema(title = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{user.id.not_blank}")
@Size(min = 1, max = 50, message = "{user.id.length_range}")
private String userId;
}

View File

@ -0,0 +1,26 @@
package io.metersphere.system.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 = true)
public class OrganizationUserRoleMemberRequest extends BasePageRequest {
@Schema(title = "组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(title = "组织ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{organization.id.not_blank}")
@Size(min = 1, max = 50, message = "{organization.id.length_range}")
private String organizationId;
@Schema(title = "用户名")
private String userName;
}

View File

@ -1,55 +1,110 @@
package io.metersphere.system.service; package io.metersphere.system.service;
import io.metersphere.sdk.constants.InternalUserRole;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.*;
import io.metersphere.system.dto.OrganizationDTO; import io.metersphere.system.dto.OrganizationDTO;
import io.metersphere.system.dto.UserExtend; import io.metersphere.system.dto.UserExtend;
import io.metersphere.system.mapper.ExtOrganizationMapper;
import io.metersphere.system.mapper.OrganizationMapper;
import io.metersphere.system.mapper.UserMapper;
import io.metersphere.system.mapper.UserRoleRelationMapper;
import io.metersphere.system.request.OrganizationMemberRequest; import io.metersphere.system.request.OrganizationMemberRequest;
import io.metersphere.system.request.OrganizationRequest; import io.metersphere.system.request.OrganizationRequest;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.UUID;
/** /**
* @author song-cc-rock * @author song-cc-rock
* 组织功能(非XPACK) * 组织功能
*/ */
public interface OrganizationService {
/** @Service
* 获取组织列表 @Transactional(rollbackFor = Exception.class)
* @param organizationRequest 列表请求参数 public class OrganizationService{
* @return 列表数据
*/
List<OrganizationDTO> list(OrganizationRequest organizationRequest);
/** @Resource
* 获取系统下所有组织 OrganizationMapper organizationMapper;
* @return 列表数据 @Resource
*/ ExtOrganizationMapper extOrganizationMapper;
List<OrganizationDTO> listAll(); @Resource
UserRoleRelationMapper userRoleRelationMapper;
@Resource
UserMapper userMapper;
/** public List<OrganizationDTO> list(OrganizationRequest organizationRequest) {
* 获取默认组织信息 List<OrganizationDTO> organizationDTOS = extOrganizationMapper.list(organizationRequest);
* @return 默认组织信息 return buildOrgAdminInfo(organizationDTOS);
*/ }
OrganizationDTO getDefault();
public List<OrganizationDTO> listAll() {
/** return extOrganizationMapper.listAll();
* 获取组织成员列表 }
* @param organizationRequest 组织成员列表请求参数
* @return 组织成员列表 public OrganizationDTO getDefault() {
*/ OrganizationDTO organizationDTO = new OrganizationDTO();
List<UserExtend> listMember(OrganizationRequest organizationRequest); OrganizationExample example = new OrganizationExample();
example.createCriteria().andNumEqualTo(100001L);
/** List<Organization> organizations = organizationMapper.selectByExample(example);
* 添加组织成员 Organization organization = organizations.get(0);
* @param organizationMemberRequest 添加组织成员请求参数 BeanUtils.copyBean(organizationDTO, organization);
* @param createUserId 创建人ID return organizationDTO;
*/ }
void addMember(OrganizationMemberRequest organizationMemberRequest, String createUserId);
public List<UserExtend> listMember(OrganizationRequest organizationRequest) {
/** return extOrganizationMapper.listMember(organizationRequest);
* 移除组织成员 }
* @param organizationId 组织ID
* @param userId 成员ID public void addMember(OrganizationMemberRequest organizationMemberRequest, String createUserId) {
*/ Organization organization = organizationMapper.selectByPrimaryKey(organizationMemberRequest.getOrganizationId());
void removeMember(String organizationId, String userId); if (organization == null) {
throw new MSException(Translator.get("organization_not_exist"));
}
for (String userId : organizationMemberRequest.getMemberIds()) {
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setId(UUID.randomUUID().toString());
userRoleRelation.setUserId(userId);
userRoleRelation.setSourceId(organizationMemberRequest.getOrganizationId());
userRoleRelation.setRoleId(InternalUserRole.ORG_MEMBER.getValue());
userRoleRelation.setCreateTime(System.currentTimeMillis());
userRoleRelation.setCreateUser(createUserId);
userRoleRelationMapper.insertSelective(userRoleRelation);
}
}
public void removeMember(String organizationId, String userId) {
Organization organization = organizationMapper.selectByPrimaryKey(organizationId);
if (organization == null) {
throw new MSException(Translator.get("organization_not_exist"));
}
User user = userMapper.selectByPrimaryKey(userId);
if (user == null) {
throw new MSException(Translator.get("organization_member_not_exist"));
}
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andUserIdEqualTo(userId).andSourceIdEqualTo(organizationId);
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectByExample(example);
if (CollectionUtils.isEmpty(userRoleRelations)) {
throw new MSException(Translator.get("organization_member_not_exist"));
}
userRoleRelationMapper.deleteByExample(example);
}
private List<OrganizationDTO> buildOrgAdminInfo(List<OrganizationDTO> organizationDTOS) {
if (CollectionUtils.isEmpty(organizationDTOS)) {
return organizationDTOS;
}
organizationDTOS.forEach(organizationDTO -> {
List<User> orgAdminList = extOrganizationMapper.getOrgAdminList(organizationDTO.getId());
organizationDTO.setOrgAdmins(orgAdminList);
});
return organizationDTOS;
}
} }

View File

@ -1,114 +0,0 @@
package io.metersphere.system.service;
import io.metersphere.sdk.constants.InternalUserRole;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.*;
import io.metersphere.system.dto.OrganizationDTO;
import io.metersphere.system.dto.UserExtend;
import io.metersphere.system.mapper.ExtOrganizationMapper;
import io.metersphere.system.mapper.OrganizationMapper;
import io.metersphere.system.mapper.UserMapper;
import io.metersphere.system.mapper.UserRoleRelationMapper;
import io.metersphere.system.request.OrganizationMemberRequest;
import io.metersphere.system.request.OrganizationRequest;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
/**
* @author song-cc-rock
* 组织功能(非XPACK)
*/
@Service
public class OrganizationServiceImpl implements OrganizationService{
@Resource
OrganizationMapper organizationMapper;
@Resource
ExtOrganizationMapper extOrganizationMapper;
@Resource
UserRoleRelationMapper userRoleRelationMapper;
@Resource
UserMapper userMapper;
@Override
public List<OrganizationDTO> list(OrganizationRequest organizationRequest) {
List<OrganizationDTO> organizationDTOS = extOrganizationMapper.list(organizationRequest);
return buildOrgAdminInfo(organizationDTOS);
}
@Override
public List<OrganizationDTO> listAll() {
return extOrganizationMapper.listAll();
}
@Override
public OrganizationDTO getDefault() {
OrganizationDTO organizationDTO = new OrganizationDTO();
OrganizationExample example = new OrganizationExample();
example.createCriteria().andNumEqualTo(100001L);
List<Organization> organizations = organizationMapper.selectByExample(example);
Organization organization = organizations.get(0);
BeanUtils.copyBean(organizationDTO, organization);
return organizationDTO;
}
@Override
public List<UserExtend> listMember(OrganizationRequest organizationRequest) {
return extOrganizationMapper.listMember(organizationRequest);
}
@Override
public void addMember(OrganizationMemberRequest organizationMemberRequest, String createUserId) {
Organization organization = organizationMapper.selectByPrimaryKey(organizationMemberRequest.getOrganizationId());
if (organization == null) {
throw new MSException(Translator.get("organization_not_exist"));
}
for (String userId : organizationMemberRequest.getMemberIds()) {
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setId(UUID.randomUUID().toString());
userRoleRelation.setUserId(userId);
userRoleRelation.setSourceId(organizationMemberRequest.getOrganizationId());
userRoleRelation.setRoleId(InternalUserRole.ORG_MEMBER.getValue());
userRoleRelation.setCreateTime(System.currentTimeMillis());
userRoleRelation.setCreateUser(createUserId);
userRoleRelationMapper.insertSelective(userRoleRelation);
}
}
@Override
public void removeMember(String organizationId, String userId) {
Organization organization = organizationMapper.selectByPrimaryKey(organizationId);
if (organization == null) {
throw new MSException(Translator.get("organization_not_exist"));
}
User user = userMapper.selectByPrimaryKey(userId);
if (user == null) {
throw new MSException(Translator.get("organization_member_not_exist"));
}
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andUserIdEqualTo(userId).andSourceIdEqualTo(organizationId);
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectByExample(example);
if (CollectionUtils.isEmpty(userRoleRelations)) {
throw new MSException(Translator.get("organization_member_not_exist"));
}
userRoleRelationMapper.deleteByExample(example);
}
private List<OrganizationDTO> buildOrgAdminInfo(List<OrganizationDTO> organizationDTOS) {
if (CollectionUtils.isEmpty(organizationDTOS)) {
return organizationDTOS;
}
organizationDTOS.forEach(organizationDTO -> {
List<User> orgAdminList = extOrganizationMapper.getOrgAdminList(organizationDTO.getId());
organizationDTO.setOrgAdmins(orgAdminList);
});
return organizationDTOS;
}
}

View File

@ -0,0 +1,174 @@
package io.metersphere.system.service;
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.Translator;
import io.metersphere.system.domain.*;
import io.metersphere.system.mapper.*;
import io.metersphere.system.request.OrganizationUserRoleMemberEditRequest;
import io.metersphere.system.request.OrganizationUserRoleMemberRequest;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static io.metersphere.system.controller.result.SystemResultCode.NO_ORG_USER_ROLE_PERMISSION;
/**
* 组织-用户组与权限
* @author song-cc-rock
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class OrganizationUserRoleService extends BaseUserRoleService {
public static final String ORGANIZATION_ROLE_TYPE = "ORGANIZATION";
public static final String ORGANIZATION_ROLE_SCOPE = "global";
@Resource
UserMapper userMapper;
@Resource
UserRoleMapper userRoleMapper;
@Resource
ExtUserRoleMapper extUserRoleMapper;
@Resource
UserRoleRelationMapper userRoleRelationMapper;
@Resource
UserRolePermissionMapper userRolePermissionMapper;
public List<UserRole> list(String organizationId) {
UserRoleExample example = new UserRoleExample();
example.createCriteria().andTypeEqualTo(ORGANIZATION_ROLE_TYPE)
.andScopeIdIn(Arrays.asList(organizationId, ORGANIZATION_ROLE_SCOPE));
return userRoleMapper.selectByExample(example);
}
@Override
public UserRole add(UserRole userRole) {
userRole.setInternal(false);
checkNewRoleExist(userRole);
return super.add(userRole);
}
@Override
public UserRole update(UserRole userRole) {
UserRole oldRole = get(userRole.getId());
// 非组织用户组不允许修改, 内置用户组不允许修改
checkOrgUserRole(oldRole);
checkInternalUserRole(oldRole);
checkNewRoleExist(userRole);
return super.update(userRole);
}
public void delete(String roleId) {
UserRole oldRole = get(roleId);
// 非组织用户组不允许删除, 内置用户组不允许删除
checkOrgUserRole(oldRole);
checkInternalUserRole(oldRole);
userRoleMapper.deleteByPrimaryKey(roleId);
UserRoleRelationExample relationExample = new UserRoleRelationExample();
relationExample.createCriteria().andRoleIdEqualTo(roleId);
userRoleRelationMapper.deleteByExample(relationExample);
UserRolePermissionExample permissionExample = new UserRolePermissionExample();
permissionExample.createCriteria().andRoleIdEqualTo(roleId);
userRolePermissionMapper.deleteByExample(permissionExample);
}
public List<User> listMember(OrganizationUserRoleMemberRequest request) {
return extUserRoleMapper.listOrganizationRoleMember(request);
}
public void addMember(OrganizationUserRoleMemberEditRequest request, String createUserId) {
checkMemberParam(request.getUserId(), request.getUserRoleId());
UserRoleRelation relation = new UserRoleRelation();
relation.setId(UUID.randomUUID().toString());
relation.setUserId(request.getUserId());
relation.setRoleId(request.getUserRoleId());
relation.setSourceId(request.getOrganizationId());
relation.setCreateTime(System.currentTimeMillis());
relation.setCreateUser(createUserId);
userRoleRelationMapper.insert(relation);
}
public void removeMember(OrganizationUserRoleMemberEditRequest request) {
checkMemberParam(request.getUserId(), request.getUserRoleId());
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andUserIdEqualTo(request.getUserId())
.andRoleIdEqualTo(request.getUserRoleId())
.andSourceIdEqualTo(request.getOrganizationId());
userRoleRelationMapper.deleteByExample(example);
}
public List<PermissionDefinitionItem> getPermissionSetting(String id) {
UserRole userRole = get(id);
checkOrgUserRole(userRole);
return getPermissionSetting(userRole);
}
@Override
public void updatePermissionSetting(PermissionSettingUpdateRequest request) {
UserRole userRole = get(request.getUserRoleId());
checkOrgUserRole(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 checkOrgUserRole(UserRole userRole) {
if (!ORGANIZATION_ROLE_TYPE.equals(userRole.getType())) {
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(), ORGANIZATION_ROLE_SCOPE))
.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

@ -5,7 +5,7 @@ import io.metersphere.system.request.OrganizationDeleteRequest;
/** /**
* @author song-cc-rock * @author song-cc-rock
* 组织功能(XPACK) * 组织功能
*/ */
public interface XpackOrganizationService { public interface XpackOrganizationService {

View File

@ -4,6 +4,32 @@
"name": "permission.system.name", "name": "permission.system.name",
"type": "SYSTEM", "type": "SYSTEM",
"children": [ "children": [
{
"id": "SYSTEM_ORGANIZATION_PROJECT",
"name": "permission.system_organization_project.name",
"permissions": [
{
"id": "SYSTEM_ORGANIZATION_PROJECT:READ",
"name": "permission.system_organization_project.read"
},
{
"id": "SYSTEM_ORGANIZATION_PROJECT:READ+ADD",
"name": "permission.system_organization_project.add"
},
{
"id": "SYSTEM_ORGANIZATION_PROJECT:READ+UPDATE",
"name": "permission.system_organization_project.update"
},
{
"id": "SYSTEM_ORGANIZATION_PROJECT:READ+DELETE",
"name": "permission.system_organization_project.delete"
},
{
"id": "SYSTEM_ORGANIZATION_PROJECT:READ+RECOVER",
"name": "permission.system_organization_project.recover"
}
]
},
{ {
"id": "SYSTEM_USER_ROLE", "id": "SYSTEM_USER_ROLE",
"name": "permission.system_user_role.name", "name": "permission.system_user_role.name",
@ -49,5 +75,34 @@
] ]
} }
] ]
},
{
"id": "ORGANIZATION",
"name": "permission.organization.name",
"type": "ORGANIZATION",
"children": [
{
"id": "ORGANIZATION_USER_ROLE",
"name": "permission.organization_user_role.name",
"permissions": [
{
"id": "ORGANIZATION_USER_ROLE:READ",
"name": "permission.organization_user_role.read"
},
{
"id": "ORGANIZATION_USER_ROLE:READ+ADD",
"name": "permission.organization_user_role.add"
},
{
"id": "ORGANIZATION_USER_ROLE:READ+UPDATE",
"name": "permission.organization_user_role.update"
},
{
"id": "ORGANIZATION_USER_ROLE:READ+DELETE",
"name": "permission.organization_user_role.delete"
}
]
}
]
} }
] ]

View File

@ -112,7 +112,6 @@ public class OrganizationControllerTests extends BaseTest{
this.requestPost(ORGANIZATION_LIST, organizationRequest, status().isBadRequest()); this.requestPost(ORGANIZATION_LIST, organizationRequest, status().isBadRequest());
} }
@Test @Test
@Order(2) @Order(2)
public void testListAllOrganizationSuccess() throws Exception { public void testListAllOrganizationSuccess() throws Exception {
@ -287,7 +286,7 @@ public class OrganizationControllerTests extends BaseTest{
@Test @Test
@Order(12) @Order(12)
public void testGetDefaultOrganizationSuccess() throws Exception { public void testGetDefaultOrganizationSuccess() throws Exception {
MvcResult mvcResult = this.responseGet(); MvcResult mvcResult = this.responseGet(OrganizationControllerTests.ORGANIZATION_DEFAULT);
// 获取返回值 // 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JsonUtils.parseObject(returnData, ResultHolder.class); ResultHolder resultHolder = JsonUtils.parseObject(returnData, ResultHolder.class);
@ -306,6 +305,8 @@ public class OrganizationControllerTests extends BaseTest{
this.requestPost(ORGANIZATION_DEFAULT, null, status().isMethodNotAllowed()); this.requestPost(ORGANIZATION_DEFAULT, null, status().isMethodNotAllowed());
} }
private void requestPost(String url, Object param, ResultMatcher resultMatcher) throws Exception { private void requestPost(String url, Object param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(url) mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId) .header(SessionConstants.HEADER_TOKEN, sessionId)
@ -336,8 +337,8 @@ public class OrganizationControllerTests extends BaseTest{
.andExpect(content().contentType(MediaType.APPLICATION_JSON)); .andExpect(content().contentType(MediaType.APPLICATION_JSON));
} }
private MvcResult responseGet() throws Exception { private MvcResult responseGet(String url) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.get(OrganizationControllerTests.ORGANIZATION_DEFAULT) return mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId) .header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken) .header(SessionConstants.CSRF_TOKEN, csrfToken)
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))

View File

@ -0,0 +1,403 @@
package io.metersphere.system.controller;
import base.BaseTest;
import io.metersphere.sdk.constants.InternalUserRole;
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 io.metersphere.system.request.OrganizationUserRoleMemberEditRequest;
import io.metersphere.system.request.OrganizationUserRoleMemberRequest;
import io.metersphere.utils.JsonUtils;
import jakarta.annotation.Resource;
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_ORG_USER_ROLE_PERMISSION;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class OrganizationUserRoleControllerTests extends BaseTest {
@Resource
private MockMvc mockMvc;
@Resource
private BaseUserRolePermissionService baseUserRolePermissionService;
public static final String ORGANIZATION_ROLE_TYPE = "ORGANIZATION";
public static final String ORGANIZATION_USER_ROLE_LIST = "/user/role/organization/list";
public static final String ORGANIZATION_USER_ROLE_ADD = "/user/role/organization/add";
public static final String ORGANIZATION_USER_ROLE_UPDATE = "/user/role/organization/update";
public static final String ORGANIZATION_USER_ROLE_DELETE = "/user/role/organization/delete";
public static final String ORGANIZATION_USER_ROLE_PERMISSION_SETTING = "/user/role/organization/permission/setting";
public static final String ORGANIZATION_USER_ROLE_PERMISSION_UPDATE = "/user/role/organization/permission/update";
public static final String ORGANIZATION_USER_ROLE_LIST_MEMBER = "/user/role/organization/list-member";
public static final String ORGANIZATION_USER_ROLE_ADD_MEMBER = "/user/role/organization/add-member";
public static final String ORGANIZATION_USER_ROLE_REMOVE_MEMBER = "/user/role/organization/remove-member";
@Test
@Order(0)
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "/dml/init_organization_user_role.sql")
public void testOrganizationUserRoleListSuccess() throws Exception {
String organizationId = "default-organization-2";
MvcResult mvcResult = this.responseGet(ORGANIZATION_USER_ROLE_LIST + "/" + organizationId);
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JsonUtils.parseObject(returnData, ResultHolder.class);
// 返回请求正常
Assertions.assertNotNull(resultHolder);
// 返回总条数是否为init_organization_user_role.sql中的数据总数
Assertions.assertEquals(4, JSON.parseArray(JSON.toJSONString(resultHolder.getData())).size());
}
@Test
@Order(1)
public void testOrganizationUserRoleAddSuccess() throws Exception {
OrganizationUserRoleEditRequest request = new OrganizationUserRoleEditRequest();
request.setName("default-org-role-4");
request.setType(ORGANIZATION_ROLE_TYPE);
request.setScopeId("default-organization-2");
this.requestPost(ORGANIZATION_USER_ROLE_ADD, request, status().isOk());
// 验证是否添加成功
String organizationId = "default-organization-2";
MvcResult mvcResult = this.responseGet(ORGANIZATION_USER_ROLE_LIST + "/" + organizationId);
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JsonUtils.parseObject(returnData, ResultHolder.class);
// 返回请求正常
Assertions.assertNotNull(resultHolder);
// 返回总条数是否为init_organization_user_role.sql中的数据总数
Assertions.assertEquals(5, JSON.parseArray(JSON.toJSONString(resultHolder.getData())).size());
}
@Test
@Order(2)
public void testOrganizationUserRoleAddError() throws Exception {
OrganizationUserRoleEditRequest request = new OrganizationUserRoleEditRequest();
// 同名用户组已存在
request.setName("default-org-role-2");
request.setType(ORGANIZATION_ROLE_TYPE);
request.setScopeId("default-organization-2");
this.requestPost(ORGANIZATION_USER_ROLE_ADD, request, status().is5xxServerError());
}
@Test
@Order(3)
public void testOrganizationUserRoleUpdateError() throws Exception {
OrganizationUserRoleEditRequest request = new OrganizationUserRoleEditRequest();
// 用户组不存在
request.setId("default-org-role-id-10");
this.requestPost(ORGANIZATION_USER_ROLE_UPDATE, request, status().is5xxServerError());
// 非组织下用户组异常
request = new OrganizationUserRoleEditRequest();
request.setId(InternalUserRole.ADMIN.getValue());
this.requestPost(ORGANIZATION_USER_ROLE_UPDATE, request).andExpect(jsonPath("$.code").value(NO_ORG_USER_ROLE_PERMISSION.getCode()));
// 非内置用户组异常
request = new OrganizationUserRoleEditRequest();
request.setId(InternalUserRole.ORG_ADMIN.getValue());
this.requestPost(ORGANIZATION_USER_ROLE_UPDATE, request).andExpect(jsonPath("$.code").value(INTERNAL_USER_ROLE_PERMISSION.getCode()));
// 用户组名称已存在
request = new OrganizationUserRoleEditRequest();
request.setId("default-org-role-id-2");
request.setName("组织管理员");
request.setType(ORGANIZATION_ROLE_TYPE);
request.setScopeId("default-organization-2");
this.requestPost(ORGANIZATION_USER_ROLE_UPDATE, request, status().is5xxServerError());
}
@Test
@Order(4)
public void testOrganizationUserRoleUpdateSuccess() throws Exception {
OrganizationUserRoleEditRequest request = new OrganizationUserRoleEditRequest();
request.setId("default-org-role-id-2");
request.setName("default-org-role-x");
request.setType(ORGANIZATION_ROLE_TYPE);
request.setScopeId("default-organization-2");
this.requestPost(ORGANIZATION_USER_ROLE_UPDATE, request, status().isOk());
// 验证是否修改成功
String organizationId = "default-organization-2";
MvcResult mvcResult = this.responseGet(ORGANIZATION_USER_ROLE_LIST + "/" + organizationId);
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JsonUtils.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-org-role-x".equals(userRole.getName())));
}
@Test
@Order(5)
public void testOrganizationUserRoleDeleteError() throws Exception {
// 用户组不存在
this.requestGet(ORGANIZATION_USER_ROLE_DELETE + "/default-org-role-id-10", status().is5xxServerError());
// 非组织下用户组异常
this.requestGet(ORGANIZATION_USER_ROLE_DELETE + "/" + InternalUserRole.ADMIN.getValue()).andExpect(jsonPath("$.code").value(NO_ORG_USER_ROLE_PERMISSION.getCode()));
// 非内置用户组异常
this.requestGet(ORGANIZATION_USER_ROLE_DELETE + "/" + InternalUserRole.ORG_ADMIN.getValue()).andExpect(jsonPath("$.code").value(INTERNAL_USER_ROLE_PERMISSION.getCode()));
}
@Test
@Order(6)
public void testOrganizationUserRoleDeleteSuccess() throws Exception {
this.requestGet(ORGANIZATION_USER_ROLE_DELETE + "/default-org-role-id-2", status().isOk());
}
@Test
@Order(7)
public void testOrganizationUserRolePermissionSettingSuccess() throws Exception {
MvcResult mvcResult = this.responseGet(ORGANIZATION_USER_ROLE_PERMISSION_SETTING + "/default-org-role-id-3");
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JsonUtils.parseObject(returnData, ResultHolder.class);
// 返回请求正常
Assertions.assertNotNull(resultHolder);
// 返回总条数是否为init_organization_user_role.sql中的数据总数
Assertions.assertEquals(1, JSON.parseArray(JSON.toJSONString(resultHolder.getData())).size());
}
@Test
@Order(8)
public void testOrganizationUserRolePermissionSettingError() throws Exception {
// 用户组不存在
this.requestGet(ORGANIZATION_USER_ROLE_PERMISSION_SETTING + "/default-org-role-id-10", status().is5xxServerError());
// 非组织下用户组异常
this.requestGet(ORGANIZATION_USER_ROLE_PERMISSION_SETTING + "/" + InternalUserRole.ADMIN.getValue())
.andExpect(jsonPath("$.code").value(NO_ORG_USER_ROLE_PERMISSION.getCode()));
}
@Test
@Order(9)
public void testOrganizationUserRolePermissionUpdateSuccess() throws Exception {
PermissionSettingUpdateRequest request = new PermissionSettingUpdateRequest();
request.setUserRoleId("default-org-role-id-3");
request.setPermissions(new ArrayList<>() {
{
// 取消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));
}
});
this.requestPost(ORGANIZATION_USER_ROLE_PERMISSION_UPDATE, request, status().isOk());
// 返回权限勾选ORGANIZATION_USER_ROLE:CREATE
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);
}
@Test
@Order(10)
public void testOrganizationUserRolePermissionUpdateError() throws Exception {
PermissionSettingUpdateRequest request = new PermissionSettingUpdateRequest();
request.setUserRoleId("default-org-role-id-10");
request.setPermissions(new ArrayList<>() {
{
// 取消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));
}
});
// 用户组不存在
this.requestPost(ORGANIZATION_USER_ROLE_PERMISSION_UPDATE, request, status().is5xxServerError());
// 非组织下用户组异常
request = new PermissionSettingUpdateRequest();
request.setUserRoleId(InternalUserRole.ADMIN.getValue());
request.setPermissions(new ArrayList<>() {
{
// 取消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));
}
});
this.requestPost(ORGANIZATION_USER_ROLE_PERMISSION_UPDATE, request)
.andExpect(jsonPath("$.code").value(NO_ORG_USER_ROLE_PERMISSION.getCode()));
// 内置用户组异常
request = new PermissionSettingUpdateRequest();
request.setUserRoleId(InternalUserRole.ORG_ADMIN.getValue());
request.setPermissions(new ArrayList<>() {
{
// 取消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));
}
});
this.requestPost(ORGANIZATION_USER_ROLE_PERMISSION_UPDATE, request)
.andExpect(jsonPath("$.code").value(INTERNAL_USER_ROLE_PERMISSION.getCode()));
}
@Test
@Order(11)
public void testOrganizationUserRoleListMemberSuccess() throws Exception {
OrganizationUserRoleMemberRequest request = new OrganizationUserRoleMemberRequest();
request.setOrganizationId("default-organization-2");
request.setUserRoleId("default-org-role-id-3");
request.setUserName("admin");
request.setCurrent(1);
request.setPageSize(10);
MvcResult mvcResult = this.responsePost(ORGANIZATION_USER_ROLE_LIST_MEMBER, request);
// 获取返回值
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JsonUtils.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());
// 返回值中取出第一条数据, 并判断是否包含关键字default
User user = JSON.parseArray(JSON.toJSONString(pageData.getList()), User.class).get(0);
Assertions.assertTrue(StringUtils.contains(user.getName(), request.getUserName())
|| StringUtils.contains(user.getId(), request.getUserName()));
}
@Test
@Order(12)
public void testOrganizationUserRoleListMemberError() throws Exception {
OrganizationUserRoleMemberRequest request = new OrganizationUserRoleMemberRequest();
request.setOrganizationId("default-organization-2");
request.setUserRoleId("default-org-role-id-3");
request.setCurrent(0);
request.setPageSize(10);
// 页码有误
this.requestPost(ORGANIZATION_USER_ROLE_LIST_MEMBER, request, status().isBadRequest());
request = new OrganizationUserRoleMemberRequest();
request.setOrganizationId("default-organization-2");
request.setUserRoleId("default-org-role-id-3");
request.setCurrent(1);
request.setPageSize(1);
// 页数有误
this.requestPost(ORGANIZATION_USER_ROLE_LIST_MEMBER, request, status().isBadRequest());
}
@Test
@Order(13)
public void testOrganizationUserRoleAddMemberSuccess() throws Exception {
OrganizationUserRoleMemberEditRequest request = new OrganizationUserRoleMemberEditRequest();
request.setOrganizationId("default-organization-2");
request.setUserRoleId("default-org-role-id-3");
request.setUserId("admin");
this.requestPost(ORGANIZATION_USER_ROLE_ADD_MEMBER, request, status().isOk());
}
@Test
@Order(14)
public void testOrganizationUserRoleAddMemberError() throws Exception {
OrganizationUserRoleMemberEditRequest request = new OrganizationUserRoleMemberEditRequest();
request.setOrganizationId("default-organization-2");
request.setUserId("admin-x");
request.setUserRoleId("default-org-role-id-3");
// 用户不存在
this.requestPost(ORGANIZATION_USER_ROLE_ADD_MEMBER, request, status().is5xxServerError());
request = new OrganizationUserRoleMemberEditRequest();
request.setOrganizationId("default-organization-2");
request.setUserId("admin");
request.setUserRoleId("default-org-role-id-x");
// 用户组不存在
this.requestPost(ORGANIZATION_USER_ROLE_ADD_MEMBER, request, status().is5xxServerError());
}
@Test
@Order(15)
public void testOrganizationUserRoleRemoveMemberSuccess() throws Exception {
OrganizationUserRoleMemberEditRequest request = new OrganizationUserRoleMemberEditRequest();
request.setOrganizationId("default-organization-2");
request.setUserRoleId("default-org-role-id-3");
request.setUserId("default-admin");
this.requestPost(ORGANIZATION_USER_ROLE_REMOVE_MEMBER, request, status().isOk());
}
@Test
@Order(16)
public void testOrganizationUserRoleRemoveMemberError() throws Exception {
OrganizationUserRoleMemberEditRequest request = new OrganizationUserRoleMemberEditRequest();
request.setOrganizationId("default-organization-2");
request.setUserId("admin-x");
request.setUserRoleId("default-org-role-id-3");
// 用户不存在
this.requestPost(ORGANIZATION_USER_ROLE_REMOVE_MEMBER, request, status().is5xxServerError());
request = new OrganizationUserRoleMemberEditRequest();
request.setOrganizationId("default-organization-2");
request.setUserId("admin");
request.setUserRoleId("default-org-role-id-x");
// 用户组不存在
this.requestPost(ORGANIZATION_USER_ROLE_REMOVE_MEMBER, request, status().is5xxServerError());
}
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).andDo(print())
.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()).andDo(print())
.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).andDo(print())
.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()).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andReturn();
}
}

View File

@ -0,0 +1,11 @@
# 组织用户组数据准备
INSERT INTO user_role(id, name, description, internal, type, create_time, update_time, create_user, scope_id) VALUE
('default-org-role-id-1', 'default-org-role-1', 'XXX', FALSE, 'ORGANIZATION', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'default-organization-2');
INSERT INTO user_role(id, name, description, internal, type, create_time, update_time, create_user, scope_id) VALUE
('default-org-role-id-2', 'default-org-role-2', 'XXX', FALSE, 'ORGANIZATION', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'default-organization-2');
INSERT INTO user_role(id, name, description, internal, type, create_time, update_time, create_user, scope_id) VALUE
('default-org-role-id-3', 'default-org-role-3', 'XXX', FALSE, 'ORGANIZATION', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'default-organization-2');
INSERT INTO user_role_permission (id, role_id, permission_id) VALUE
(uuid(), 'default-org-role-id-3', 'ORGANIZATION_USER_ROLE:READ');
INSERT INTO user_role_relation (id, user_id, role_id, source_id, create_time, create_user) VALUE
(UUID(), 'default-admin', 'default-org-role-id-3', 'default-organization-2', UNIX_TIMESTAMP() * 1000, 'admin');