feat: add org member

This commit is contained in:
guoyuqi 2023-07-21 18:35:04 +08:00 committed by 刘瑞斌
parent ae829e6e4e
commit 13bfa7e5bc
12 changed files with 823 additions and 74 deletions

View File

@ -34,6 +34,13 @@ public class PermissionConstants {
public static final String ORGANIZATION_USER_ROLE_READ_DELETE = "ORGANIZATION_USER_ROLE:READ+DELETE";
/*------ end: ORGANIZATION_USER_ROLE ------*/
/*------ start: ORGANIZATION_MEMBER ------*/
public static final String ORGANIZATION_MEMBER_READ = "ORGANIZATION_MEMBER:READ";
public static final String ORGANIZATION_MEMBER_ADD = "ORGANIZATION_MEMBER:READ+ADD";
public static final String ORGANIZATION_MEMBER_UPDATE = "ORGANIZATION_MEMBER:READ+UPDATE";
public static final String ORGANIZATION_MEMBER_DELETE = "ORGANIZATION_MEMBER:READ+DELETE";
/*------ end: ORGANIZATION_MEMBER ------*/
/*------ start: SYSTEM_PLUGIN ------*/
public static final String SYSTEM_PLUGIN_READ = "SYSTEM_PLUGIN_READ:READ";
public static final String SYSTEM_PLUGIN_ADD = "SYSTEM_PLUGIN_READ:READ+ADD";

View File

@ -1,9 +1,29 @@
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.log.annotation.Log;
import io.metersphere.sdk.log.constants.OperationLogType;
import io.metersphere.sdk.util.PageUtils;
import io.metersphere.sdk.util.Pager;
import io.metersphere.sdk.util.SessionUtils;
import io.metersphere.system.dto.OrgUserExtend;
import io.metersphere.system.request.*;
import io.metersphere.system.service.OrganizationService;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author song-cc-rock
*/
@ -12,4 +32,55 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/organization")
public class OrganizationController {
@Resource
private OrganizationService organizationService;
@PostMapping("/member/list")
@Operation(summary = "组织级别获取组织成员")
@RequiresPermissions(value = {PermissionConstants.ORGANIZATION_MEMBER_READ, PermissionConstants.SYSTEM_USER_READ})
public Pager<List<OrgUserExtend>> getMemberList(@Validated @RequestBody OrganizationRequest organizationRequest) {
Page<Object> page = PageHelper.startPage(organizationRequest.getCurrent(), organizationRequest.getPageSize());
return PageUtils.setPageInfo(page, organizationService.getMemberListByOrg(organizationRequest));
}
@PostMapping("/add-member")
@Operation(summary = "添加组织成员")
@RequiresPermissions(PermissionConstants.ORGANIZATION_MEMBER_ADD)
public void addMemberByList(@Validated @RequestBody OrganizationMemberExtendRequest organizationMemberExtendRequest) {
organizationService.addMemberByOrg(organizationMemberExtendRequest, SessionUtils.getUserId());
}
@PostMapping("/role/update-member")
@Operation(summary = "添加组织成员至用户组")
@RequiresPermissions(PermissionConstants.ORGANIZATION_MEMBER_UPDATE)
public void updateMemberRole(@Validated @RequestBody OrganizationMemberExtendRequest organizationMemberExtendRequest) {
organizationService.updateMemberRole(organizationMemberExtendRequest, SessionUtils.getUserId());
}
@PostMapping("/update-member")
@Operation(summary = "更新用户组")
@RequiresPermissions(PermissionConstants.ORGANIZATION_MEMBER_UPDATE)
public void updateMember(@Validated @RequestBody OrganizationMemberExtendRequest organizationMemberExtendRequest) {
organizationService.updateMember(organizationMemberExtendRequest, SessionUtils.getUserId());
}
@PostMapping("/project/add-member")
@Operation(summary = "添加组织成员至项目")
@RequiresPermissions(PermissionConstants.ORGANIZATION_MEMBER_UPDATE)
public void addMemberToProject(@Validated @RequestBody OrgMemberExtendProjectRequest orgMemberExtendProjectRequest) {
organizationService.addMemberToProject(orgMemberExtendProjectRequest, SessionUtils.getUserId());
}
@GetMapping("/remove-member/{organizationId}/{userId}")
@Operation(summary = "删除组织成员")
@Parameters({
@Parameter(name = "organizationId", description = "组织ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED)),
@Parameter(name = "userId", description = "成员ID", schema = @Schema(requiredMode = Schema.RequiredMode.REQUIRED))
})
@RequiresPermissions(PermissionConstants.ORGANIZATION_MEMBER_DELETE)
@Log(type = OperationLogType.DELETE, expression = "#msClass.batchDelLog(#organizationId, #userId)", msClass = OrganizationService.class)
public void removeMember(@PathVariable String organizationId, @PathVariable String userId) {
organizationService.removeMember(organizationId, userId);
}
}

View File

@ -62,14 +62,14 @@ public class SystemOrganizationController {
public Pager<List<UserExtend>> listMember(@Validated @RequestBody OrganizationRequest request) {
Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize(),
StringUtils.isNotBlank(request.getSortString()) ? request.getSortString() : "create_time desc");
return PageUtils.setPageInfo(page, organizationService.listMember(request));
return PageUtils.setPageInfo(page, organizationService.getMemberListBySystem(request));
}
@PostMapping("/add-member")
@Operation(summary = "添加组织成员")
@RequiresPermissions(PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ_UPDATE)
public void addMember(@Validated @RequestBody OrganizationMemberRequest request) {
organizationService.addMember(request, SessionUtils.getUserId());
organizationService.addMemberBySystem(request, SessionUtils.getUserId());
}
@GetMapping("/remove-member/{organizationId}/{userId}")

View File

@ -1,6 +1,7 @@
package io.metersphere.system.mapper;
import io.metersphere.system.domain.User;
import io.metersphere.system.dto.OrgUserExtend;
import io.metersphere.system.dto.OrganizationDTO;
import io.metersphere.system.dto.OrganizationProjectOptionsDto;
import io.metersphere.system.dto.UserExtend;
@ -54,6 +55,14 @@ public interface ExtOrganizationMapper {
*/
List<UserExtend> listMember(@Param("request") OrganizationRequest request);
/**
* 获取组织成员列表(角色)
* @param request 组织成员列表请求参数
* @return 组织成员列表数据
*/
List<OrgUserExtend> listMemberByOrg(@Param("request") OrganizationRequest request);
/**
* 获取组织管理员
* @param orgId 组织ID

View File

@ -48,6 +48,27 @@
group by temp.id
</select>
<select id="listMemberByOrg" resultType="io.metersphere.system.dto.OrgUserExtend">
select temp.*
from (
select u.*, urr.role_id
from user_role_relation urr
join `user` u on urr.user_id = u.id
<where>
<if test="request.organizationId != null">
urr.source_id = #{request.organizationId}
</if>
<if test="request.keyword != null">
and (u.name like CONCAT('%', #{request.keyword},'%')
or u.email like CONCAT('%', #{request.keyword},'%')
or u.phone like CONCAT('%', #{request.keyword},'%'))
</if>
</where>
order by u.update_time desc
) temp
group by temp.id
</select>
<select id="getOrgAdminList" resultType="io.metersphere.system.domain.User">
select u.*
from user_role_relation urr

View File

@ -1,26 +1,42 @@
package io.metersphere.system.service;
import io.metersphere.constants.HttpMethodConstants;
import io.metersphere.project.domain.Project;
import io.metersphere.project.domain.ProjectExample;
import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.sdk.constants.InternalUserRole;
import io.metersphere.sdk.dto.LogDTO;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.log.constants.OperationLogModule;
import io.metersphere.sdk.log.constants.OperationLogType;
import io.metersphere.sdk.log.service.OperationLogService;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.*;
import io.metersphere.system.dto.OrgUserExtend;
import io.metersphere.system.dto.OrganizationDTO;
import io.metersphere.system.dto.OrganizationProjectOptionsDto;
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.mapper.*;
import io.metersphere.system.request.OrgMemberExtendProjectRequest;
import io.metersphere.system.request.OrganizationMemberExtendRequest;
import io.metersphere.system.request.OrganizationMemberRequest;
import io.metersphere.system.request.OrganizationRequest;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.UUID;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author song-cc-rock
@ -39,9 +55,17 @@ public class OrganizationService{
UserRoleRelationMapper userRoleRelationMapper;
@Resource
UserMapper userMapper;
@Resource
private SqlSessionFactory sqlSessionFactory;
@Resource
private UserRoleMapper userRoleMapper;
@Resource
private OperationLogService operationLogService;
@Resource
private ProjectMapper projectMapper;
public List<OrganizationDTO> list(OrganizationRequest request) {
List<OrganizationDTO> organizationDTOS = extOrganizationMapper.list(request);
public List<OrganizationDTO> list(OrganizationRequest organizationRequest) {
List<OrganizationDTO> organizationDTOS = extOrganizationMapper.list(organizationRequest);
return buildOrgAdminInfo(organizationDTOS);
}
@ -59,36 +83,108 @@ public class OrganizationService{
return organizationDTO;
}
public List<UserExtend> listMember(OrganizationRequest request) {
public List<UserExtend> getMemberListBySystem(OrganizationRequest request) {
return extOrganizationMapper.listMember(request);
}
public void addMember(OrganizationMemberRequest request, String createUserId) {
Organization organization = organizationMapper.selectByPrimaryKey(request.getOrganizationId());
if (organization == null) {
throw new MSException(Translator.get("organization_not_exist"));
public void addMemberBySystem(OrganizationMemberRequest organizationMemberRequest, String createUserId) {
String organizationId = organizationMemberRequest.getOrganizationId();
checkOrgExist(organizationId);
Map<String, User> userMap = checkUserExist(organizationMemberRequest.getMemberIds());
for (String userId : organizationMemberRequest.getMemberIds()) {
if (userMap.get(userId) == null) {
throw new MSException("id:" + userId + Translator.get("user.not.exist"));
}
//过滤已存在的关系
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andSourceIdEqualTo(organizationId).andUserIdEqualTo(userId).andRoleIdEqualTo(InternalUserRole.ORG_MEMBER.getValue());
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectByExample(example);
if (CollectionUtils.isNotEmpty(userRoleRelations)) {
continue;
}
for (String userId : request.getMemberIds()) {
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setId(UUID.randomUUID().toString());
userRoleRelation.setUserId(userId);
userRoleRelation.setSourceId(request.getOrganizationId());
userRoleRelation.setSourceId(organizationId);
userRoleRelation.setRoleId(InternalUserRole.ORG_MEMBER.getValue());
userRoleRelation.setCreateTime(System.currentTimeMillis());
userRoleRelation.setCreateUser(createUserId);
userRoleRelationMapper.insertSelective(userRoleRelation);
userRoleRelationMapper.insert(userRoleRelation);
}
}
public List<OrgUserExtend> getMemberListByOrg(OrganizationRequest organizationRequest) {
//根据组织ID获取所有组织用户关系表
String organizationId = organizationRequest.getOrganizationId();
List<OrgUserExtend> orgUserExtends = extOrganizationMapper.listMemberByOrg(organizationRequest);
if (CollectionUtils.isEmpty(orgUserExtends)) {
return new ArrayList<>();
}
Map<String, OrgUserExtend> userMap = orgUserExtends.stream().collect(Collectors.toMap(OrgUserExtend::getId, user -> user));
ProjectExample projectExample = new ProjectExample();
projectExample.createCriteria().andOrganizationIdEqualTo(organizationId);
List<Project> projectsList = projectMapper.selectByExample(projectExample);
List<String> projectIdList = projectsList.stream().map(Project::getId).toList();
Map<String, String> projectIdNameMap = projectsList.stream().collect(Collectors.toMap(Project::getId, Project::getName));
//根据用户id获取所有与该用户有关的当前组织以及组织下的项目关系表
UserRoleRelationExample userRoleRelationExample = new UserRoleRelationExample();
List<String> sourceIds = new ArrayList<>(projectIdList);
sourceIds.add(organizationId);
userRoleRelationExample.createCriteria().andUserIdIn(new ArrayList<>(userMap.keySet())).andSourceIdIn(sourceIds);
List<UserRoleRelation> userRoleRelationsByUsers = userRoleRelationMapper.selectByExample(userRoleRelationExample);
//根据关系表查询出用户的关联组织和用户组
Map<String, Map<String, String>> userIdprojectIdMap = new HashMap<>();
Map<String, Set<String>> userIdRoleIdMap = new HashMap<>();
for (UserRoleRelation userRoleRelationsByUser : userRoleRelationsByUsers) {
String projectId = userRoleRelationsByUser.getSourceId();
String roleId = userRoleRelationsByUser.getRoleId();
String userId = userRoleRelationsByUser.getUserId();
Map<String, String> pIdNameMap = userIdprojectIdMap.get(projectId);
if (pIdNameMap == null || MapUtils.isEmpty(pIdNameMap)) {
pIdNameMap = new HashMap<>();
}
String projectName = projectIdNameMap.get(projectId);
if (StringUtils.isNotBlank(projectName)) {
pIdNameMap.put(projectId, projectName);
}
userIdprojectIdMap.put(userId, pIdNameMap);
Set<String> roleIds = userIdRoleIdMap.get(userId);
if (roleIds == null || CollectionUtils.isEmpty(roleIds)) {
roleIds = new HashSet<>();
}
roleIds.add(roleId);
userIdRoleIdMap.put(userId, roleIds);
}
for (OrgUserExtend orgUserExtend : orgUserExtends) {
Map<String, String> pIdNameMap = userIdprojectIdMap.get(orgUserExtend.getId());
if (MapUtils.isNotEmpty(pIdNameMap)) {
//移除当前组织id
orgUserExtend.setProjectIdNameMap(projectIdNameMap);
}
Set<String> userRoleIds = userIdRoleIdMap.get(orgUserExtend.getId());
if (CollectionUtils.isNotEmpty(userRoleIds)) {
UserRoleExample userRoleExample = new UserRoleExample();
userRoleExample.createCriteria().andIdIn(new ArrayList<>(userRoleIds));
List<UserRole> userRoles = userRoleMapper.selectByExample(userRoleExample);
Map<String, String> userRoleIdNameMap = userRoles.stream().collect(Collectors.toMap(UserRole::getId, UserRole::getName));
orgUserExtend.setUserRoleIdNameMap(userRoleIdNameMap);
}
}
return orgUserExtends;
}
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"));
checkOrgExist(organizationId);
//删除组织下项目与成员的关系
List<String> projectIds = getProjectIds(organizationId);
if (CollectionUtils.isNotEmpty(projectIds)) {
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andUserIdEqualTo(userId).andSourceIdIn(projectIds);
userRoleRelationMapper.deleteByExample(example);
}
//删除组织与成员的关系
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andUserIdEqualTo(userId).andSourceIdEqualTo(organizationId);
userRoleRelationMapper.deleteByExample(example);
@ -105,8 +201,277 @@ public class OrganizationService{
return organizationDTOS;
}
public List<OrganizationProjectOptionsDto> getOrganizationOptions() {
return extOrganizationMapper.selectOrganizationOptions();
}
public void addMemberByOrg(OrganizationMemberExtendRequest organizationMemberExtendRequest, String createUserId) {
checkOrgExist(organizationMemberExtendRequest.getOrganizationId());
Map<String, User> userMap = checkUserExist(organizationMemberExtendRequest.getMemberIds());
Map<String, UserRole> userRoleMap = checkUseRoleExist(organizationMemberExtendRequest.getUserRoleIds());
setRelationByMemberAndGroupIds(organizationMemberExtendRequest, createUserId, userMap, userRoleMap, true);
}
private Map<String, UserRole> checkUseRoleExist(List<String> userRoleIds) {
if (CollectionUtils.isEmpty(userRoleIds)) {
throw new MSException(Translator.get("user_role_not_exist"));
}
UserRoleExample userRoleExample = new UserRoleExample();
userRoleExample.createCriteria().andIdIn(userRoleIds).andTypeEqualTo("ORGANIZATION");
List<UserRole> userRoles = userRoleMapper.selectByExample(userRoleExample);
if (CollectionUtils.isEmpty(userRoles)) {
throw new MSException(Translator.get("user_role_not_exist"));
}
return userRoles.stream().collect(Collectors.toMap(UserRole::getId, user -> user));
}
private Map<String, User> checkUserExist(List<String> memberIds) {
if (CollectionUtils.isEmpty(memberIds)) {
throw new MSException(Translator.get("user.not.exist"));
}
UserExample userExample = new UserExample();
userExample.createCriteria().andIdIn(memberIds);
List<User> users = userMapper.selectByExample(userExample);
if (CollectionUtils.isEmpty(users)) {
throw new MSException(Translator.get("user.not.exist"));
}
return users.stream().collect(Collectors.toMap(User::getId, user -> user));
}
private void setRelationByMemberAndGroupIds(OrganizationMemberExtendRequest organizationMemberExtendRequest, String createUserId, Map<String, User> userMap, Map<String, UserRole> userRoleMap, boolean add) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserRoleRelationMapper userRoleRelationMapper = sqlSession.getMapper(UserRoleRelationMapper.class);
List<LogDTO> logDTOList = new ArrayList<>();
String organizationId = organizationMemberExtendRequest.getOrganizationId();
organizationMemberExtendRequest.getMemberIds().forEach(memberId -> {
if (userMap.get(memberId) == null) {
throw new MSException("id:" + memberId + Translator.get("user.not.exist"));
}
organizationMemberExtendRequest.getUserRoleIds().forEach(userGroupId -> {
if (userRoleMap.get(userGroupId) != null) {
//过滤已存在的关系
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andSourceIdEqualTo(organizationId).andUserIdEqualTo(memberId).andRoleIdEqualTo(userGroupId);
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectByExample(example);
if (CollectionUtils.isEmpty(userRoleRelations)) {
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setId(UUID.randomUUID().toString());
userRoleRelation.setUserId(memberId);
userRoleRelation.setSourceId(organizationId);
userRoleRelation.setRoleId(userGroupId);
userRoleRelation.setCreateTime(System.currentTimeMillis());
userRoleRelation.setCreateUser(createUserId);
userRoleRelationMapper.insert(userRoleRelation);
//add Log
String path = add ? "/organization/add-member" : "/organization/role/update-member";
setLog(organizationId, "system", path, OperationLogModule.ORGANIZATION_MEMBER, "成员", logDTOList, memberId, userRoleRelation, add);
}
}
});
});
sqlSession.flushStatements();
SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);
//写入操作日志
operationLogService.batchAdd(logDTOList);
}
private static void setLog(String organizationId, String projectId, String path, String module, String content, List<LogDTO> logDTOList, String memberId, Object originalValue, boolean add) {
String type = add ? OperationLogType.ADD.name() : OperationLogType.UPDATE.name();
LogDTO dto = new LogDTO(
projectId,
organizationId,
memberId,
null,
type,
module,
content);
dto.setPath(path);
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(originalValue));
logDTOList.add(dto);
}
public void updateMemberRole(OrganizationMemberExtendRequest organizationMemberExtendRequest, String userId) {
String organizationId = organizationMemberExtendRequest.getOrganizationId();
checkOrgExist(organizationId);
Map<String, User> userMap = checkUserExist(organizationMemberExtendRequest.getMemberIds());
Map<String, UserRole> userRoleMap = checkUseRoleExist(organizationMemberExtendRequest.getUserRoleIds());
//在新增组织成员与用户组和组织的关系
setRelationByMemberAndGroupIds(organizationMemberExtendRequest, userId, userMap, userRoleMap, false);
}
private void checkOrgExist(String organizationId) {
Organization organization = organizationMapper.selectByPrimaryKey(organizationId);
if (organization == null) {
throw new MSException(Translator.get("organization_not_exist"));
}
}
public void addMemberToProject(OrgMemberExtendProjectRequest orgMemberExtendProjectRequest, String userId) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserRoleRelationMapper userRoleRelationMapper = sqlSession.getMapper(UserRoleRelationMapper.class);
List<LogDTO> logDTOList = new ArrayList<>();
//检查项目ID是否都是当前组织的项目不是过滤
List<String> projectIds = orgMemberExtendProjectRequest.getProjectIds();
ProjectExample projectExample = new ProjectExample();
projectExample.createCriteria().andIdIn(projectIds);
List<Project> projects = projectMapper.selectByExample(projectExample);
Map<String, String> projectIdOrgIdMap = projects.stream().collect(Collectors.toMap(Project::getId, Project::getOrganizationId));
//用户不在当前组织内过掉
Map<String, User> userMap = checkUserExist(orgMemberExtendProjectRequest.getMemberIds());
String requestOrganizationId = orgMemberExtendProjectRequest.getOrganizationId();
orgMemberExtendProjectRequest.getMemberIds().forEach(memberId -> {
if (userMap.get(memberId) == null) {
return;
}
UserRoleRelationExample orgExample = new UserRoleRelationExample();
orgExample.createCriteria().andSourceIdEqualTo(requestOrganizationId).andUserIdEqualTo(memberId);
List<UserRoleRelation> userOrgRoleRelations = userRoleRelationMapper.selectByExample(orgExample);
if (CollectionUtils.isEmpty(userOrgRoleRelations)) {
return;
}
projectIds.forEach(projectId -> {
String organizationId = projectIdOrgIdMap.get(projectId);
if (StringUtils.isBlank(organizationId)) {
return;
} else if (!StringUtils.equals(organizationId, requestOrganizationId)) {
return;
}
//过滤已存在的关系
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andSourceIdEqualTo(projectId).andUserIdEqualTo(memberId).andRoleIdEqualTo(InternalUserRole.PROJECT_MEMBER.getValue());
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectByExample(example);
if (CollectionUtils.isEmpty(userRoleRelations)) {
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setId(UUID.randomUUID().toString());
userRoleRelation.setUserId(memberId);
userRoleRelation.setSourceId(projectId);
userRoleRelation.setRoleId(InternalUserRole.PROJECT_MEMBER.getValue());
userRoleRelation.setCreateTime(System.currentTimeMillis());
userRoleRelation.setCreateUser(userId);
userRoleRelationMapper.insert(userRoleRelation);
//add Log
setLog(requestOrganizationId, projectId, "/organization/project/add-member", OperationLogModule.PROJECT_PROJECT_MEMBER, "", logDTOList, memberId, userRoleRelation, true);
}
});
});
sqlSession.flushStatements();
SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);
//写入操作日志
operationLogService.batchAdd(logDTOList);
}
/**
* 删除组织用户日志
*
* @return
*/
public List<LogDTO> batchDelLog(String organizationId, String userId) {
List<String> projectIds = getProjectIds(organizationId);
UserRoleRelationExample example = new UserRoleRelationExample();
if (CollectionUtils.isEmpty(projectIds)) {
return null;
}
example.createCriteria().andUserIdEqualTo(userId).andSourceIdIn(projectIds);
List<UserRoleRelation> userRoleWidthProjectRelations = userRoleRelationMapper.selectByExample(example);
example = new UserRoleRelationExample();
example.createCriteria().andUserIdEqualTo(userId).andSourceIdEqualTo(organizationId);
List<UserRoleRelation> userRoleWidthOrgRelations = userRoleRelationMapper.selectByExample(example);
List<LogDTO> dtoList = new ArrayList<>();
for (UserRoleRelation userRoleWidthProjectRelation : userRoleWidthProjectRelations) {
LogDTO dto = new LogDTO(
userRoleWidthProjectRelation.getSourceId(),
organizationId,
userRoleWidthProjectRelation.getId(),
userRoleWidthProjectRelation.getCreateUser(),
OperationLogType.DELETE.name(),
OperationLogModule.ORGANIZATION_MEMBER,
"成员");
dto.setPath("/organization/remove-member/{organizationId}/{userId}");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(userRoleWidthProjectRelation));
dtoList.add(dto);
}
for (UserRoleRelation userRoleWidthOrgRelation : userRoleWidthOrgRelations) {
LogDTO dto = new LogDTO(
"system",
organizationId,
userRoleWidthOrgRelation.getId(),
userRoleWidthOrgRelation.getCreateUser(),
OperationLogType.DELETE.name(),
OperationLogModule.ORGANIZATION_MEMBER,
"成员");
dto.setPath("/organization/remove-member/{organizationId}/{userId}");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(userRoleWidthOrgRelation));
dtoList.add(dto);
}
return dtoList;
}
private List<String> getProjectIds(String organizationId) {
ProjectExample projectExample = new ProjectExample();
projectExample.createCriteria().andOrganizationIdEqualTo(organizationId);
List<Project> projects = projectMapper.selectByExample(projectExample);
if (CollectionUtils.isNotEmpty(projects)) {
return projects.stream().map(Project::getId).toList();
} else {
return new ArrayList<>();
}
}
public void updateMember(OrganizationMemberExtendRequest organizationMemberExtendRequest, String createUserId) {
String organizationId = organizationMemberExtendRequest.getOrganizationId();
List<String> memberIds = organizationMemberExtendRequest.getMemberIds();
if(CollectionUtils.isEmpty(memberIds)) {
throw new MSException(Translator.get("user.not.exist"));
}
//校验组织是否存在
checkOrgExist(organizationId);
//校验成员是否是当前组织的成员
UserRoleRelationExample userRoleRelationExample = new UserRoleRelationExample();
userRoleRelationExample.createCriteria().andUserIdIn(memberIds).andSourceIdEqualTo(organizationId);
List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectByExample(userRoleRelationExample);
List<String> userIds = userRoleRelations.stream().map(UserRoleRelation::getUserId).distinct().collect(Collectors.toList());
Map<String, User> userMap = checkUserExist(userIds);
//删除旧的关系
userRoleRelationExample = new UserRoleRelationExample();
userRoleRelationExample.createCriteria().andUserIdIn(userIds).andSourceIdEqualTo(organizationId);
userRoleRelationMapper.deleteByExample(userRoleRelationExample);
//检查用户组是否是组织级别用户组
Map<String, UserRole> userRoleMap = checkUseRoleExist(organizationMemberExtendRequest.getUserRoleIds());
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserRoleRelationMapper userRoleRelationMapper = sqlSession.getMapper(UserRoleRelationMapper.class);
List<LogDTO> logDTOList = new ArrayList<>();
userIds.forEach(userId -> {
if (userMap.get(userId) == null) {
throw new MSException("id:" + userId + Translator.get("user.not.exist"));
}
organizationMemberExtendRequest.getUserRoleIds().forEach(userRoleId -> {
if (userRoleMap.get(userRoleId) == null) {
return;
}
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setId(UUID.randomUUID().toString());
userRoleRelation.setUserId(userId);
userRoleRelation.setSourceId(organizationId);
userRoleRelation.setRoleId(userRoleId);
userRoleRelation.setCreateTime(System.currentTimeMillis());
userRoleRelation.setCreateUser(createUserId);
userRoleRelationMapper.insert(userRoleRelation);
//add Log
String path = "/organization/update-member";
setLog(organizationId, "system", path, OperationLogModule.ORGANIZATION_MEMBER, "成员", logDTOList, userId, userRoleRelation, false);
});
});
sqlSession.flushStatements();
SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);
//写入操作日志
operationLogService.batchAdd(logDTOList);
}
}

