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 = "SETTING";
public static final String SETTING_SYSTEM = "SETTING_SYSTEM"; 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_USER_GROUP = "SETTING_SYSTEM_USER_GROUP";
public static final String SETTING_SYSTEM_ORGANIZATION = "SETTING_SYSTEM_ORGANIZATION"; public static final String SETTING_SYSTEM_ORGANIZATION = "SETTING_SYSTEM_ORGANIZATION";
public static final String SETTING_SYSTEM_PARAMETER = "SETTING_SYSTEM_PARAMETER"; 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 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.not.delete=User can't delete
user.id.not_blank=User id must not be blank user.id.not_blank=User id must not be blank
user.name.not_blank=User name must not be blank user.name.not_blank=Username must not be blank
user.name.length_range=User name must be between {min} and {max} characters long 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.not_blank=User email must not be blank
user.email.length_range=User email must be between {min} and {max} characters long user.email.length_range=User email must be between {min} and {max} characters long
user.email.repeat=User email already exists 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.email.invalid=User email is invalid
user.status.not_blank=User status must not be blank user.status.not_blank=User status must not be blank
user.status.length_range=User status must be between {min} and {max} characters long 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.not_blank=用户email不能为空
user.email.length_range=用户email长度必须在{min}和{max}之间 user.email.length_range=用户email长度必须在{min}和{max}之间
user.email.repeat=用户email已存在 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.email.invalid=用户email格式不正确
user.status.not_blank=用户状态不能为空 user.status.not_blank=用户状态不能为空
user.status.length_range=用户状态长度必须在{min}和{max}之间 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.not_blank=用戶email不能為空
user.email.length_range=用戶email長度必須在{min}和{max}之間 user.email.length_range=用戶email長度必須在{min}和{max}之間
user.email.repeat=用戶email已存在 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.email.invalid=用戶email格式不正確
user.status.not_blank=用戶狀態不能為空 user.status.not_blank=用戶狀態不能為空
user.status.length_range=用戶狀態長度必須在{min}和{max}之間 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.Created;
import io.metersphere.validation.groups.Updated; import io.metersphere.validation.groups.Updated;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.Logical;
@ -39,6 +40,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
@RestController @RestController
@Tag(name = "系统设置-系统-用户")
@RequestMapping("/system/user") @RequestMapping("/system/user")
public class UserController { public class UserController {
@Resource @Resource
@ -64,14 +66,14 @@ public class UserController {
} }
@PostMapping("/add") @PostMapping("/add")
@Operation(summary = "添加用户") @Operation(summary = "系统设置-系统-用户-添加用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_ADD) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_ADD)
public UserBatchCreateDTO addUser(@Validated({Created.class}) @RequestBody UserBatchCreateDTO userCreateDTO) { public UserBatchCreateDTO addUser(@Validated({Created.class}) @RequestBody UserBatchCreateDTO userCreateDTO) {
return userService.addUser(userCreateDTO, UserSource.LOCAL.name(), SessionUtils.getUserId()); return userService.addUser(userCreateDTO, UserSource.LOCAL.name(), SessionUtils.getUserId());
} }
@PostMapping("/update") @PostMapping("/update")
@Operation(summary = "修改用户") @Operation(summary = "系统设置-系统-用户-修改用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.updateLog(#request)", msClass = UserLogService.class) @Log(type = OperationLogType.UPDATE, expression = "#msClass.updateLog(#request)", msClass = UserLogService.class)
public UserEditRequest updateUser(@Validated({Updated.class}) @RequestBody UserEditRequest request) { public UserEditRequest updateUser(@Validated({Updated.class}) @RequestBody UserEditRequest request) {
@ -79,7 +81,7 @@ public class UserController {
} }
@PostMapping("/page") @PostMapping("/page")
@Operation(summary = "分页查找用户") @Operation(summary = "系统设置-系统-用户-分页查找用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ)
public Pager<List<UserTableResponse>> list(@Validated @RequestBody BasePageRequest request) { public Pager<List<UserTableResponse>> list(@Validated @RequestBody BasePageRequest request) {
Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize(), Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize(),
@ -88,22 +90,22 @@ public class UserController {
} }
@PostMapping("/update/enable") @PostMapping("/update/enable")
@Operation(summary = "启用/禁用用户") @Operation(summary = "系统设置-系统-用户-启用/禁用用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE) @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) { public TableBatchProcessResponse updateUserEnable(@Validated @RequestBody UserChangeEnableRequest request) {
return userService.updateUserEnable(request, SessionUtils.getSessionId()); return userService.updateUserEnable(request, SessionUtils.getSessionId());
} }
@PostMapping(value = "/import", consumes = {"multipart/form-data"}) @PostMapping(value = "/import", consumes = {"multipart/form-data"})
@Operation(summary = "导入用户") @Operation(summary = "系统设置-系统-用户-导入用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_IMPORT) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_IMPORT)
public UserImportResponse importUser(@RequestPart(value = "file", required = false) MultipartFile excelFile) { public UserImportResponse importUser(@RequestPart(value = "file", required = false) MultipartFile excelFile) {
return userService.importByExcel(excelFile, UserSource.LOCAL.name(), SessionUtils.getSessionId()); return userService.importByExcel(excelFile, UserSource.LOCAL.name(), SessionUtils.getSessionId());
} }
@PostMapping("/delete") @PostMapping("/delete")
@Operation(summary = "删除用户") @Operation(summary = "系统设置-系统-用户-删除用户")
@Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#request)", msClass = UserLogService.class) @Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#request)", msClass = UserLogService.class)
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_DELETE) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_DELETE)
public TableBatchProcessResponse deleteUser(@Validated @RequestBody TableBatchProcessDTO request) { public TableBatchProcessResponse deleteUser(@Validated @RequestBody TableBatchProcessDTO request) {
@ -111,7 +113,7 @@ public class UserController {
} }
@PostMapping("/reset/password") @PostMapping("/reset/password")
@Operation(summary = "重置用户密码") @Operation(summary = "系统设置-系统-用户-重置用户密码")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.resetPasswordLog(#request)", msClass = UserLogService.class) @Log(type = OperationLogType.UPDATE, expression = "#msClass.resetPasswordLog(#request)", msClass = UserLogService.class)
public TableBatchProcessResponse resetPassword(@Validated @RequestBody TableBatchProcessDTO request) { public TableBatchProcessResponse resetPassword(@Validated @RequestBody TableBatchProcessDTO request) {
@ -119,21 +121,21 @@ public class UserController {
} }
@GetMapping("/get/global/system/role") @GetMapping("/get/global/system/role")
@Operation(summary = "查找系统级用户权限") @Operation(summary = "系统设置-系统-用户-查找系统级用户组")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_READ) @RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_READ)
public List<UserSelectOption> getGlobalSystemRole() { public List<UserSelectOption> getGlobalSystemRole() {
return globalUserRoleService.getGlobalSystemRoleList(); return globalUserRoleService.getGlobalSystemRoleList();
} }
@GetMapping("/get/organization") @GetMapping("/get/organization")
@Operation(summary = "用户批量操作-查找组织") @Operation(summary = "系统设置-系统-用户-用户批量操作-查找组织")
@RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_ROLE_READ, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ}, logical = Logical.AND) @RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_ROLE_READ, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ}, logical = Logical.AND)
public List<OptionDTO> getOrganization() { public List<OptionDTO> getOrganization() {
return organizationService.listAll(); return organizationService.listAll();
} }
@GetMapping("/get/project") @GetMapping("/get/project")
@Operation(summary = "用户批量操作-查找项目") @Operation(summary = "系统设置-系统-用户-用户批量操作-查找项目")
@RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_ROLE_READ, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ}, logical = Logical.AND) @RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_ROLE_READ, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ}, logical = Logical.AND)
public List<BaseTreeNode> getProject() { public List<BaseTreeNode> getProject() {
Map<Organization, List<Project>> orgProjectMap = organizationService.getOrgProjectMap(); Map<Organization, List<Project>> orgProjectMap = organizationService.getOrgProjectMap();
@ -141,15 +143,16 @@ public class UserController {
} }
@PostMapping("/add/batch/user-role") @PostMapping("/add/batch/user-role")
@Operation(summary = "批量添加用户到多个用户组中") @Operation(summary = "系统设置-系统-用户-批量添加用户到多个用户组中")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE) @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) { 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") @PostMapping("/add-project-member")
@Operation(summary = "批量添加用户到项目") @Operation(summary = "系统设置-系统-用户-批量添加用户到项目")
@RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_READ_UPDATE, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_MEMBER_ADD}, logical = Logical.AND) @RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_READ_UPDATE, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_MEMBER_ADD}, logical = Logical.AND)
public TableBatchProcessResponse addProjectMember(@Validated @RequestBody UserRoleBatchRelationRequest userRoleBatchRelationRequest) { public TableBatchProcessResponse addProjectMember(@Validated @RequestBody UserRoleBatchRelationRequest userRoleBatchRelationRequest) {
ProjectAddMemberBatchRequest request = new ProjectAddMemberBatchRequest(); ProjectAddMemberBatchRequest request = new ProjectAddMemberBatchRequest();
@ -161,7 +164,7 @@ public class UserController {
} }
@PostMapping("/add-org-member") @PostMapping("/add-org-member")
@Operation(summary = "批量添加用户到组织") @Operation(summary = "系统设置-系统-用户-批量添加用户到组织")
@RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_READ_UPDATE, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_MEMBER_ADD}, logical = Logical.AND) @RequiresPermissions(value = {PermissionConstants.SYSTEM_USER_READ_UPDATE, PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_MEMBER_ADD}, logical = Logical.AND)
public TableBatchProcessResponse addMember(@Validated @RequestBody UserRoleBatchRelationRequest userRoleBatchRelationRequest) { 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.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils; import org.mybatis.spring.SqlSessionUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -832,13 +831,12 @@ public class OrganizationService {
ProjectExample projectExample = new ProjectExample(); ProjectExample projectExample = new ProjectExample();
projectExample.setOrderByClause("name asc"); projectExample.setOrderByClause("name asc");
List<Project> allProject = projectMapper.selectByExample(projectExample); List<Project> allProject = projectMapper.selectByExample(projectExample);
if (CollectionUtils.isNotEmpty(allProject)) {
LinkedHashMap<Organization, List<Project>> returnMap = new LinkedHashMap<>();
OrganizationExample orgExample = new OrganizationExample(); OrganizationExample orgExample = new OrganizationExample();
orgExample.createCriteria().andIdIn(allProject.stream().map(Project::getOrganizationId).distinct().collect(Collectors.toList())); orgExample.createCriteria().andIdIn(allProject.stream().map(Project::getOrganizationId).distinct().collect(Collectors.toList()));
orgExample.setOrderByClause("name asc"); orgExample.setOrderByClause("name asc");
List<Organization> orgList = organizationMapper.selectByExample(orgExample); List<Organization> orgList = organizationMapper.selectByExample(orgExample);
LinkedHashMap<Organization, List<Project>> returnMap = new LinkedHashMap<>();
for (Organization org : orgList) { for (Organization org : orgList) {
List<Project> projectsInOrg = new ArrayList<>(); List<Project> projectsInOrg = new ArrayList<>();
for (Project project : allProject) { for (Project project : allProject) {
@ -850,6 +848,9 @@ public class OrganizationService {
returnMap.put(org, projectsInOrg); returnMap.put(org, projectsInOrg);
} }
return returnMap; return returnMap;
} else {
return new LinkedHashMap<>();
}
} }
public Map<String, Long> getTotal(String organizationId) { public Map<String, Long> getTotal(String organizationId) {

View File

@ -1,5 +1,8 @@
package io.metersphere.system.service; 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.HttpMethodConstants;
import io.metersphere.sdk.constants.OperationLogConstants; import io.metersphere.sdk.constants.OperationLogConstants;
import io.metersphere.sdk.dto.LogDTO; 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.constants.OperationLogType;
import io.metersphere.sdk.log.service.OperationLogService; import io.metersphere.sdk.log.service.OperationLogService;
import io.metersphere.sdk.util.JSON; import io.metersphere.sdk.util.JSON;
import io.metersphere.system.domain.User; import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.UserExample; import io.metersphere.system.domain.*;
import io.metersphere.system.mapper.OrganizationMapper;
import io.metersphere.system.mapper.UserMapper; 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.UserEditRequest;
import io.metersphere.system.request.user.UserRoleBatchRelationRequest; import io.metersphere.system.request.user.UserRoleBatchRelationRequest;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.stream.Collectors;
@Service @Service
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@ -32,23 +39,29 @@ public class UserLogService {
private UserToolService userToolService; private UserToolService userToolService;
@Resource @Resource
private OperationLogService operationLogService; private OperationLogService operationLogService;
@Resource
private ProjectMapper projectMapper;
@Resource
private OrganizationMapper organizationMapper;
@Resource
private UserRoleMapper userRoleMapper;
//批量添加用户记录日志 //批量添加用户记录日志
public List<LogDTO> getBatchAddLogs(@Valid List<User> userList) { public List<LogDTO> getBatchAddLogs(@Valid List<User> userList) {
List<LogDTO> logs = new ArrayList<>(); List<LogDTO> logs = new ArrayList<>();
userList.forEach(user -> { userList.forEach(user -> {
LogDTO log = new LogDTO(); LogDTO log = LogDTOBuilder.builder()
log.setId(UUID.randomUUID().toString()); .projectId(OperationLogConstants.SYSTEM)
log.setCreateUser(user.getCreateUser()); .organizationId(OperationLogConstants.SYSTEM)
log.setProjectId(OperationLogConstants.SYSTEM); .type(OperationLogType.ADD.name())
log.setOrganizationId(OperationLogConstants.SYSTEM); .module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
log.setType(OperationLogType.ADD.name()); .method(HttpMethodConstants.POST.name())
log.setModule(OperationLogModule.SYSTEM_USER); .path("/addUser")
log.setMethod("addUser"); .sourceId(user.getId())
log.setCreateTime(user.getCreateTime()); .content(user.getName() + "(" + user.getEmail() + ")")
log.setSourceId(user.getId()); .originalValue(JSON.toJSONBytes(user))
log.setContent(user.getName() + "(" + user.getEmail() + ")"); .createUser(user.getCreateUser())
log.setOriginalValue(JSON.toJSONBytes(user)); .build().getLogDTO();
logs.add(log); logs.add(log);
}); });
return logs; return logs;
@ -57,45 +70,45 @@ public class UserLogService {
public LogDTO updateLog(UserEditRequest request) { public LogDTO updateLog(UserEditRequest request) {
User user = userMapper.selectByPrimaryKey(request.getId()); User user = userMapper.selectByPrimaryKey(request.getId());
if (user != null) { if (user != null) {
LogDTO dto = new LogDTO( LogDTO dto = LogDTOBuilder.builder()
OperationLogConstants.SYSTEM, .projectId(OperationLogConstants.SYSTEM)
OperationLogConstants.SYSTEM, .organizationId(OperationLogConstants.SYSTEM)
request.getId(), .type(OperationLogType.UPDATE.name())
null, .module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
OperationLogType.UPDATE.name(), .method(HttpMethodConstants.POST.name())
OperationLogModule.SYSTEM_USER, .path("/update")
JSON.toJSONString(user)); .sourceId(request.getId())
dto.setPath("/update"); .content(user.getName())
dto.setMethod(HttpMethodConstants.POST.name()); .originalValue(JSON.toJSONBytes(user))
dto.setOriginalValue(JSON.toJSONBytes(user)); .build().getLogDTO();
return dto; return dto;
} }
return null; return null;
} }
public List<LogDTO> batchUpdateLog(TableBatchProcessDTO request) { //批量开启和关闭
public List<LogDTO> batchUpdateEnableLog(UserChangeEnableRequest request) {
List<LogDTO> logDTOList = new ArrayList<>(); List<LogDTO> logDTOList = new ArrayList<>();
request.setSelectIds(userToolService.getBatchUserIds(request)); request.setSelectIds(userToolService.getBatchUserIds(request));
List<User> userList = userToolService.selectByIdList(request.getSelectIds()); List<User> userList = userToolService.selectByIdList(request.getSelectIds());
for (User user : userList) { for (User user : userList) {
LogDTO dto = new LogDTO( LogDTO dto = LogDTOBuilder.builder()
OperationLogConstants.SYSTEM, .projectId(OperationLogConstants.SYSTEM)
OperationLogConstants.SYSTEM, .organizationId(OperationLogConstants.SYSTEM)
user.getId(), .type(OperationLogType.UPDATE.name())
null, .module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
OperationLogType.UPDATE.name(), .method(HttpMethodConstants.POST.name())
OperationLogModule.SYSTEM_USER, .path("/update/enable")
JSON.toJSONString(user)); .sourceId(user.getId())
dto.setMethod(HttpMethodConstants.POST.name()); .content((request.isEnable() ? Translator.get("user.enable") : Translator.get("user.disable")) + ":" + user.getName())
dto.setOriginalValue(JSON.toJSONBytes(user)); .originalValue(JSON.toJSONBytes(user))
.build().getLogDTO();
logDTOList.add(dto); logDTOList.add(dto);
} }
return logDTOList; return logDTOList;
} }
/** //批量重置密码
* @param request 批量重置密码 用于记录Log使用
*/
public List<LogDTO> resetPasswordLog(TableBatchProcessDTO request) { public List<LogDTO> resetPasswordLog(TableBatchProcessDTO request) {
request.setSelectIds(userToolService.getBatchUserIds(request)); request.setSelectIds(userToolService.getBatchUserIds(request));
List<LogDTO> returnList = new ArrayList<>(); List<LogDTO> returnList = new ArrayList<>();
@ -103,41 +116,41 @@ public class UserLogService {
example.createCriteria().andIdIn(request.getSelectIds()); example.createCriteria().andIdIn(request.getSelectIds());
List<User> userList = userMapper.selectByExample(example); List<User> userList = userMapper.selectByExample(example);
for (User user : userList) { for (User user : userList) {
LogDTO dto = new LogDTO( LogDTO dto = LogDTOBuilder.builder()
OperationLogConstants.SYSTEM, .projectId(OperationLogConstants.SYSTEM)
OperationLogConstants.SYSTEM, .organizationId(OperationLogConstants.SYSTEM)
user.getId(), .type(OperationLogType.UPDATE.name())
null, .module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
OperationLogType.UPDATE.name(), .method(HttpMethodConstants.POST.name())
OperationLogModule.SYSTEM_USER, .path("/reset/password")
user.getName()); .sourceId(user.getId())
dto.setPath("/reset/password"); .content(Translator.get("user.reset.password") + " : " + user.getName())
dto.setMethod(HttpMethodConstants.POST.name()); .originalValue(JSON.toJSONBytes(user))
dto.setOriginalValue(JSON.toJSONBytes(user)); .build().getLogDTO();
returnList.add(dto); returnList.add(dto);
} }
return returnList; return returnList;
} }
//删除日志
public List<LogDTO> deleteLog(TableBatchProcessDTO request) { public List<LogDTO> deleteLog(TableBatchProcessDTO request) {
List<LogDTO> logDTOList = new ArrayList<>(); List<LogDTO> logDTOList = new ArrayList<>();
request.getSelectIds().forEach(item -> { request.getSelectIds().forEach(item -> {
User user = userMapper.selectByPrimaryKey(item); User user = userMapper.selectByPrimaryKey(item);
if (user != null) { if (user != null) {
LogDTO dto = LogDTOBuilder.builder()
LogDTO dto = new LogDTO( .projectId(OperationLogConstants.SYSTEM)
OperationLogConstants.SYSTEM, .organizationId(OperationLogConstants.SYSTEM)
OperationLogConstants.SYSTEM, .type(OperationLogType.UPDATE.name())
user.getId(), .module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
user.getCreateUser(), .method(HttpMethodConstants.POST.name())
OperationLogType.DELETE.name(), .path("/delete")
OperationLogModule.SYSTEM_PROJECT, .sourceId(user.getId())
user.getName()); .content(Translator.get("user.delete") + " : " + user.getName())
.originalValue(JSON.toJSONBytes(user))
dto.setPath("/delete"); .build().getLogDTO();
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(user));
logDTOList.add(dto); logDTOList.add(dto);
} }
}); });
return logDTOList; return logDTOList;
@ -147,6 +160,11 @@ public class UserLogService {
List<LogDTO> logs = new ArrayList<>(); List<LogDTO> logs = new ArrayList<>();
List<String> userIds = userToolService.getBatchUserIds(request); List<String> userIds = userToolService.getBatchUserIds(request);
List<User> userList = userToolService.selectByIdList(userIds); 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) { for (User user : userList) {
//用户管理处修改了用户的组织 //用户管理处修改了用户的组织
LogDTO log = LogDTOBuilder.builder() LogDTO log = LogDTOBuilder.builder()
@ -156,8 +174,8 @@ public class UserLogService {
.organizationId(OperationLogConstants.SYSTEM) .organizationId(OperationLogConstants.SYSTEM)
.sourceId(user.getId()) .sourceId(user.getId())
.type(OperationLogType.UPDATE.name()) .type(OperationLogType.UPDATE.name())
.module(OperationLogModule.SYSTEM_USER) .module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.content(user.getName()) .content(user.getName() + Translator.get("user.add.project") + ":" + projectNames)
.path("/system/user/add-project-member") .path("/system/user/add-project-member")
.modifiedValue(JSON.toJSONBytes(request.getRoleIds())) .modifiedValue(JSON.toJSONBytes(request.getRoleIds()))
.build().getLogDTO(); .build().getLogDTO();
@ -166,20 +184,56 @@ public class UserLogService {
operationLogService.batchAdd(logs); operationLogService.batchAdd(logs);
} }
public void batchAddOrgLog(UserRoleBatchRelationRequest request, String operator) { public void batchAddUserRoleLog(UserRoleBatchRelationRequest request, String operator) {
List<LogDTO> logs = new ArrayList<>(); List<LogDTO> logs = new ArrayList<>();
List<String> userIds = userToolService.getBatchUserIds(request); List<String> userIds = userToolService.getBatchUserIds(request);
List<User> userList = userToolService.selectByIdList(userIds); 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) { for (User user : userList) {
//用户管理处修改了用户的组织 //用户管理处修改了用户的组织
LogDTO log = LogDTOBuilder.builder() LogDTO log = LogDTOBuilder.builder()
.projectId(OperationLogConstants.SYSTEM) .projectId(OperationLogConstants.SYSTEM)
.module(OperationLogModule.SYSTEM_USER) .module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.createUser(operator) .createUser(operator)
.organizationId(OperationLogConstants.SYSTEM) .organizationId(OperationLogConstants.SYSTEM)
.sourceId(user.getId()) .sourceId(user.getId())
.type(OperationLogType.UPDATE.name()) .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") .path("/system/user/add-org-member")
.method(HttpMethodConstants.POST.name()) .method(HttpMethodConstants.POST.name())
.modifiedValue(JSON.toJSONBytes(request.getRoleIds())) .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.UserRoleMapper;
import io.metersphere.system.mapper.UserRoleRelationMapper; import io.metersphere.system.mapper.UserRoleRelationMapper;
import io.metersphere.system.response.user.UserTableResponse; 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.annotation.Resource;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotEmpty;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -28,7 +25,6 @@ import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils; import org.mybatis.spring.SqlSessionUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -81,11 +77,7 @@ public class UserRoleRelationService {
return logs; return logs;
} }
public void batchSave(@Validated({Created.class, Updated.class}) public void batchSave(List<String> userRoleIdList, List<User> userList) {
@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) {
long operationTime = System.currentTimeMillis(); long operationTime = System.currentTimeMillis();
List<UserRoleRelation> userRoleRelationSaveList = new ArrayList<>(); List<UserRoleRelation> userRoleRelationSaveList = new ArrayList<>();
//添加用户组织关系 //添加用户组织关系
@ -113,11 +105,6 @@ public class UserRoleRelationService {
} }
sqlSession.flushStatements(); sqlSession.flushStatements();
SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory); 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) { 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) @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserControllerTests extends BaseTest { public class UserControllerTests extends BaseTest {
@Resource @Resource
private UserService userService; private UserService userService;
@Resource @Resource
@ -405,7 +404,7 @@ public class UserControllerTests extends BaseTest {
@Order(6) @Order(6)
public void testUserChangeEnableSuccess() throws Exception { public void testUserChangeEnableSuccess() throws Exception {
this.checkUserList(); this.checkUserList();
//单独修改状态 //修改状态关闭
UserCreateInfo userInfo = USER_LIST.get(0); UserCreateInfo userInfo = USER_LIST.get(0);
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setSelectIds(new ArrayList<>() {{ userChangeEnableRequest.setSelectIds(new ArrayList<>() {{
@ -419,6 +418,16 @@ public class UserControllerTests extends BaseTest {
UserDTO userDTO = this.getUserByEmail(userInfo.getEmail()); UserDTO userDTO = this.getUserByEmail(userInfo.getEmail());
Assertions.assertEquals(userDTO.getEnable(), userChangeEnableRequest.isEnable()); 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 @Test
@ -722,8 +731,8 @@ public class UserControllerTests extends BaseTest {
request.getSelectIds().size() * request.getRoleIds().size() request.getSelectIds().size() * request.getRoleIds().size()
); );
//检查日志 //检查日志
for (UserSelectOption option : USER_ROLE_LIST) { for (String userID : request.getSelectIds()) {
this.checkLog(option.getId(), OperationLogType.ADD); this.checkLog(userID, OperationLogType.ADD);
} }
//测试重复添加用户权限预期结果不会额外增加数据 //测试重复添加用户权限预期结果不会额外增加数据
@ -733,10 +742,6 @@ public class UserControllerTests extends BaseTest {
globalUserRoleRelationService.selectByUserIdAndRuleId(request.getSelectIds(), request.getRoleIds()).size(), globalUserRoleRelationService.selectByUserIdAndRuleId(request.getSelectIds(), request.getRoleIds()).size(),
request.getSelectIds().size() * request.getRoleIds().size() request.getSelectIds().size() * request.getRoleIds().size()
); );
//检查日志
for (UserSelectOption option : USER_ROLE_LIST) {
this.checkLog(option.getId(), OperationLogType.ADD);
}
} }
@Test @Test
@ -771,6 +776,32 @@ public class UserControllerTests extends BaseTest {
userRequestUtils.requestPost(UserRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER); 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 @Test
@Order(10) @Order(10)
@Sql(scripts = {"/dml/init_user_org_project.sql"}, @Sql(scripts = {"/dml/init_user_org_project.sql"},
@ -834,8 +865,8 @@ public class UserControllerTests extends BaseTest {
} }
} }
//检查日志 //检查日志
for (UserSelectOption option : USER_ROLE_LIST) { for (String userID : request.getSelectIds()) {
this.checkLog(option.getId(), OperationLogType.ADD); this.checkLog(userID, OperationLogType.UPDATE);
} }
//检查用户表格不会加载出来非全局用户组 //检查用户表格不会加载出来非全局用户组
this.testPageSuccess(); this.testPageSuccess();