refactor(系统设置): 更新用户操作的日志记录方式

This commit is contained in:
song-tianyang 2023-08-28 13:27:27 +08:00 committed by 刘瑞斌
parent 3648a50c40
commit e89eafab47
9 changed files with 225 additions and 128 deletions

View File

@ -57,7 +57,7 @@ public class OperationLogModule {
public static final String SETTING = "SETTING";
public static final String SETTING_SYSTEM = "SETTING_SYSTEM";
public static final String SETTING_SYSTEM_USER_SINGLE = "SETTING_SYSTEM_USER";
public static final String SETTING_SYSTEM_USER_SINGLE = "SETTING_SYSTEM_USER_SINGLE";
public static final String SETTING_SYSTEM_USER_GROUP = "SETTING_SYSTEM_USER_GROUP";
public static final String SETTING_SYSTEM_ORGANIZATION = "SETTING_SYSTEM_ORGANIZATION";
public static final String SETTING_SYSTEM_PARAMETER = "SETTING_SYSTEM_PARAMETER";

View File

@ -84,11 +84,18 @@ test_resource_pool.status.not_blank=Test resource pool status must not be blank
test_resource_pool.status.length_range=Test resource pool status must be between {min} and {max} characters long
user.not.delete=User can't delete
user.id.not_blank=User id must not be blank
user.name.not_blank=User name must not be blank
user.name.length_range=User name must be between {min} and {max} characters long
user.name.not_blank=Username must not be blank
user.name.length_range=Username must be between {min} and {max} characters long
user.email.not_blank=User email must not be blank
user.email.length_range=User email must be between {min} and {max} characters long
user.email.repeat=User email already exists
user.reset.password=Reset password
user.delete=Delete user
user.enable=Enable user
user.disable=Disable user
user.add.project=Add project
user.add.org=Add organization
user.add.group=Add group
user.email.invalid=User email is invalid
user.status.not_blank=User status must not be blank
user.status.length_range=User status must be between {min} and {max} characters long

View File

@ -89,6 +89,13 @@ user.name.length_range=用户名称长度必须在{min}和{max}之间
user.email.not_blank=用户email不能为空
user.email.length_range=用户email长度必须在{min}和{max}之间
user.email.repeat=用户email已存在
user.reset.password=重置密码
user.delete=删除用户
user.enable=启用用户
user.disable=禁用用户
user.add.project=添加项目
user.add.org=添加组织
user.add.group=添加用户组
user.email.invalid=用户email格式不正确
user.status.not_blank=用户状态不能为空
user.status.length_range=用户状态长度必须在{min}和{max}之间

View File

@ -89,6 +89,13 @@ user.name.length_range=用戶名稱長度必須在{min}和{max}之間
user.email.not_blank=用戶email不能為空
user.email.length_range=用戶email長度必須在{min}和{max}之間
user.email.repeat=用戶email已存在
user.reset.password=重置密碼
user.delete=刪除用戶
user.enable=啟用用戶
user.disable=禁用用戶
user.add.project=添加項目
user.add.org=添加組織
user.add.group=添加用戶組
user.email.invalid=用戶email格式不正確
user.status.not_blank=用戶狀態不能為空
user.status.length_range=用戶狀態長度必須在{min}和{max}之間

View File

@ -27,6 +27,7 @@ import io.metersphere.system.utils.TreeNodeParseUtils;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
@ -39,6 +40,7 @@ import java.util.List;
import java.util.Map;
@RestController
@Tag(name = "系统设置-系统-用户")
@RequestMapping("/system/user")
public class UserController {
@Resource
@ -64,14 +66,14 @@ public class UserController {
}
@PostMapping("/add")
@Operation(summary = "添加用户")
@Operation(summary = "系统设置-系统-用户-添加用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_ADD)
public UserBatchCreateDTO addUser(@Validated({Created.class}) @RequestBody UserBatchCreateDTO userCreateDTO) {
return userService.addUser(userCreateDTO, UserSource.LOCAL.name(), SessionUtils.getUserId());
}
@PostMapping("/update")
@Operation(summary = "修改用户")
@Operation(summary = "系统设置-系统-用户-修改用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.updateLog(#request)", msClass = UserLogService.class)
public UserEditRequest updateUser(@Validated({Updated.class}) @RequestBody UserEditRequest request) {
@ -79,7 +81,7 @@ public class UserController {
}
@PostMapping("/page")
@Operation(summary = "分页查找用户")
@Operation(summary = "系统设置-系统-用户-分页查找用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ)
public Pager<List<UserTableResponse>> list(@Validated @RequestBody BasePageRequest request) {
Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize(),
@ -88,22 +90,22 @@ public class UserController {
}
@PostMapping("/update/enable")
@Operation(summary = "启用/禁用用户")
@Operation(summary = "系统设置-系统-用户-启用/禁用用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.batchUpdateLog(#request)", msClass = UserLogService.class)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.batchUpdateEnableLog(#request)", msClass = UserLogService.class)
public TableBatchProcessResponse updateUserEnable(@Validated @RequestBody UserChangeEnableRequest request) {
return userService.updateUserEnable(request, SessionUtils.getSessionId());
}
@PostMapping(value = "/import", consumes = {"multipart/form-data"})
@Operation(summary = "导入用户")
@Operation(summary = "系统设置-系统-用户-导入用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_IMPORT)
public UserImportResponse importUser(@RequestPart(value = "file", required = false) MultipartFile excelFile) {
return userService.importByExcel(excelFile, UserSource.LOCAL.name(), SessionUtils.getSessionId());
}
@PostMapping("/delete")
@Operation(summary = "删除用户")
@Operation(summary = "系统设置-系统-用户-删除用户")
@Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#request)", msClass = UserLogService.class)
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_DELETE)
public TableBatchProcessResponse deleteUser(@Validated @RequestBody TableBatchProcessDTO request) {
@ -111,7 +113,7 @@ public class UserController {
}
@PostMapping("/reset/password")
@Operation(summary = "重置用户密码")
@Operation(summary = "系统设置-系统-用户-重置用户密码")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.resetPasswordLog(#request)", msClass = UserLogService.class)
public TableBatchProcessResponse resetPassword(@Validated @RequestBody TableBatchProcessDTO request) {
@ -119,21 +121,21 @@ public class UserController {
}
@GetMapping("/get/global/system/role")
@Operation(summary = "查找系统级用户权限")
@Operation(summary = "系统设置-系统-用户-查找系统级用户组")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_READ)
public List<UserSelectOption> getGlobalSystemRole() {
return globalUserRoleService.getGlobalSystemRoleList();
}
@GetMapping("/get/organization")
@Operation(summary = "用户批量操作-查找组织")
@Operation(summary = "系统设置-系统-用户-用户批量操作-查找组织")
@RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_ROLE_READ, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ}, logical = Logical.AND)
public List<OptionDTO> getOrganization() {
return organizationService.listAll();
}
@GetMapping("/get/project")
@Operation(summary = "用户批量操作-查找项目")
@Operation(summary = "系统设置-系统-用户-用户批量操作-查找项目")
@RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_ROLE_READ, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ}, logical = Logical.AND)
public List<BaseTreeNode> getProject() {
Map<Organization, List<Project>> orgProjectMap = organizationService.getOrgProjectMap();
@ -141,15 +143,16 @@ public class UserController {
}
@PostMapping("/add/batch/user-role")
@Operation(summary = "批量添加用户到多个用户组中")
@Operation(summary = "系统设置-系统-用户-批量添加用户到多个用户组中")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.ADD, expression = "#msClass.batchAddLog(#request)", msClass = GlobalUserRoleRelationLogService.class)
public TableBatchProcessResponse batchAddUserGroupRole(@Validated({Created.class}) @RequestBody UserRoleBatchRelationRequest request) {
return globalUserRoleRelationService.batchAdd(request, SessionUtils.getUserId());
TableBatchProcessResponse returnResponse = globalUserRoleRelationService.batchAdd(request, SessionUtils.getUserId());
userLogService.batchAddUserRoleLog(request, SessionUtils.getUserId());
return returnResponse;
}
@PostMapping("/add-project-member")
@Operation(summary = "批量添加用户到项目")
@Operation(summary = "系统设置-系统-用户-批量添加用户到项目")
@RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_READ_UPDATE, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_MEMBER_ADD}, logical = Logical.AND)
public TableBatchProcessResponse addProjectMember(@Validated @RequestBody UserRoleBatchRelationRequest userRoleBatchRelationRequest) {
ProjectAddMemberBatchRequest request = new ProjectAddMemberBatchRequest();
@ -161,7 +164,7 @@ public class UserController {
}
@PostMapping("/add-org-member")
@Operation(summary = "批量添加用户到组织")
@Operation(summary = "系统设置-系统-用户-批量添加用户到组织")
@RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_READ_UPDATE, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_MEMBER_ADD}, logical = Logical.AND)
public TableBatchProcessResponse addMember(@Validated @RequestBody UserRoleBatchRelationRequest userRoleBatchRelationRequest) {
//获取本次处理的用户

View File

@ -26,7 +26,6 @@ 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.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -832,24 +831,26 @@ public class OrganizationService {
ProjectExample projectExample = new ProjectExample();
projectExample.setOrderByClause("name asc");
List<Project> allProject = projectMapper.selectByExample(projectExample);
OrganizationExample orgExample = new OrganizationExample();
orgExample.createCriteria().andIdIn(allProject.stream().map(Project::getOrganizationId).distinct().collect(Collectors.toList()));
orgExample.setOrderByClause("name asc");
List<Organization> orgList = organizationMapper.selectByExample(orgExample);
LinkedHashMap<Organization, List<Project>> returnMap = new LinkedHashMap<>();
for (Organization org : orgList) {
List<Project> projectsInOrg = new ArrayList<>();
for (Project project : allProject) {
if (StringUtils.equals(project.getOrganizationId(), org.getId())) {
projectsInOrg.add(project);
if (CollectionUtils.isNotEmpty(allProject)) {
LinkedHashMap<Organization, List<Project>> returnMap = new LinkedHashMap<>();
OrganizationExample orgExample = new OrganizationExample();
orgExample.createCriteria().andIdIn(allProject.stream().map(Project::getOrganizationId).distinct().collect(Collectors.toList()));
orgExample.setOrderByClause("name asc");
List<Organization> orgList = organizationMapper.selectByExample(orgExample);
for (Organization org : orgList) {
List<Project> projectsInOrg = new ArrayList<>();
for (Project project : allProject) {
if (StringUtils.equals(project.getOrganizationId(), org.getId())) {
projectsInOrg.add(project);
}
}
allProject.remove(projectsInOrg);
returnMap.put(org, projectsInOrg);
}
allProject.remove(projectsInOrg);
returnMap.put(org, projectsInOrg);
return returnMap;
} else {
return new LinkedHashMap<>();
}
return returnMap;
}
public Map<String, Long> getTotal(String organizationId) {

View File

@ -1,5 +1,8 @@
package io.metersphere.system.service;
import io.metersphere.project.domain.Project;
import io.metersphere.project.domain.ProjectExample;
import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.sdk.constants.HttpMethodConstants;
import io.metersphere.sdk.constants.OperationLogConstants;
import io.metersphere.sdk.dto.LogDTO;
@ -9,19 +12,23 @@ 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.JSON;
import io.metersphere.system.domain.User;
import io.metersphere.system.domain.UserExample;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.*;
import io.metersphere.system.mapper.OrganizationMapper;
import io.metersphere.system.mapper.UserMapper;
import io.metersphere.system.mapper.UserRoleMapper;
import io.metersphere.system.request.user.UserChangeEnableRequest;
import io.metersphere.system.request.user.UserEditRequest;
import io.metersphere.system.request.user.UserRoleBatchRelationRequest;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@Transactional(rollbackFor = Exception.class)
@ -32,23 +39,29 @@ public class UserLogService {
private UserToolService userToolService;
@Resource
private OperationLogService operationLogService;
@Resource
private ProjectMapper projectMapper;
@Resource
private OrganizationMapper organizationMapper;
@Resource
private UserRoleMapper userRoleMapper;
//批量添加用户记录日志
public List<LogDTO> getBatchAddLogs(@Valid List<User> userList) {
List<LogDTO> logs = new ArrayList<>();
userList.forEach(user -> {
LogDTO log = new LogDTO();
log.setId(UUID.randomUUID().toString());
log.setCreateUser(user.getCreateUser());
log.setProjectId(OperationLogConstants.SYSTEM);
log.setOrganizationId(OperationLogConstants.SYSTEM);
log.setType(OperationLogType.ADD.name());
log.setModule(OperationLogModule.SYSTEM_USER);
log.setMethod("addUser");
log.setCreateTime(user.getCreateTime());
log.setSourceId(user.getId());
log.setContent(user.getName() + "(" + user.getEmail() + ")");
log.setOriginalValue(JSON.toJSONBytes(user));
LogDTO log = LogDTOBuilder.builder()
.projectId(OperationLogConstants.SYSTEM)
.organizationId(OperationLogConstants.SYSTEM)
.type(OperationLogType.ADD.name())
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.method(HttpMethodConstants.POST.name())
.path("/addUser")
.sourceId(user.getId())
.content(user.getName() + "(" + user.getEmail() + ")")
.originalValue(JSON.toJSONBytes(user))
.createUser(user.getCreateUser())
.build().getLogDTO();
logs.add(log);
});
return logs;
@ -57,45 +70,45 @@ public class UserLogService {
public LogDTO updateLog(UserEditRequest request) {
User user = userMapper.selectByPrimaryKey(request.getId());
if (user != null) {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
request.getId(),
null,
OperationLogType.UPDATE.name(),
OperationLogModule.SYSTEM_USER,
JSON.toJSONString(user));
dto.setPath("/update");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(user));
LogDTO dto = LogDTOBuilder.builder()
.projectId(OperationLogConstants.SYSTEM)
.organizationId(OperationLogConstants.SYSTEM)
.type(OperationLogType.UPDATE.name())
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.method(HttpMethodConstants.POST.name())
.path("/update")
.sourceId(request.getId())
.content(user.getName())
.originalValue(JSON.toJSONBytes(user))
.build().getLogDTO();
return dto;
}
return null;
}
public List<LogDTO> batchUpdateLog(TableBatchProcessDTO request) {
//批量开启和关闭
public List<LogDTO> batchUpdateEnableLog(UserChangeEnableRequest request) {
List<LogDTO> logDTOList = new ArrayList<>();
request.setSelectIds(userToolService.getBatchUserIds(request));
List<User> userList = userToolService.selectByIdList(request.getSelectIds());
for (User user : userList) {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
user.getId(),
null,
OperationLogType.UPDATE.name(),
OperationLogModule.SYSTEM_USER,
JSON.toJSONString(user));
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(user));
LogDTO dto = LogDTOBuilder.builder()
.projectId(OperationLogConstants.SYSTEM)
.organizationId(OperationLogConstants.SYSTEM)
.type(OperationLogType.UPDATE.name())
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.method(HttpMethodConstants.POST.name())
.path("/update/enable")
.sourceId(user.getId())
.content((request.isEnable() ? Translator.get("user.enable") : Translator.get("user.disable")) + ":" + user.getName())
.originalValue(JSON.toJSONBytes(user))
.build().getLogDTO();
logDTOList.add(dto);
}
return logDTOList;
}
/**
* @param request 批量重置密码 用于记录Log使用
*/
//批量重置密码
public List<LogDTO> resetPasswordLog(TableBatchProcessDTO request) {
request.setSelectIds(userToolService.getBatchUserIds(request));
List<LogDTO> returnList = new ArrayList<>();
@ -103,41 +116,41 @@ public class UserLogService {
example.createCriteria().andIdIn(request.getSelectIds());
List<User> userList = userMapper.selectByExample(example);
for (User user : userList) {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
user.getId(),
null,
OperationLogType.UPDATE.name(),
OperationLogModule.SYSTEM_USER,
user.getName());
dto.setPath("/reset/password");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(user));
LogDTO dto = LogDTOBuilder.builder()
.projectId(OperationLogConstants.SYSTEM)
.organizationId(OperationLogConstants.SYSTEM)
.type(OperationLogType.UPDATE.name())
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.method(HttpMethodConstants.POST.name())
.path("/reset/password")
.sourceId(user.getId())
.content(Translator.get("user.reset.password") + " : " + user.getName())
.originalValue(JSON.toJSONBytes(user))
.build().getLogDTO();
returnList.add(dto);
}
return returnList;
}
//删除日志
public List<LogDTO> deleteLog(TableBatchProcessDTO request) {
List<LogDTO> logDTOList = new ArrayList<>();
request.getSelectIds().forEach(item -> {
User user = userMapper.selectByPrimaryKey(item);
if (user != null) {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
user.getId(),
user.getCreateUser(),
OperationLogType.DELETE.name(),
OperationLogModule.SYSTEM_PROJECT,
user.getName());
dto.setPath("/delete");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(user));
LogDTO dto = LogDTOBuilder.builder()
.projectId(OperationLogConstants.SYSTEM)
.organizationId(OperationLogConstants.SYSTEM)
.type(OperationLogType.UPDATE.name())
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.method(HttpMethodConstants.POST.name())
.path("/delete")
.sourceId(user.getId())
.content(Translator.get("user.delete") + " : " + user.getName())
.originalValue(JSON.toJSONBytes(user))
.build().getLogDTO();
logDTOList.add(dto);
}
});
return logDTOList;
@ -147,6 +160,11 @@ public class UserLogService {
List<LogDTO> logs = new ArrayList<>();
List<String> userIds = userToolService.getBatchUserIds(request);
List<User> userList = userToolService.selectByIdList(userIds);
ProjectExample projectExample = new ProjectExample();
projectExample.createCriteria().andIdIn(request.getRoleIds());
List<String> projectNameList = projectMapper.selectByExample(projectExample)
.stream().map(Project::getName).collect(Collectors.toList());
String projectNames = StringUtils.join(projectNameList, ",");
for (User user : userList) {
//用户管理处修改了用户的组织
LogDTO log = LogDTOBuilder.builder()
@ -156,8 +174,8 @@ public class UserLogService {
.organizationId(OperationLogConstants.SYSTEM)
.sourceId(user.getId())
.type(OperationLogType.UPDATE.name())
.module(OperationLogModule.SYSTEM_USER)
.content(user.getName())
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.content(user.getName() + Translator.get("user.add.project") + ":" + projectNames)
.path("/system/user/add-project-member")
.modifiedValue(JSON.toJSONBytes(request.getRoleIds()))
.build().getLogDTO();
@ -166,20 +184,56 @@ public class UserLogService {
operationLogService.batchAdd(logs);
}
public void batchAddOrgLog(UserRoleBatchRelationRequest request, String operator) {
public void batchAddUserRoleLog(UserRoleBatchRelationRequest request, String operator) {
List<LogDTO> logs = new ArrayList<>();
List<String> userIds = userToolService.getBatchUserIds(request);
List<User> userList = userToolService.selectByIdList(userIds);
UserRoleExample example = new UserRoleExample();
example.createCriteria().andIdIn(request.getRoleIds());
List<String> roleNameList = userRoleMapper.selectByExample(example)
.stream().map(UserRole::getName).collect(Collectors.toList());
String roleNames = StringUtils.join(roleNameList, ",");
for (User user : userList) {
//用户管理处修改了用户的组织
LogDTO log = LogDTOBuilder.builder()
.projectId(OperationLogConstants.SYSTEM)
.module(OperationLogModule.SYSTEM_USER)
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.createUser(operator)
.organizationId(OperationLogConstants.SYSTEM)
.sourceId(user.getId())
.type(OperationLogType.UPDATE.name())
.content(user.getName())
.content(user.getName() + Translator.get("user.add.group") + ":" + roleNames)
.path("/system/user/add-org-member")
.method(HttpMethodConstants.POST.name())
.modifiedValue(JSON.toJSONBytes(request.getRoleIds()))
.build().getLogDTO();
logs.add(log);
}
operationLogService.batchAdd(logs);
}
public void batchAddOrgLog(UserRoleBatchRelationRequest request, String operator) {
List<LogDTO> logs = new ArrayList<>();
List<String> userIds = userToolService.getBatchUserIds(request);
List<User> userList = userToolService.selectByIdList(userIds);
OrganizationExample example = new OrganizationExample();
example.createCriteria().andIdIn(request.getRoleIds());
List<String> roleNameList = organizationMapper.selectByExample(example)
.stream().map(Organization::getName).collect(Collectors.toList());
String roleNames = StringUtils.join(roleNameList, ",");
for (User user : userList) {
//用户管理处修改了用户的组织
LogDTO log = LogDTOBuilder.builder()
.projectId(OperationLogConstants.SYSTEM)
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.createUser(operator)
.organizationId(OperationLogConstants.SYSTEM)
.sourceId(user.getId())
.type(OperationLogType.UPDATE.name())
.content(user.getName() + Translator.get("user.add.org") + ":" + roleNames)
.path("/system/user/add-org-member")
.method(HttpMethodConstants.POST.name())
.modifiedValue(JSON.toJSONBytes(request.getRoleIds()))

View File

@ -14,11 +14,8 @@ import io.metersphere.system.mapper.OrganizationMapper;
import io.metersphere.system.mapper.UserRoleMapper;
import io.metersphere.system.mapper.UserRoleRelationMapper;
import io.metersphere.system.response.user.UserTableResponse;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
@ -28,7 +25,6 @@ import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.util.*;
import java.util.stream.Collectors;
@ -81,11 +77,7 @@ public class UserRoleRelationService {
return logs;
}
public void batchSave(@Validated({Created.class, Updated.class})
@NotEmpty(groups = {Created.class, Updated.class}, message = "{user_role.id.not_blank}")
List<@Valid @NotBlank(message = "{user_role.id.not_blank}", groups = {Created.class, Updated.class}) String> userRoleIdList,
@NotEmpty(groups = {Created.class, Updated.class}, message = "{user.info.not_empty}")
List<@Valid User> userList) {
public void batchSave(List<String> userRoleIdList, List<User> userList) {
long operationTime = System.currentTimeMillis();
List<UserRoleRelation> userRoleRelationSaveList = new ArrayList<>();
//添加用户组织关系
@ -113,11 +105,6 @@ public class UserRoleRelationService {
}
sqlSession.flushStatements();
SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);
//记录添加日志
for (User user : userList) {
operationLogService.batchAdd(this.getBatchLogs(userRoleIdList, user, "addUser", user.getCreateUser(), OperationLogType.ADD.name()));
}
}
public Map<String, UserTableResponse> selectGlobalUserRoleAndOrganization(@Valid @NotEmpty List<String> userIdList) {

View File

@ -54,7 +54,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserControllerTests extends BaseTest {
@Resource
private UserService userService;
@Resource
@ -405,7 +404,7 @@ public class UserControllerTests extends BaseTest {
@Order(6)
public void testUserChangeEnableSuccess() throws Exception {
this.checkUserList();
//单独修改状态
//修改状态关闭
UserCreateInfo userInfo = USER_LIST.get(0);
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setSelectIds(new ArrayList<>() {{
@ -419,6 +418,16 @@ public class UserControllerTests extends BaseTest {
UserDTO userDTO = this.getUserByEmail(userInfo.getEmail());
Assertions.assertEquals(userDTO.getEnable(), userChangeEnableRequest.isEnable());
//修改状态开启
userChangeEnableRequest.setEnable(true);
this.requestPost(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk());
for (String item : userChangeEnableRequest.getSelectIds()) {
checkLog(item, OperationLogType.UPDATE);
}
userDTO = this.getUserByEmail(userInfo.getEmail());
Assertions.assertEquals(userDTO.getEnable(), userChangeEnableRequest.isEnable());
}
@Test
@ -722,8 +731,8 @@ public class UserControllerTests extends BaseTest {
request.getSelectIds().size() * request.getRoleIds().size()
);
//检查日志
for (UserSelectOption option : USER_ROLE_LIST) {
this.checkLog(option.getId(), OperationLogType.ADD);
for (String userID : request.getSelectIds()) {
this.checkLog(userID, OperationLogType.ADD);
}
//测试重复添加用户权限预期结果不会额外增加数据
@ -733,10 +742,6 @@ public class UserControllerTests extends BaseTest {
globalUserRoleRelationService.selectByUserIdAndRuleId(request.getSelectIds(), request.getRoleIds()).size(),
request.getSelectIds().size() * request.getRoleIds().size()
);
//检查日志
for (UserSelectOption option : USER_ROLE_LIST) {
this.checkLog(option.getId(), OperationLogType.ADD);
}
}
@Test
@ -771,6 +776,32 @@ public class UserControllerTests extends BaseTest {
userRequestUtils.requestPost(UserRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER);
}
@Test
@Order(9)
public void testGetEmptyProject() throws Exception {
//测试如果没有项目系统不会报错
List<Project> allProjectList = projectMapper.selectByExample(null);
projectMapper.deleteByExample(null);
String str = userRequestUtils.responseGet(UserRequestUtils.URL_GET_PROJECT).getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder rh = JSON.parseObject(str, ResultHolder.class);
List<BaseTreeNode> userTreeSelectOptions = JSON.parseArray(
JSON.toJSONString(rh.getData()),
BaseTreeNode.class);
Assertions.assertTrue(CollectionUtils.isEmpty(userTreeSelectOptions));
//还原数据
for (Project project : allProjectList) {
projectMapper.insert(project);
}
//开始正常获取数据 有可能在整体运行单元测试的过程中会被默认插入了项目测试数据所以这里根据上面数据库查到的来做判断
str = userRequestUtils.responseGet(UserRequestUtils.URL_GET_PROJECT).getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(str, ResultHolder.class);
userTreeSelectOptions = JSON.parseArray(
JSON.toJSONString(resultHolder.getData()),
BaseTreeNode.class);
Assertions.assertEquals(CollectionUtils.isEmpty(userTreeSelectOptions), CollectionUtils.isEmpty(allProjectList));
}
@Test
@Order(10)
@Sql(scripts = {"/dml/init_user_org_project.sql"},
@ -834,8 +865,8 @@ public class UserControllerTests extends BaseTest {
}
}
//检查日志
for (UserSelectOption option : USER_ROLE_LIST) {
this.checkLog(option.getId(), OperationLogType.ADD);
for (String userID : request.getSelectIds()) {
this.checkLog(userID, OperationLogType.UPDATE);
}
//检查用户表格不会加载出来非全局用户组
this.testPageSuccess();