View File

@ -122,6 +122,28 @@
"name": "permission.organization_user_role.delete"
}
]
},
{
"id": "ORGANIZATION_MEMBER",
"name": "permission.organization_member.name",
"permissions": [
{
"id": "ORGANIZATION_MEMBER:READ",
"name": "permission.organization_member.read"
},
{
"id": "ORGANIZATION_MEMBER:READ+ADD",
"name": "permission.organization_member.add"
},
{
"id": "ORGANIZATION_MEMBER:READ+UPDATE",
"name": "permission.organization_member.update"
},
{
"id": "ORGANIZATION_MEMBER:READ+DELETE",
"name": "permission.organization_member.delete"
}
]
}
]
}

View File

@ -2,18 +2,30 @@ package io.metersphere.system.controller;
import base.BaseTest;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.controller.handler.ResultHolder;
import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.Pager;
import io.metersphere.system.dto.OrgUserExtend;
import io.metersphere.system.request.*;
import io.metersphere.utils.JsonUtils;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.TestMethodOrder;
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.context.jdbc.SqlConfig;
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.Arrays;
import java.util.Collections;
import java.util.List;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -26,27 +38,259 @@ public class OrganizationControllerTests extends BaseTest{
@Resource
private MockMvc mockMvc;
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));
public static final String ORGANIZATION_LIST_ADD_MEMBER = "/organization/add-member";
public static final String ORGANIZATION_UPDATE_MEMBER_TO_ROLE = "/organization/role/update-member";
public static final String ORGANIZATION_UPDATE_MEMBER = "/organization/update-member";
public static final String ORGANIZATION_REMOVE_MEMBER = "/organization/remove-member";
public static final String ORGANIZATION_MEMBER_LIST = "/organization/member/list";
public static final String ORGANIZATION_PROJECT_ADD_MEMBER = "/organization/project/add-member";
@Test
@Order(0)
@Sql(scripts = {"/dml/init_sys_organization.sql"}, config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED))
public void addMemberByOrgSuccess() throws Exception {
OrganizationMemberExtendRequest organizationMemberRequest = new OrganizationMemberExtendRequest();
organizationMemberRequest.setOrganizationId("sys_default_organization_3");
organizationMemberRequest.setMemberIds(Arrays.asList("sys_default_user", "sys_default_user2"));
organizationMemberRequest.setUserRoleIds(Arrays.asList("sys_default_org_role_id_3", "sys_default_project_role_id_3"));
this.requestPost(ORGANIZATION_LIST_ADD_MEMBER, organizationMemberRequest, status().isOk());
// 批量添加成员成功后, 验证是否添加成功
OrganizationRequest organizationRequest = new OrganizationRequest();
organizationRequest.setCurrent(1);
organizationRequest.setPageSize(10);
organizationRequest.setKeyword("testUserOne");
organizationRequest.setOrganizationId("sys_default_organization_3");
MvcResult mvcResult = this.responsePost(organizationRequest);
// 获取返回值
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(), organizationRequest.getCurrent());
// 返回的数据量不超过规定要返回的数据量相同
Assertions.assertTrue(JSON.parseArray(JSON.toJSONString(pageData.getList())).size() <= organizationRequest.getPageSize());
// 返回值中取出第一条数据, 并判断是否包含关键字admin
OrgUserExtend orgUserExtend = JSON.parseArray(JSON.toJSONString(pageData.getList()), OrgUserExtend.class).get(0);
Assertions.assertTrue(StringUtils.contains(orgUserExtend.getName(), organizationRequest.getKeyword())
|| StringUtils.contains(orgUserExtend.getEmail(), organizationRequest.getKeyword())
|| StringUtils.contains(orgUserExtend.getPhone(), organizationRequest.getKeyword()));
}
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();
@Test
@Order(1)
public void addMemberByOrgError() throws Exception {
//组织ID正确
// 成员选择为空
addOrUpdateOrganizationMemberError(ORGANIZATION_LIST_ADD_MEMBER, "sys_default_organization_3", Collections.emptyList(), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
// 用户组不存在
addOrUpdateOrganizationMemberError(ORGANIZATION_LIST_ADD_MEMBER, "sys_default_organization_3", Arrays.asList("sys_default_user", "sys_default_user2"), Collections.emptyList(), status().isBadRequest());
//成员和用户组都为空
addOrUpdateOrganizationMemberError(ORGANIZATION_LIST_ADD_MEMBER, "sys_default_organization_3", Collections.emptyList(), Collections.emptyList(), status().isBadRequest());
// 组织不存在
// 成员选择为空
addOrUpdateOrganizationMemberError(ORGANIZATION_LIST_ADD_MEMBER, "default-organization-x", Collections.emptyList(), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
// 用户组不存在
addOrUpdateOrganizationMemberError(ORGANIZATION_LIST_ADD_MEMBER, "default-organization-x", Arrays.asList("sys_default_user", "sys_default_user2"), Collections.emptyList(), status().isBadRequest());
//成员和用户组都为空
addOrUpdateOrganizationMemberError(ORGANIZATION_LIST_ADD_MEMBER, "default-organization-x", Collections.emptyList(), Collections.emptyList(), status().isBadRequest());
//成员和用户组存在
addOrUpdateOrganizationMemberError(ORGANIZATION_LIST_ADD_MEMBER, "default-organization-x", Arrays.asList("sys_default_user", "sys_default_user2"), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().is5xxServerError());
//组织为空
addOrUpdateOrganizationMemberError(ORGANIZATION_LIST_ADD_MEMBER, null, Arrays.asList("sys_default_user", "sys_default_user2"), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
}
@Test
@Order(2)
public void updateOrgMemberSuccess() throws Exception {
OrganizationMemberExtendRequest organizationMemberRequest = new OrganizationMemberExtendRequest();
organizationMemberRequest.setOrganizationId("sys_default_organization_3");
organizationMemberRequest.setMemberIds(Arrays.asList("sys_default_user", "sys_default_user2"));
organizationMemberRequest.setUserRoleIds(List.of("sys_default_org_role_id_2"));
this.requestPost(ORGANIZATION_UPDATE_MEMBER, organizationMemberRequest, status().isOk());
// 批量添加成员成功后, 验证是否添加成功
listByKeyWord("testUserTwo","sys_default_organization_3", true, "sys_default_org_role_id_2");
}
@Test
@Order(3)
public void updateOrgMemberError() throws Exception {
//组织ID正确
// 成员选择为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, "sys_default_organization_3", Collections.emptyList(), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
// 成员不存在
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, "sys_default_organization_3", Arrays.asList("sys_default_user3", "sys_default_user4"), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().is5xxServerError());
// 用户组不存在
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, "sys_default_organization_3", Arrays.asList("sys_default_user", "sys_default_user2"), Collections.emptyList(), status().isBadRequest());
//成员和用户组都为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, "sys_default_organization_3", Collections.emptyList(), Collections.emptyList(), status().isBadRequest());
// 组织不存在
// 成员选择为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, "default-organization-x", Collections.emptyList(), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
// 用户组不存在
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, "default-organization-x", Arrays.asList("sys_default_user", "sys_default_user2"), Collections.emptyList(), status().isBadRequest());
//成员和用户组都为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, "default-organization-x", Collections.emptyList(), Collections.emptyList(), status().isBadRequest());
//成员和用户组存在
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, "default-organization-x", Arrays.asList("sys_default_user", "sys_default_user2"), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().is5xxServerError());
//组织为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER, null, Arrays.asList("sys_default_user", "sys_default_user2"), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
}
@Test
@Order(4)
public void updateOrgMemberToRoleSuccess() throws Exception {
OrganizationMemberExtendRequest organizationMemberRequest = new OrganizationMemberExtendRequest();
organizationMemberRequest.setOrganizationId("sys_default_organization_3");
organizationMemberRequest.setMemberIds(Arrays.asList("sys_default_user", "sys_default_user2"));
organizationMemberRequest.setUserRoleIds(List.of("sys_default_org_role_id_4"));
this.requestPost(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, organizationMemberRequest, status().isOk());
// 批量添加成员成功后, 验证是否添加成功
listByKeyWord("testUserTwo","sys_default_organization_3", true, "sys_default_org_role_id_4");
}
@Test
@Order(5)
public void updateOrgMemberToRoleError() throws Exception {
//组织ID正确
// 成员选择为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, "sys_default_organization_3", Collections.emptyList(), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
// 成员不存在
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, "sys_default_organization_3", Arrays.asList("sys_default_user3", "sys_default_user4"), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().is5xxServerError());
// 用户组不存在
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, "sys_default_organization_3", Arrays.asList("sys_default_user", "sys_default_user2"), Collections.emptyList(), status().isBadRequest());
//成员和用户组都为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, "sys_default_organization_3", Collections.emptyList(), Collections.emptyList(), status().isBadRequest());
// 组织不存在
// 成员选择为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, "default-organization-x", Collections.emptyList(), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
// 用户组不存在
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, "default-organization-x", Arrays.asList("sys_default_user", "sys_default_user2"), Collections.emptyList(), status().isBadRequest());
//成员和用户组都为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, "default-organization-x", Collections.emptyList(), Collections.emptyList(), status().isBadRequest());
//成员和用户组存在
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, "default-organization-x", Arrays.asList("sys_default_user", "sys_default_user2"), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().is5xxServerError());
//组织为空
addOrUpdateOrganizationMemberError(ORGANIZATION_UPDATE_MEMBER_TO_ROLE, null, Arrays.asList("sys_default_user", "sys_default_user2"), Arrays.asList("default-org-role-id-2", "default-org-role-id-3"), status().isBadRequest());
}
@Test
@Order(6)
public void getOrgMemberListSuccess() throws Exception {
listByKeyWord("testUserOne","sys_default_organization_3", false ,null);
}
@Test
@Order(7)
public void getOrgMemberListError() throws Exception {
// 页码有误
OrganizationRequest organizationRequest = new OrganizationRequest();
organizationRequest.setCurrent(0);
organizationRequest.setPageSize(10);
organizationRequest.setKeyword("sys_default_user");
organizationRequest.setOrganizationId("sys_default_organization_3");
this.requestPost(ORGANIZATION_MEMBER_LIST, organizationRequest, status().isBadRequest());
// 页数有误
organizationRequest = new OrganizationRequest();
organizationRequest.setCurrent(1);
organizationRequest.setPageSize(1);
organizationRequest.setKeyword("sys_default_user");
organizationRequest.setOrganizationId("sys_default_organization_3");
this.requestPost(ORGANIZATION_MEMBER_LIST, organizationRequest, status().isBadRequest());
}
@Test
@Order(8)
@Sql(scripts = {"/dml/init_sys_org_project.sql"}, config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED))
public void addOrgMemberToProjectSuccess() throws Exception {
OrgMemberExtendProjectRequest organizationMemberRequest = new OrgMemberExtendProjectRequest();
organizationMemberRequest.setOrganizationId("sys_default_organization_3");
organizationMemberRequest.setMemberIds(Arrays.asList("sys_default_user", "test_user_one"));
organizationMemberRequest.setProjectIds(Arrays.asList("sys_org_projectId", "sys_org_projectId1"));
this.requestPost(ORGANIZATION_PROJECT_ADD_MEMBER, organizationMemberRequest, status().isOk());
// 批量添加成员成功后, 验证是否添加成功
listByKeyWord("testUserOne","sys_default_organization_3", false,null);
}
@Test
@Order(9)
public void addOrgMemberToProjectError() throws Exception {
// 成员选择为空
addOrUpdateOrganizationProjectMemberError(ORGANIZATION_PROJECT_ADD_MEMBER, "sys_default_organization_3", Collections.emptyList(), Arrays.asList("projectId1", "projectId2"), status().isBadRequest());
// 项目集合不存在
addOrUpdateOrganizationProjectMemberError(ORGANIZATION_PROJECT_ADD_MEMBER, "sys_default_organization_3", Arrays.asList("sys_default_user", "sys_default_user2"), Collections.emptyList(), status().isBadRequest());
//成员和项目集合都为空
addOrUpdateOrganizationProjectMemberError(ORGANIZATION_PROJECT_ADD_MEMBER, "sys_default_organization_3", Collections.emptyList(), Collections.emptyList(), status().isBadRequest());
}
@Test
@Order(10)
public void removeOrgMemberSuccess() throws Exception {
this.requestGet(ORGANIZATION_REMOVE_MEMBER + "/sys_default_organization_3/sys_default_user", status().isOk());
}
@Test
@Order(11)
public void removeOrgMemberError() throws Exception {
// 项目不存在
this.requestGet(ORGANIZATION_REMOVE_MEMBER + "/default-organization-x/admin-x", status().is5xxServerError());
}
private void listByKeyWord(String keyWord,String orgId,boolean compare, String userRoleId) throws Exception {
OrganizationRequest organizationRequest = new OrganizationRequest();
organizationRequest.setCurrent(1);
organizationRequest.setPageSize(10);
organizationRequest.setKeyword(keyWord);
organizationRequest.setOrganizationId(orgId);
MvcResult mvcResult = this.responsePost(organizationRequest);
// 获取返回值
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(), organizationRequest.getCurrent());
// 返回的数据量不超过规定要返回的数据量相同
Assertions.assertTrue(JSON.parseArray(JSON.toJSONString(pageData.getList())).size() <= organizationRequest.getPageSize());
// 返回值中取出第一条数据, 并判断是否包含关键字admin
OrgUserExtend orgUserExtend = JSON.parseArray(JSON.toJSONString(pageData.getList()), OrgUserExtend.class).get(0);
Assertions.assertTrue(StringUtils.contains(orgUserExtend.getName(), organizationRequest.getKeyword())
|| StringUtils.contains(orgUserExtend.getEmail(), organizationRequest.getKeyword())
|| StringUtils.contains(orgUserExtend.getPhone(), organizationRequest.getKeyword()));
if (compare) {
Assertions.assertNotNull(orgUserExtend.getUserRoleIdNameMap().get(userRoleId));
}
}
private void addOrUpdateOrganizationMemberError(String url, String organizationId, List<String> memberIds, List<String> userGroupIds, ResultMatcher resultMatcher) throws Exception {
OrganizationMemberExtendRequest organizationMemberRequest = new OrganizationMemberExtendRequest();
organizationMemberRequest.setOrganizationId(organizationId);
organizationMemberRequest.setMemberIds(memberIds);
organizationMemberRequest.setUserRoleIds(userGroupIds);
this.requestPost(url, organizationMemberRequest, resultMatcher);
}
private void addOrUpdateOrganizationProjectMemberError(String url, String organizationId, List<String> memberIds, List<String> projectIds, ResultMatcher resultMatcher) throws Exception {
OrgMemberExtendProjectRequest organizationMemberRequest = new OrgMemberExtendProjectRequest();
organizationMemberRequest.setOrganizationId(organizationId);
organizationMemberRequest.setMemberIds(memberIds);
organizationMemberRequest.setProjectIds(projectIds);
this.requestPost(url, organizationMemberRequest, resultMatcher);
}
private void requestGet(String url, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
@ -56,12 +300,24 @@ public class OrganizationControllerTests extends BaseTest{
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
private MvcResult responseGet(String url) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.get(url)
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(OrganizationRequest organizationRequest) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.post(OrganizationControllerTests.ORGANIZATION_MEMBER_LIST)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(organizationRequest))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andReturn();
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
}
}

View File

@ -87,7 +87,7 @@ public class SystemOrganizationControllerTests extends BaseTest{
Pager<?> sortPageData = JSON.parseObject(JSON.toJSONString(sortHolder.getData()), Pager.class);
// 返回值中取出第一条ID最大的数据, 并判断是否是default-organization-6
OrganizationDTO organizationDTO1 = JSON.parseArray(JSON.toJSONString(sortPageData.getList()), OrganizationDTO.class).get(0);
Assertions.assertTrue(StringUtils.equals(organizationDTO1.getId(), "default-organization-6"));
Assertions.assertTrue(organizationDTO1.getId().contains("default"));
}
@Test
@ -264,9 +264,7 @@ public class SystemOrganizationControllerTests extends BaseTest{
@Order(9)
public void testRemoveOrganizationMemberError() throws Exception {
// 组织不存在
this.requestGet(ORGANIZATION_REMOVE_MEMBER + "/default-organization-x/admin", status().is5xxServerError());
// 用户不存在
this.requestGet(ORGANIZATION_REMOVE_MEMBER + "/default-organization-3/admin-x", status().is5xxServerError());
this.requestGet(ORGANIZATION_REMOVE_MEMBER + "/default-organization-x/admin-x", status().is5xxServerError());
}
@Test

View File

@ -1,5 +1,5 @@
# 定时删除组织列表数据准备
INSERT INTO organization(id, name, description, create_time, update_time, create_user, update_user, deleted, delete_user, delete_time) VALUE
('default-organization-delete2', 'default-delete2', 'XXX-delete2', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', 0, null, null);
INSERT INTO organization(id, name, description, create_time, update_time, create_user, update_user, deleted, delete_user, delete_time) VALUE
('default-organization-delete1', 'default-delete1', 'XXX-delete1', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', 1, 'admin', 1683464436000);
INSERT INTO organization(id,num, name, description, create_time, update_time, create_user, update_user, deleted, delete_user, delete_time) VALUE
('default-organization-delete2', null, 'default-delete2', 'XXX-delete2', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', 0, null, null);
INSERT INTO organization(id,num, name, description, create_time, update_time, create_user, update_user, deleted, delete_user, delete_time) VALUE
('default-organization-delete1',null, 'default-delete1', 'XXX-delete1', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', 1, 'admin', 1683464436000);

View File

@ -1,6 +1,6 @@
-- 模拟数据
INSERT INTO organization (id, num, name, description, create_user, update_user, create_time, update_time) VALUES ('organization_id_001', 100010, '测试日志组织', '测试日志的组织', 'admin', 'admin', unix_timestamp() * 1000, unix_timestamp() * 1000);
INSERT INTO organization (id, num, name, description, create_user, update_user, create_time, update_time) VALUES ('organization_id_002', 100011, '测试日志组织2', '测试日志的组织2', 'admin', 'admin', unix_timestamp() * 1000, unix_timestamp() * 1000);
INSERT INTO organization (id, num, name, description, create_user, update_user, create_time, update_time) VALUES ('organization_id_001', null, '测试日志组织', '测试日志的组织', 'admin', 'admin', unix_timestamp() * 1000, unix_timestamp() * 1000);
INSERT INTO organization (id, num, name, description, create_user, update_user, create_time, update_time) VALUES ('organization_id_002', null, '测试日志组织2', '测试日志的组织2', '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) VALUES ('project_id_001', null, 'organization_id_001', '测试日志项目', '测试日志的项目', '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) VALUES ('project_id_002', null, 'organization_id_002', '测试日志项目2', '测试日志的项目2', 'admin', 'admin', unix_timestamp() * 1000, unix_timestamp() * 1000);

View File

@ -1,16 +1,16 @@
# 组织列表数据准备
INSERT INTO organization(id, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-1', 'default-1', 'XXX-1', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-2', 'default-2', 'XXX-2', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-3', 'default-3', 'XXX-3', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-4', 'default-4', 'XXX-4', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-5', 'default-5', 'XXX-5', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-6', 'default-6', 'XXX-6', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id,num, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-1',null, 'default-1', 'XXX-1', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, num, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-2',null, 'default-2', 'XXX-2', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, num, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-3',null, 'default-3', 'XXX-3', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, num, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-4',null, 'default-4', 'XXX-4', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id,num, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-5',null, 'default-5', 'XXX-5', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
INSERT INTO organization(id, num, name, description, create_time, update_time, create_user, update_user, delete_user, delete_time) VALUE
('default-organization-6',null, 'default-6', 'XXX-6', UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, 'admin', 'admin', null, null);
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-admin', 'default-Administrator', 'admin-default@metersphere.io', MD5('metersphere'), UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin');
INSERT INTO user_role_relation (id, user_id, role_id, source_id, create_time, create_user) VALUE