feat(系统设置): 用户管理支持跨页批量操作

This commit is contained in:
song-tianyang 2023-08-11 18:08:54 +08:00 committed by 建国
parent 28a9338a85
commit bd37fe78a0
19 changed files with 364 additions and 168 deletions

View File

@ -22,10 +22,10 @@ public interface BaseUserMapper {
List<User> selectUserIdByEmailList(@Param("emailList") List<String> emailList); List<User> selectUserIdByEmailList(@Param("emailList") List<String> emailList);
List<User> selectByKeyword(String keyword); List<User> selectByKeyword(@Param("keyword") String keyword, @Param("selectId") boolean selectId);
List<String> selectUnDeletedUserIdByIdList(@Param("idList") List<String> userIdList); List<String> selectUnDeletedUserIdByIdList(@Param("idList") List<String> userIdList);
long deleteUser(String id); long deleteUser(String id, String deleteUser, long deleteTime);
List<OptionDTO> selectUserOptionByIds(List<String> userIds); List<OptionDTO> selectUserOptionByIds(List<String> userIds);
} }

View File

@ -2,7 +2,12 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="io.metersphere.sdk.mapper.BaseUserMapper"> <mapper namespace="io.metersphere.sdk.mapper.BaseUserMapper">
<update id="deleteUser"> <update id="deleteUser">
UPDATE `user` SET `deleted` = 1, `email` = id WHERE `id` = #{id} UPDATE `user`
SET `deleted` = 1,
update_user = #{deleteUser},
update_time = #{deleteTime},
`email` = id
WHERE `id` = #{id}
</update> </update>
<select id="selectById" resultType="io.metersphere.sdk.dto.UserDTO"> <select id="selectById" resultType="io.metersphere.sdk.dto.UserDTO">
SELECT * SELECT *
@ -56,7 +61,13 @@
</foreach> </foreach>
</select> </select>
<select id="selectByKeyword" resultType="io.metersphere.system.domain.User"> <select id="selectByKeyword" resultType="io.metersphere.system.domain.User">
SELECT * SELECT
<if test="selectId">
id
</if>
<if test="!selectId">
*
</if>
FROM user FROM user
WHERE DELETED IS FALSE WHERE DELETED IS FALSE
<if test="keyword != null and keyword != ''"> <if test="keyword != null and keyword != ''">

View File

@ -80,6 +80,7 @@ test_resource_pool.type.not_blank=Test resource pool type must not be blank
test_resource_pool.type.length_range=Test resource pool type must be between {min} and {max} characters long test_resource_pool.type.length_range=Test resource pool type must be between {min} and {max} characters long
test_resource_pool.status.not_blank=Test resource pool status must not be blank 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.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=User name must not be blank
user.name.length_range=User name must be between {min} and {max} characters long user.name.length_range=User name must be between {min} and {max} characters long

View File

@ -80,6 +80,7 @@ test_resource_pool.type.not_blank=资源池类型不能为空
test_resource_pool.type.length_range=资源池类型长度必须在{min}和{max}之间 test_resource_pool.type.length_range=资源池类型长度必须在{min}和{max}之间
test_resource_pool.status.not_blank=资源池状态不能为空 test_resource_pool.status.not_blank=资源池状态不能为空
test_resource_pool.status.length_range=资源池状态长度必须在{min}和{max}之间 test_resource_pool.status.length_range=资源池状态长度必须在{min}和{max}之间
user.not.delete=用户不能删除
user.id.not_blank=用户ID不能为空 user.id.not_blank=用户ID不能为空
user.name.not_blank=用户名称不能为空 user.name.not_blank=用户名称不能为空
user.name.length_range=用户名称长度必须在{min}和{max}之间 user.name.length_range=用户名称长度必须在{min}和{max}之间

View File

@ -80,6 +80,7 @@ test_resource_pool.type.not_blank=資源池類型不能為空
test_resource_pool.type.length_range=資源池類型長度必須在{min}和{max}之間 test_resource_pool.type.length_range=資源池類型長度必須在{min}和{max}之間
test_resource_pool.status.not_blank=資源池狀態不能為空 test_resource_pool.status.not_blank=資源池狀態不能為空
test_resource_pool.status.length_range=資源池狀態長度必須在{min}和{max}之間 test_resource_pool.status.length_range=資源池狀態長度必須在{min}和{max}之間
user.not.delete=用戶不能刪除
user.id.not_blank=用戶ID不能為空 user.id.not_blank=用戶ID不能為空
user.name.not_blank=用戶名稱不能為空 user.name.not_blank=用戶名稱不能為空
user.name.length_range=用戶名稱長度必須在{min}和{max}之間 user.name.length_range=用戶名稱長度必須在{min}和{max}之間

View File

@ -4,7 +4,6 @@ import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import io.metersphere.sdk.constants.PermissionConstants; import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.dto.UserRoleRelationUserDTO; import io.metersphere.sdk.dto.UserRoleRelationUserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest;
import io.metersphere.sdk.log.annotation.Log; import io.metersphere.sdk.log.annotation.Log;
import io.metersphere.sdk.log.constants.OperationLogType; import io.metersphere.sdk.log.constants.OperationLogType;
@ -12,6 +11,7 @@ import io.metersphere.sdk.util.PageUtils;
import io.metersphere.sdk.util.Pager; import io.metersphere.sdk.util.Pager;
import io.metersphere.sdk.util.SessionUtils; import io.metersphere.sdk.util.SessionUtils;
import io.metersphere.system.dto.request.GlobalUserRoleRelationQueryRequest; import io.metersphere.system.dto.request.GlobalUserRoleRelationQueryRequest;
import io.metersphere.system.dto.request.user.UserAndRoleBatchRequest;
import io.metersphere.system.service.GlobalUserRoleRelationLogService; import io.metersphere.system.service.GlobalUserRoleRelationLogService;
import io.metersphere.system.service.GlobalUserRoleRelationService; import io.metersphere.system.service.GlobalUserRoleRelationService;
import io.metersphere.validation.groups.Created; import io.metersphere.validation.groups.Created;
@ -54,11 +54,11 @@ public class GlobalUserRoleRelationController {
} }
//用户管理页面批量添加用户到多个用户组 权限所属是用户管理的编辑页面权限 //用户管理页面批量添加用户到多个用户组 权限所属是用户管理的编辑页面权限
@PostMapping("/add/batch") @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) @Log(type = OperationLogType.ADD, expression = "#msClass.batchAddLog(#request)", msClass = GlobalUserRoleRelationLogService.class)
public void batchAdd(@Validated({Created.class}) @RequestBody GlobalUserRoleRelationBatchRequest request) { public void batchAdd(@Validated({Created.class}) @RequestBody UserAndRoleBatchRequest request) {
globalUserRoleRelationService.batchAdd(request, SessionUtils.getUserId()); globalUserRoleRelationService.batchAdd(request, SessionUtils.getUserId());
} }

View File

@ -16,11 +16,15 @@ import io.metersphere.system.domain.User;
import io.metersphere.system.dto.UserBatchCreateDTO; import io.metersphere.system.dto.UserBatchCreateDTO;
import io.metersphere.system.dto.UserExtend; import io.metersphere.system.dto.UserExtend;
import io.metersphere.system.dto.UserRoleOption; import io.metersphere.system.dto.UserRoleOption;
import io.metersphere.system.dto.request.UserBaseBatchRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest; import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.dto.request.UserEditRequest; import io.metersphere.system.dto.request.UserEditRequest;
import io.metersphere.system.dto.request.user.UserAndRoleBatchRequest;
import io.metersphere.system.dto.response.UserBatchProcessResponse; import io.metersphere.system.dto.response.UserBatchProcessResponse;
import io.metersphere.system.dto.response.UserImportResponse; import io.metersphere.system.dto.response.UserImportResponse;
import io.metersphere.system.dto.response.UserTableResponse; import io.metersphere.system.dto.response.UserTableResponse;
import io.metersphere.system.service.GlobalUserRoleRelationLogService;
import io.metersphere.system.service.GlobalUserRoleRelationService;
import io.metersphere.system.service.GlobalUserRoleService; import io.metersphere.system.service.GlobalUserRoleService;
import io.metersphere.system.service.UserService; import io.metersphere.system.service.UserService;
import io.metersphere.validation.groups.Created; import io.metersphere.validation.groups.Created;
@ -45,17 +49,19 @@ public class UserController {
private UserService userService; private UserService userService;
@Resource @Resource
private GlobalUserRoleService globalUserRoleService; private GlobalUserRoleService globalUserRoleService;
@Resource
private GlobalUserRoleRelationService globalUserRoleRelationService;
@GetMapping("/get/{email}") @GetMapping("/get/{email}")
@Operation(summary = "通过email查找用户") @Operation(summary = "通过email查找用户")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_READ) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ)
public UserDTO getUser(@PathVariable String email) { public UserDTO getUser(@PathVariable String email) {
return userService.getUserDTOByEmail(email); return userService.getUserDTOByEmail(email);
} }
@GetMapping("/get/global/system/role") @GetMapping("/get/global/system/role")
@Operation(summary = "查找系统级用户权限") @Operation(summary = "查找系统级用户权限")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_ADD) @RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_READ)
public List<UserRoleOption> getGlobalSystemRole() { public List<UserRoleOption> getGlobalSystemRole() {
return globalUserRoleService.getGlobalSystemRoleList(); return globalUserRoleService.getGlobalSystemRoleList();
} }
@ -87,6 +93,7 @@ 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 = UserService.class)
public UserBatchProcessResponse updateUserEnable(@Validated @RequestBody UserChangeEnableRequest request) { public UserBatchProcessResponse updateUserEnable(@Validated @RequestBody UserChangeEnableRequest request) {
return userService.updateUserEnable(request, SessionUtils.getSessionId()); return userService.updateUserEnable(request, SessionUtils.getSessionId());
} }
@ -100,10 +107,10 @@ public class UserController {
@PostMapping("/delete") @PostMapping("/delete")
@Operation(summary = "删除用户") @Operation(summary = "删除用户")
@Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#userBatchProcessRequest)", msClass = UserService.class) @Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#request)", msClass = UserService.class)
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_DELETE) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_DELETE)
public UserBatchProcessResponse deleteUser(@Validated @RequestBody UserChangeEnableRequest userBatchProcessRequest) { public UserBatchProcessResponse deleteUser(@Validated @RequestBody UserBaseBatchRequest request) {
return userService.deleteUser(userBatchProcessRequest.getUserIdList()); return userService.deleteUser(request, SessionUtils.getUserId());
} }
@GetMapping("/list") @GetMapping("/list")
@ -116,10 +123,9 @@ 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(#userId)", msClass = UserService.class) @Log(type = OperationLogType.UPDATE, expression = "#msClass.resetPasswordLog(#request)", msClass = UserService.class)
public boolean resetPassword(@RequestBody String userId) { public UserBatchProcessResponse resetPassword(@Validated @RequestBody UserBaseBatchRequest request) {
userService.resetPassword(userId, SessionUtils.getUserId()); return userService.resetPassword(request, SessionUtils.getUserId());
return true;
} }
@GetMapping("/get-option/{sourceId}") @GetMapping("/get-option/{sourceId}")
@ -129,4 +135,12 @@ public class UserController {
public List<UserExtend> getMemberOption(@PathVariable String sourceId) { public List<UserExtend> getMemberOption(@PathVariable String sourceId) {
return userService.getMemberOption(sourceId); return userService.getMemberOption(sourceId);
} }
@PostMapping("/add/batch/user-role")
@Operation(summary = "批量添加用户到多个用户组中")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.ADD, expression = "#msClass.batchAddLog(#request)", msClass = GlobalUserRoleRelationLogService.class)
public UserBatchProcessResponse batchAdd(@Validated({Created.class}) @RequestBody UserAndRoleBatchRequest request) {
return globalUserRoleRelationService.batchAdd(request, SessionUtils.getUserId());
}
} }

View File

@ -0,0 +1,32 @@
package io.metersphere.system.dto.request;
import io.metersphere.system.dto.request.user.BaseCondition;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.List;
@Data
public class UserBaseBatchRequest {
@Schema(description = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED)
@Valid
private List<
@NotBlank(message = "{user_role_relation.user_id.not_blank}", groups = {Created.class, Updated.class})
@Size(min = 1, max = 50, message = "{user_role_relation.user_id.length_range}", groups = {Created.class, Updated.class})
String
> userIds;
@Schema(description = "不处理的用户ID")
List<String> skipIds;
@Schema(description = "是否选择所有数据")
private boolean selectAll;
@Schema(description = "查询条件")
private BaseCondition condition = new BaseCondition();
}

View File

@ -1,15 +0,0 @@
package io.metersphere.system.dto.request;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class UserBatchProcessRequest {
@Schema(description = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "{user.not.empty}")
List<String> userIdList = new ArrayList<>();
}

View File

@ -1,10 +1,12 @@
package io.metersphere.system.dto.request; package io.metersphere.system.dto.request;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
@Data @Data
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class UserChangeEnableRequest extends UserBatchProcessRequest { public class UserChangeEnableRequest extends UserBaseBatchRequest {
@Schema(description = "禁用/启用", requiredMode = Schema.RequiredMode.REQUIRED)
boolean enable; boolean enable;
} }

View File

@ -0,0 +1,19 @@
package io.metersphere.system.dto.request.user;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class BaseCondition {
@Schema(description = "关键字")
private String keyword;
@Schema(description = "过滤字段")
private Map<String, List<String>> filter;
@Schema(description = "高级搜索")
private Map<String, Object> combine;
}

View File

@ -1,5 +1,6 @@
package io.metersphere.sdk.dto.request; package io.metersphere.system.dto.request.user;
import io.metersphere.system.dto.request.UserBaseBatchRequest;
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.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
@ -12,20 +13,10 @@ import lombok.Data;
import java.util.List; import java.util.List;
@Data @Data
public class GlobalUserRoleRelationBatchRequest { public class UserAndRoleBatchRequest extends UserBaseBatchRequest {
@Schema(description = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "{user_role_relation.user_id.not_blank}", groups = {Created.class, Updated.class})
@Valid
private List<
@NotBlank(message = "{user_role_relation.user_id.not_blank}", groups = {Created.class, Updated.class})
@Size(min = 1, max = 50, message = "{user_role_relation.user_id.length_range}", groups = {Created.class, Updated.class})
String
> userIds;
@Schema(description = "组ID", requiredMode = Schema.RequiredMode.REQUIRED) @Schema(description = "组ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "{user_role_relation.role_id.not_blank}", groups = {Created.class}) @NotEmpty(message = "{user_role_relation.role_id.not_blank}", groups = {Created.class})
@Size(min = 1, max = 50, message = "{user_role_relation.role_id.length_range}", groups = {Created.class, Updated.class})
@Valid @Valid
private List< private List<
@NotBlank(message = "{user_role_relation.role_id.not_blank}", groups = {Created.class, Updated.class}) @NotBlank(message = "{user_role_relation.role_id.not_blank}", groups = {Created.class, Updated.class})
@ -33,4 +24,12 @@ public class GlobalUserRoleRelationBatchRequest {
String String
> roleIds; > roleIds;
@Schema(description = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "{user_role_relation.role_id.not_blank}", groups = {Created.class})
@Valid
private List<
@NotBlank(message = "{user_role_relation.user_id.not_blank}", groups = {Created.class, Updated.class})
@Size(min = 1, max = 50, message = "{user_role_relation.user_id.length_range}", groups = {Created.class, Updated.class})
String
> userIds;
} }

View File

@ -2,8 +2,11 @@ package io.metersphere.system.dto.response;
import lombok.Data; import lombok.Data;
import java.util.List;
@Data @Data
public class UserBatchProcessResponse { public class UserBatchProcessResponse {
private long totalCount; private long totalCount;
private long successCount; private long successCount;
private List<String> processedIds;
} }

View File

@ -4,7 +4,6 @@ import io.metersphere.sdk.constants.OperationLogConstants;
import io.metersphere.sdk.dto.LogDTO; import io.metersphere.sdk.dto.LogDTO;
import io.metersphere.sdk.dto.OptionDTO; import io.metersphere.sdk.dto.OptionDTO;
import io.metersphere.sdk.dto.UserDTO; import io.metersphere.sdk.dto.UserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest;
import io.metersphere.sdk.log.constants.OperationLogModule; import io.metersphere.sdk.log.constants.OperationLogModule;
import io.metersphere.sdk.log.constants.OperationLogType; import io.metersphere.sdk.log.constants.OperationLogType;
@ -13,6 +12,7 @@ import io.metersphere.sdk.util.JSON;
import io.metersphere.system.domain.UserRole; import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRoleExample; import io.metersphere.system.domain.UserRoleExample;
import io.metersphere.system.domain.UserRoleRelation; import io.metersphere.system.domain.UserRoleRelation;
import io.metersphere.system.dto.request.user.UserAndRoleBatchRequest;
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 jakarta.annotation.Resource; import jakarta.annotation.Resource;
@ -58,7 +58,7 @@ public class GlobalUserRoleRelationLogService {
return dto; return dto;
} }
public List<LogDTO> batchAddLog(GlobalUserRoleRelationBatchRequest request) { public List<LogDTO> batchAddLog(UserAndRoleBatchRequest request) {
UserRoleExample example = new UserRoleExample(); UserRoleExample example = new UserRoleExample();
example.createCriteria().andIdIn(request.getRoleIds()); example.createCriteria().andIdIn(request.getRoleIds());
List<UserRole> userRoles = userRoleMapper.selectByExample(example); List<UserRole> userRoles = userRoleMapper.selectByExample(example);

View File

@ -1,7 +1,6 @@
package io.metersphere.system.service; package io.metersphere.system.service;
import io.metersphere.sdk.dto.UserRoleRelationUserDTO; import io.metersphere.sdk.dto.UserRoleRelationUserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest;
import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.service.BaseUserRoleRelationService; import io.metersphere.sdk.service.BaseUserRoleRelationService;
@ -12,6 +11,8 @@ import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRoleRelation; import io.metersphere.system.domain.UserRoleRelation;
import io.metersphere.system.domain.UserRoleRelationExample; import io.metersphere.system.domain.UserRoleRelationExample;
import io.metersphere.system.dto.request.GlobalUserRoleRelationQueryRequest; import io.metersphere.system.dto.request.GlobalUserRoleRelationQueryRequest;
import io.metersphere.system.dto.request.user.UserAndRoleBatchRequest;
import io.metersphere.system.dto.response.UserBatchProcessResponse;
import io.metersphere.system.mapper.ExtUserRoleRelationMapper; import io.metersphere.system.mapper.ExtUserRoleRelationMapper;
import io.metersphere.validation.groups.Created; import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated; import io.metersphere.validation.groups.Updated;
@ -83,9 +84,11 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService {
return userRoleRelationMapper.selectByExample(example); return userRoleRelationMapper.selectByExample(example);
} }
public void batchAdd(@Validated({Created.class, Updated.class}) GlobalUserRoleRelationBatchRequest request, String operator) { public UserBatchProcessResponse batchAdd(@Validated({Created.class, Updated.class}) UserAndRoleBatchRequest request, String operator) {
//检查角色的合法性 //检查角色的合法性
this.checkGlobalSystemUserRoleLegality(request.getRoleIds()); this.checkGlobalSystemUserRoleLegality(request.getRoleIds());
//获取本次处理的用户
request.setUserIds(userService.getBatchUserIds(request));
//检查用户的合法性 //检查用户的合法性
userService.checkUserLegality(request.getUserIds()); userService.checkUserLegality(request.getUserIds());
List<UserRoleRelation> savedUserRoleRelation = this.selectByUserIdAndRuleId(request.getUserIds(), request.getRoleIds()); List<UserRoleRelation> savedUserRoleRelation = this.selectByUserIdAndRuleId(request.getUserIds(), request.getRoleIds());
@ -112,7 +115,11 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService {
if (CollectionUtils.isNotEmpty(saveList)) { if (CollectionUtils.isNotEmpty(saveList)) {
userRoleRelationMapper.batchInsert(saveList); userRoleRelationMapper.batchInsert(saveList);
} }
UserBatchProcessResponse response = new UserBatchProcessResponse();
response.setTotalCount(request.getUserIds().size());
response.setSuccessCount(saveList.size());
response.setProcessedIds(saveList.stream().map(UserRoleRelation::getUserId).collect(Collectors.toList()));
return response;
} }
@Override @Override

View File

@ -20,6 +20,7 @@ import io.metersphere.system.dto.UserCreateInfo;
import io.metersphere.system.dto.UserExtend; import io.metersphere.system.dto.UserExtend;
import io.metersphere.system.dto.excel.UserExcel; import io.metersphere.system.dto.excel.UserExcel;
import io.metersphere.system.dto.excel.UserExcelRowDTO; import io.metersphere.system.dto.excel.UserExcelRowDTO;
import io.metersphere.system.dto.request.UserBaseBatchRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest; import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.dto.request.UserEditRequest; import io.metersphere.system.dto.request.UserEditRequest;
import io.metersphere.system.dto.response.UserBatchProcessResponse; import io.metersphere.system.dto.response.UserBatchProcessResponse;
@ -166,7 +167,7 @@ public class UserService {
public List<UserTableResponse> list(BasePageRequest request) { public List<UserTableResponse> list(BasePageRequest request) {
List<UserTableResponse> returnList = new ArrayList<>(); List<UserTableResponse> returnList = new ArrayList<>();
List<User> userList = baseUserMapper.selectByKeyword(request.getKeyword()); List<User> userList = baseUserMapper.selectByKeyword(request.getKeyword(), false);
List<String> userIdList = userList.stream().map(User::getId).collect(Collectors.toList()); List<String> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
Map<String, UserTableResponse> roleAndOrganizationMap = userRoleRelationService.selectGlobalUserRoleAndOrganization(userIdList); Map<String, UserTableResponse> roleAndOrganizationMap = userRoleRelationService.selectGlobalUserRoleAndOrganization(userIdList);
for (User user : userList) { for (User user : userList) {
@ -197,24 +198,27 @@ public class UserService {
} }
public UserBatchProcessResponse updateUserEnable(UserChangeEnableRequest request, String operator) { public UserBatchProcessResponse updateUserEnable(UserChangeEnableRequest request, String operator) {
this.checkUserInDb(request.getUserIdList()); request.setUserIds(this.getBatchUserIds(request));
this.checkUserInDb(request.getUserIds());
UserBatchProcessResponse response = new UserBatchProcessResponse(); UserBatchProcessResponse response = new UserBatchProcessResponse();
response.setTotalCount(request.getUserIdList().size()); response.setTotalCount(request.getUserIds().size());
UserExample userExample = new UserExample(); UserExample userExample = new UserExample();
userExample.createCriteria().andIdIn( userExample.createCriteria().andIdIn(
request.getUserIdList() request.getUserIds()
); );
User updateUser = new User(); User updateUser = new User();
updateUser.setEnable(request.isEnable()); updateUser.setEnable(request.isEnable());
updateUser.setUpdateUser(operator); updateUser.setUpdateUser(operator);
updateUser.setUpdateTime(System.currentTimeMillis()); updateUser.setUpdateTime(System.currentTimeMillis());
response.setSuccessCount(userMapper.updateByExampleSelective(updateUser, userExample)); response.setSuccessCount(userMapper.updateByExampleSelective(updateUser, userExample));
response.setProcessedIds(request.getUserIds());
return response; return response;
} }
private void checkUserInDb(@Valid @NotEmpty List<String> userIdList) { private void checkUserInDb(List<String> userIdList) {
if (CollectionUtils.isEmpty(userIdList)) {
throw new MSException(Translator.get("user.not.exist"));
}
List<String> userInDb = baseUserMapper.selectUnDeletedUserIdByIdList(userIdList); List<String> userInDb = baseUserMapper.selectUnDeletedUserIdByIdList(userIdList);
if (userIdList.size() != userInDb.size()) { if (userIdList.size() != userInDb.size()) {
throw new MSException(Translator.get("user.not.exist")); throw new MSException(Translator.get("user.not.exist"));
@ -238,15 +242,12 @@ public class UserService {
public ExcelParseDTO<UserExcelRowDTO> getUserExcelParseDTO(MultipartFile excelFile) throws Exception { public ExcelParseDTO<UserExcelRowDTO> getUserExcelParseDTO(MultipartFile excelFile) throws Exception {
UserImportEventListener userImportEventListener = new UserImportEventListener(); UserImportEventListener userImportEventListener = new UserImportEventListener();
EasyExcelFactory.read(excelFile.getInputStream(), UserExcel.class, userImportEventListener).sheet().doRead(); EasyExcelFactory.read(excelFile.getInputStream(), UserExcel.class, userImportEventListener).sheet().doRead();
ExcelParseDTO<UserExcelRowDTO> excelParseDTO = this.validateExcelUserInfo(userImportEventListener.getExcelParseDTO()); return this.validateExcelUserInfo(userImportEventListener.getExcelParseDTO());
return excelParseDTO;
} }
/** /**
* 校验excel导入的数据是否与数据库中的数据冲突 * 校验excel导入的数据是否与数据库中的数据冲突
* *
* @param excelParseDTO
* @return
*/ */
private ExcelParseDTO<UserExcelRowDTO> validateExcelUserInfo(@Valid @NotNull ExcelParseDTO<UserExcelRowDTO> excelParseDTO) { private ExcelParseDTO<UserExcelRowDTO> validateExcelUserInfo(@Valid @NotNull ExcelParseDTO<UserExcelRowDTO> excelParseDTO) {
List<UserExcelRowDTO> prepareSaveList = excelParseDTO.getDataList(); List<UserExcelRowDTO> prepareSaveList = excelParseDTO.getDataList();
@ -282,27 +283,38 @@ public class UserService {
} }
public UserBatchProcessResponse deleteUser(@Valid @NotEmpty List<String> userIdList) { public UserBatchProcessResponse deleteUser(@Valid UserBaseBatchRequest request, String operator) {
List<String> userIdList = this.getBatchUserIds(request);
this.checkUserInDb(userIdList); this.checkUserInDb(userIdList);
//检查是否含有Admin
UserBatchProcessResponse response = new UserBatchProcessResponse(); this.checkAdminAndThrowException(userIdList);
response.setTotalCount(userIdList.size());
UserExample userExample = new UserExample(); UserExample userExample = new UserExample();
userExample.createCriteria().andIdIn(userIdList); userExample.createCriteria().andIdIn(userIdList);
//更新删除标志位 //更新删除标志位
response.setSuccessCount(this.deleteUserByList(userIdList)); UserBatchProcessResponse response = new UserBatchProcessResponse();
response.setTotalCount(userIdList.size());
response.setProcessedIds(userIdList);
response.setSuccessCount(this.deleteUserByList(userIdList, operator));
//删除用户角色关系 //删除用户角色关系
userRoleRelationService.deleteByUserIdList(userIdList); userRoleRelationService.deleteByUserIdList(userIdList);
return response; return response;
} }
private int deleteUserByList(List<String> updateUserList) { private void checkAdminAndThrowException(List<String> userIdList) {
for (String userId : userIdList) {
if (userId.equals("admin")) {
throw new MSException(Translator.get("user.not.delete"));
}
}
}
private int deleteUserByList(List<String> updateUserList, String operator) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
BaseUserMapper batchDeleteMapper = sqlSession.getMapper(BaseUserMapper.class); BaseUserMapper batchDeleteMapper = sqlSession.getMapper(BaseUserMapper.class);
int insertIndex = 0; int insertIndex = 0;
long deleteTime = System.currentTimeMillis();
for (String userId : updateUserList) { for (String userId : updateUserList) {
batchDeleteMapper.deleteUser(userId); batchDeleteMapper.deleteUser(userId, operator, deleteTime);
insertIndex++; insertIndex++;
if (insertIndex % 50 == 0) { if (insertIndex % 50 == 0) {
sqlSession.flushStatements(); sqlSession.flushStatements();
@ -323,8 +335,7 @@ public class UserService {
null, null,
OperationLogType.UPDATE.name(), OperationLogType.UPDATE.name(),
OperationLogModule.SYSTEM_USER, OperationLogModule.SYSTEM_USER,
request.getName()); JSON.toJSONString(user));
dto.setPath("/update"); dto.setPath("/update");
dto.setMethod(HttpMethodConstants.POST.name()); dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(user)); dto.setOriginalValue(JSON.toJSONBytes(user));
@ -333,13 +344,40 @@ public class UserService {
return null; return null;
} }
public LogDTO resetPasswordLog(String userId) { public List<LogDTO> batchUpdateLog(UserBaseBatchRequest request) {
User user = userMapper.selectByPrimaryKey(userId); List<LogDTO> logDTOList = new ArrayList<>();
if (user != null) { request.setUserIds(this.getBatchUserIds(request));
List<User> userList = this.selectByIdList(request.getUserIds());
for (User user : userList) {
LogDTO dto = new LogDTO( LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM, OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM, OperationLogConstants.SYSTEM,
userId, user.getId(),
null,
OperationLogType.UPDATE.name(),
OperationLogModule.SYSTEM_USER,
JSON.toJSONString(user));
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(user));
logDTOList.add(dto);
}
return logDTOList;
}
/**
* @param request 批量重置密码 用于记录Log使用
*/
public List<LogDTO> resetPasswordLog(UserBaseBatchRequest request) {
request.setUserIds(this.getBatchUserIds(request));
List<LogDTO> returnList = new ArrayList<>();
UserExample example = new UserExample();
example.createCriteria().andIdIn(request.getUserIds());
List<User> userList = userMapper.selectByExample(example);
for (User user : userList) {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
user.getId(),
null, null,
OperationLogType.UPDATE.name(), OperationLogType.UPDATE.name(),
OperationLogModule.SYSTEM_USER, OperationLogModule.SYSTEM_USER,
@ -347,14 +385,14 @@ public class UserService {
dto.setPath("/reset/password"); dto.setPath("/reset/password");
dto.setMethod(HttpMethodConstants.POST.name()); dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(user)); dto.setOriginalValue(JSON.toJSONBytes(user));
return dto; returnList.add(dto);
} }
return null; return returnList;
} }
public List<LogDTO> deleteLog(UserChangeEnableRequest request) { public List<LogDTO> deleteLog(UserBaseBatchRequest request) {
List<LogDTO> logDTOList = new ArrayList<>(); List<LogDTO> logDTOList = new ArrayList<>();
request.getUserIdList().forEach(item -> { request.getUserIds().forEach(item -> {
User user = userMapper.selectByPrimaryKey(item); User user = userMapper.selectByPrimaryKey(item);
if (user != null) { if (user != null) {
@ -386,21 +424,39 @@ public class UserService {
return extUserMapper.getMemberOption(sourceId); return extUserMapper.getMemberOption(sourceId);
} }
public void resetPassword(String userId, String operator) { public UserBatchProcessResponse resetPassword(UserBaseBatchRequest request, String operator) {
User user = userMapper.selectByPrimaryKey(userId); request.setUserIds(this.getBatchUserIds(request));
if (user == null) { this.checkUserInDb(request.getUserIds());
throw new MSException(Translator.get("user.not.exist"));
} SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserMapper batchUpdateMapper = sqlSession.getMapper(UserMapper.class);
int insertIndex = 0;
long updateTime = System.currentTimeMillis();
List<User> userList = this.selectByIdList(request.getUserIds());
for (User user : userList) {
User updateModel = new User(); User updateModel = new User();
updateModel.setId(userId); updateModel.setId(user.getId());
if (StringUtils.equalsIgnoreCase("admin", user.getId())) { if (StringUtils.equalsIgnoreCase("admin", user.getId())) {
updateModel.setPassword(CodingUtil.md5("metersphere")); updateModel.setPassword(CodingUtil.md5("metersphere"));
} else { } else {
updateModel.setPassword(CodingUtil.md5(user.getEmail())); updateModel.setPassword(CodingUtil.md5(user.getEmail()));
} }
updateModel.setUpdateTime(System.currentTimeMillis()); updateModel.setUpdateTime(updateTime);
updateModel.setUpdateUser(operator); updateModel.setUpdateUser(operator);
userMapper.updateByPrimaryKeySelective(updateModel); batchUpdateMapper.updateByPrimaryKeySelective(updateModel);
insertIndex++;
if (insertIndex % 50 == 0) {
sqlSession.flushStatements();
}
}
sqlSession.flushStatements();
SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);
UserBatchProcessResponse response = new UserBatchProcessResponse();
response.setTotalCount(request.getUserIds().size());
response.setSuccessCount(request.getUserIds().size());
response.setProcessedIds(request.getUserIds());
return response;
} }
public void checkUserLegality(List<String> userIds) { public void checkUserLegality(List<String> userIds) {
@ -410,4 +466,17 @@ public class UserService {
throw new MSException(Translator.get("user.id.not.exist")); throw new MSException(Translator.get("user.id.not.exist"));
} }
} }
public List<String> getBatchUserIds(UserBaseBatchRequest request) {
if (request.isSelectAll()) {
List<User> userList = baseUserMapper.selectByKeyword(request.getCondition().getKeyword(), true);
List<String> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(request.getSkipIds())) {
userIdList.removeAll(request.getSkipIds());
}
return userIdList;
} else {
return request.getUserIds();
}
}
} }

View File

@ -1,11 +1,11 @@
package io.metersphere.system.controller.user; package io.metersphere.system.controller.user;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.system.dto.UserCreateInfo; import io.metersphere.system.dto.UserCreateInfo;
import io.metersphere.system.dto.UserRoleOption; import io.metersphere.system.dto.UserRoleOption;
import io.metersphere.system.dto.request.UserBatchProcessRequest; import io.metersphere.system.dto.request.UserBaseBatchRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest; import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.dto.request.user.UserAndRoleBatchRequest;
import io.metersphere.system.utils.user.UserParamUtils; import io.metersphere.system.utils.user.UserParamUtils;
import io.metersphere.system.utils.user.UserRequestUtils; import io.metersphere.system.utils.user.UserRequestUtils;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
@ -22,6 +22,7 @@ import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@ -84,7 +85,7 @@ public class UserControllerNonePermissionTests {
//校验权限启用/禁用用户 //校验权限启用/禁用用户
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setEnable(false); userChangeEnableRequest.setEnable(false);
userChangeEnableRequest.setUserIdList(new ArrayList<>() {{ userChangeEnableRequest.setUserIds(new ArrayList<>() {{
this.add("testId"); this.add("testId");
}}); }});
userRequestUtils.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, CHECK_RESULT_MATHER); userRequestUtils.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, CHECK_RESULT_MATHER);
@ -95,17 +96,19 @@ public class UserControllerNonePermissionTests {
MockMultipartFile file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath)); MockMultipartFile file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
userRequestUtils.requestFile(userRequestUtils.URL_USER_IMPORT, file, CHECK_RESULT_MATHER); userRequestUtils.requestFile(userRequestUtils.URL_USER_IMPORT, file, CHECK_RESULT_MATHER);
//用户删除 //用户删除
UserBatchProcessRequest request = new UserBatchProcessRequest(); UserBaseBatchRequest request = new UserBaseBatchRequest();
request.setUserIdList(new ArrayList<>() {{ request.setUserIds(new ArrayList<>() {{
this.add("testId"); this.add("testId");
}}); }});
userRequestUtils.requestPost(userRequestUtils.URL_USER_DELETE, request, CHECK_RESULT_MATHER); userRequestUtils.requestPost(userRequestUtils.URL_USER_DELETE, request, CHECK_RESULT_MATHER);
//重置密码 //重置密码
userRequestUtils.requestPostString(userRequestUtils.URL_USER_RESET_PASSWORD, NONE_ROLE_USERNAME, CHECK_RESULT_MATHER); request = new UserBaseBatchRequest();
request.setUserIds(Collections.singletonList("admin"));
userRequestUtils.requestPost(userRequestUtils.URL_USER_RESET_PASSWORD, request, CHECK_RESULT_MATHER);
//添加用户到用户组 //添加用户到用户组
GlobalUserRoleRelationBatchRequest userRoleRelationRequest = new GlobalUserRoleRelationBatchRequest(); UserAndRoleBatchRequest userRoleRelationRequest = new UserAndRoleBatchRequest();
userRoleRelationRequest.setUserIds(new ArrayList<>() {{ userRoleRelationRequest.setUserIds(new ArrayList<>() {{
this.add(NONE_ROLE_USERNAME); this.add(NONE_ROLE_USERNAME);
}}); }});

View File

@ -5,7 +5,6 @@ import io.metersphere.sdk.controller.handler.ResultHolder;
import io.metersphere.sdk.dto.BasePageRequest; import io.metersphere.sdk.dto.BasePageRequest;
import io.metersphere.sdk.dto.ExcelParseDTO; import io.metersphere.sdk.dto.ExcelParseDTO;
import io.metersphere.sdk.dto.UserDTO; import io.metersphere.sdk.dto.UserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.log.constants.OperationLogType; import io.metersphere.sdk.log.constants.OperationLogType;
import io.metersphere.sdk.util.BeanUtils; import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.CodingUtil; import io.metersphere.sdk.util.CodingUtil;
@ -17,9 +16,10 @@ import io.metersphere.system.dto.UserBatchCreateDTO;
import io.metersphere.system.dto.UserCreateInfo; import io.metersphere.system.dto.UserCreateInfo;
import io.metersphere.system.dto.UserRoleOption; import io.metersphere.system.dto.UserRoleOption;
import io.metersphere.system.dto.excel.UserExcelRowDTO; import io.metersphere.system.dto.excel.UserExcelRowDTO;
import io.metersphere.system.dto.request.UserBatchProcessRequest; import io.metersphere.system.dto.request.UserBaseBatchRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest; import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.dto.request.UserEditRequest; import io.metersphere.system.dto.request.UserEditRequest;
import io.metersphere.system.dto.request.user.UserAndRoleBatchRequest;
import io.metersphere.system.dto.response.UserBatchProcessResponse; import io.metersphere.system.dto.response.UserBatchProcessResponse;
import io.metersphere.system.dto.response.UserImportResponse; import io.metersphere.system.dto.response.UserImportResponse;
import io.metersphere.system.dto.response.UserTableResponse; import io.metersphere.system.dto.response.UserTableResponse;
@ -469,12 +469,12 @@ public class UserControllerTests extends BaseTest {
//单独修改状态 //单独修改状态
UserCreateInfo userInfo = USER_LIST.get(0); UserCreateInfo userInfo = USER_LIST.get(0);
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setUserIdList(new ArrayList<>() {{ userChangeEnableRequest.setUserIds(new ArrayList<>() {{
this.add(userInfo.getId()); this.add(userInfo.getId());
}}); }});
userChangeEnableRequest.setEnable(false); userChangeEnableRequest.setEnable(false);
this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk()); this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk());
for (String item : userChangeEnableRequest.getUserIdList()) { for (String item : userChangeEnableRequest.getUserIds()) {
checkLog(item, OperationLogType.UPDATE); checkLog(item, OperationLogType.UPDATE);
} }
@ -491,7 +491,7 @@ public class UserControllerTests extends BaseTest {
userChangeEnableRequest.setEnable(false); userChangeEnableRequest.setEnable(false);
this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, BAD_REQUEST_MATCHER);
//含有非法用户 //含有非法用户
userChangeEnableRequest.setUserIdList(new ArrayList<>() {{ userChangeEnableRequest.setUserIds(new ArrayList<>() {{
this.add("BCDEDIT"); this.add("BCDEDIT");
}}); }});
this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, ERROR_REQUEST_MATCHER);
@ -584,21 +584,69 @@ public class UserControllerTests extends BaseTest {
@Order(8) @Order(8)
public void testUserResetPasswordSuccess() throws Exception { public void testUserResetPasswordSuccess() throws Exception {
this.checkUserList(); this.checkUserList();
String userId = USER_LIST.get(0).getId();
String userEmail = USER_LIST.get(0).getEmail();
//重置普通用户密码
this.resetPasswordAndCheck(userId, userEmail);
this.checkLog(userId, OperationLogType.UPDATE);
//重置admin的密码 //重置admin的密码
this.resetPasswordAndCheck("admin", "metersphere"); {
this.checkLog(userId, OperationLogType.UPDATE); UserBaseBatchRequest request = new UserBaseBatchRequest();
request.setUserIds(Collections.singletonList("admin"));
userRequestUtils.parseObjectFromMvcResult(
this.requestPostAndReturn(userRequestUtils.URL_USER_RESET_PASSWORD, request),
UserBatchProcessResponse.class
);
//检查数据库
UserExample userExample = new UserExample();
userExample.createCriteria().andIdEqualTo("admin").andPasswordEqualTo(CodingUtil.md5("metersphere"));
Assertions.assertEquals(1, userMapper.countByExample(userExample));
this.checkLog("admin", OperationLogType.UPDATE);
}
//重置普通用户密码
{
User paramUser = new User();
String userId = USER_LIST.get(0).getId();
paramUser.setId(userId);
paramUser.setPassword("I can't say any dirty words");
Assertions.assertEquals(1, userMapper.updateByPrimaryKeySelective(paramUser));
UserBaseBatchRequest request = new UserBaseBatchRequest();
request.setUserIds(Collections.singletonList(userId));
UserBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult(
this.requestPostAndReturn(userRequestUtils.URL_USER_RESET_PASSWORD, request),
UserBatchProcessResponse.class
);
List<User> userList = userService.selectByIdList(response.getProcessedIds());
for (User checkUser : userList) {
UserExample userExample = new UserExample();
userExample.createCriteria().andIdEqualTo(checkUser.getId()).andPasswordEqualTo(CodingUtil.md5(checkUser.getEmail()));
Assertions.assertEquals(1, userMapper.countByExample(userExample));
this.checkLog(checkUser.getId(), OperationLogType.UPDATE);
}
}
//重置非Admin用户的密码
{
UserBaseBatchRequest request = new UserBaseBatchRequest();
request.setSkipIds(Collections.singletonList("admin"));
request.setSelectAll(true);
UserBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult(
this.requestPostAndReturn(userRequestUtils.URL_USER_RESET_PASSWORD, request),
UserBatchProcessResponse.class
);
List<User> userList = userService.selectByIdList(response.getProcessedIds());
for (User checkUser : userList) {
UserExample userExample = new UserExample();
userExample.createCriteria().andIdEqualTo(checkUser.getId()).andPasswordEqualTo(CodingUtil.md5(checkUser.getEmail()));
Assertions.assertEquals(1, userMapper.countByExample(userExample));
this.checkLog(checkUser.getId(), OperationLogType.UPDATE);
}
}
} }
@Test @Test
@Order(8) @Order(8)
public void testUserResetPasswordError() throws Exception { public void testUserResetPasswordError() throws Exception {
//用户不存在 //用户不存在
userRequestUtils.requestPostString(userRequestUtils.URL_USER_RESET_PASSWORD, "none user", ERROR_REQUEST_MATCHER); {
UserBaseBatchRequest request = new UserBaseBatchRequest();
request.setUserIds(Collections.singletonList("none user"));
this.requestPostAndReturn(userRequestUtils.URL_USER_RESET_PASSWORD, request, ERROR_REQUEST_MATCHER);
}
} }
@Test @Test
@ -610,7 +658,7 @@ public class UserControllerTests extends BaseTest {
} }
List<UserCreateInfo> last50Users = USER_LIST.subList(USER_LIST.size() - 50, USER_LIST.size()); List<UserCreateInfo> last50Users = USER_LIST.subList(USER_LIST.size() - 50, USER_LIST.size());
//测试添加角色权限 预期数据每个用户都会增加对应的权限 //测试添加角色权限 预期数据每个用户都会增加对应的权限
GlobalUserRoleRelationBatchRequest request = new GlobalUserRoleRelationBatchRequest(); UserAndRoleBatchRequest request = new UserAndRoleBatchRequest();
request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList())); request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList())); request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList()));
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, null); userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, null);
@ -646,23 +694,23 @@ public class UserControllerTests extends BaseTest {
} }
List<UserCreateInfo> last50Users = USER_LIST.subList(USER_LIST.size() - 50, USER_LIST.size()); List<UserCreateInfo> last50Users = USER_LIST.subList(USER_LIST.size() - 50, USER_LIST.size());
// 用户ID为空 // 用户ID为空
GlobalUserRoleRelationBatchRequest request = new GlobalUserRoleRelationBatchRequest(); UserAndRoleBatchRequest request = new UserAndRoleBatchRequest();
request.setUserIds(new ArrayList<>()); request.setUserIds(new ArrayList<>());
request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList())); request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList()));
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, BAD_REQUEST_MATCHER); userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, BAD_REQUEST_MATCHER);
// 角色id为空 // 角色id为空
request = new GlobalUserRoleRelationBatchRequest(); request = new UserAndRoleBatchRequest();
request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList())); request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setRoleIds(new ArrayList<>()); request.setRoleIds(new ArrayList<>());
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, BAD_REQUEST_MATCHER); userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, BAD_REQUEST_MATCHER);
// 用户ID含有不存在的 // 用户ID含有不存在的
request = new GlobalUserRoleRelationBatchRequest(); request = new UserAndRoleBatchRequest();
request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList())); request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList())); request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList()));
request.getUserIds().add("none user"); request.getUserIds().add("none user");
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER); userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER);
// 角色ID含有不存在的 // 角色ID含有不存在的
request = new GlobalUserRoleRelationBatchRequest(); request = new UserAndRoleBatchRequest();
request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList())); request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList())); request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList()));
request.getRoleIds().add("none role"); request.getRoleIds().add("none role");
@ -674,42 +722,69 @@ public class UserControllerTests extends BaseTest {
@Order(99) @Order(99)
public void testUserDeleteSuccess() throws Exception { public void testUserDeleteSuccess() throws Exception {
this.checkUserList(); this.checkUserList();
//删除已存的所有用户 //删除指定的用户
UserBatchProcessRequest request = new UserBatchProcessRequest(); {
request.setUserIdList(USER_LIST.stream().map(UserCreateInfo::getId).collect(Collectors.toList())); UserCreateInfo deleteUser = USER_LIST.get(0);
UserBaseBatchRequest request = new UserBaseBatchRequest();
request.setUserIds(Collections.singletonList(deleteUser.getId()));
UserBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_DELETE, request), UserBatchProcessResponse.class); UserBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_DELETE, request), UserBatchProcessResponse.class);
Assertions.assertEquals(request.getUserIdList().size(), response.getTotalCount()); Assertions.assertEquals(request.getUserIds().size(), response.getTotalCount());
Assertions.assertEquals(request.getUserIdList().size(), response.getSuccessCount()); Assertions.assertEquals(request.getUserIds().size(), response.getSuccessCount());
//检查数据库 //检查数据库
UserExample example = new UserExample(); UserExample example = new UserExample();
example.createCriteria().andIdIn(request.getUserIdList()); example.createCriteria().andIdIn(response.getProcessedIds());
List<User> userList = userMapper.selectByExample(example); List<User> userList = userMapper.selectByExample(example);
for (User user : userList) { for (User user : userList) {
Assertions.assertTrue(user.getDeleted()); Assertions.assertTrue(user.getDeleted());
} }
USER_LIST.remove(deleteUser);
}
//删除已存的所有用户(不包括admin
{
UserBaseBatchRequest request = new UserBaseBatchRequest();
request.setUserIds(USER_LIST.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setSkipIds(Collections.singletonList("admin"));
UserBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_DELETE, request), UserBatchProcessResponse.class);
Assertions.assertEquals(request.getUserIds().size(), response.getTotalCount());
Assertions.assertEquals(request.getUserIds().size(), response.getSuccessCount());
//检查数据库
UserExample example = new UserExample();
example.createCriteria().andIdIn(response.getProcessedIds());
List<User> userList = userMapper.selectByExample(example);
for (User user : userList) {
Assertions.assertTrue(user.getDeleted());
}
//记录已经删除了的用户用于反例 //记录已经删除了的用户用于反例
DELETED_USER_ID_LIST.clear(); DELETED_USER_ID_LIST.clear();
USER_LIST.clear(); USER_LIST.clear();
DELETED_USER_ID_LIST.addAll(request.getUserIdList()); DELETED_USER_ID_LIST.addAll(response.getProcessedIds());
//检查删除了的用户可以用其邮箱继续注册 //检查删除了的用户可以用其邮箱继续注册
this.testAddSuccess(); this.testAddSuccess();
} }
}
//删除失败的方法要放在删除成功方法后面执行 //删除失败的方法要放在删除成功方法后面执行
@Test @Test
@Order(100) @Order(100)
public void testUserDeleteError() throws Exception { public void testUserDeleteError() throws Exception {
//参数为空 //参数为空
UserBatchProcessRequest request = new UserBatchProcessRequest(); UserBaseBatchRequest request = new UserBaseBatchRequest();
this.requestPost(userRequestUtils.URL_USER_DELETE, request, BAD_REQUEST_MATCHER);
//用户不存在
request.getUserIdList().add("123456789012345678901234");
this.requestPost(userRequestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER);
//用户已经被删除 //用户不存在
request.setUserIds(Collections.singletonList("none user"));
this.requestPost(userRequestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER);
//测试用户已经被删除的
if (CollectionUtils.isEmpty(DELETED_USER_ID_LIST)) { if (CollectionUtils.isEmpty(DELETED_USER_ID_LIST)) {
this.testUserDeleteSuccess(); this.testUserDeleteSuccess();
} }
request.setUserIdList(DELETED_USER_ID_LIST); request.setUserIds(DELETED_USER_ID_LIST);
this.requestPost(userRequestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER);
//测试包含Admin用户
request = new UserBaseBatchRequest();
request.setSelectAll(true);
this.requestPost(userRequestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER);
} }
@ -753,19 +828,4 @@ public class UserControllerTests extends BaseTest {
} }
return returnList; return returnList;
} }
private void resetPasswordAndCheck(String userId, String userEmail) throws Exception {
User user = new User();
user.setId(userId);
user.setPassword("I can't say any dirty words");
Assertions.assertEquals(1, userMapper.updateByPrimaryKeySelective(user));
//调用重置密码的接口
userRequestUtils.requestPostString(userRequestUtils.URL_USER_RESET_PASSWORD, userId, status().isOk());
//检查数据库
UserExample example = new UserExample();
example.createCriteria().andIdEqualTo(userId).andPasswordEqualTo(CodingUtil.md5(userEmail));
Assertions.assertEquals(1, userMapper.countByExample(example));
checkLog(userId, OperationLogType.UPDATE);
}
} }

View File

@ -29,7 +29,7 @@ public class UserRequestUtils {
public final String URL_USER_IMPORT = "/system/user/import"; public final String URL_USER_IMPORT = "/system/user/import";
public final String URL_USER_DELETE = "/system/user/delete"; public final String URL_USER_DELETE = "/system/user/delete";
public final String URL_USER_RESET_PASSWORD = "/system/user/reset/password"; public final String URL_USER_RESET_PASSWORD = "/system/user/reset/password";
public final String URL_USER_ROLE_RELATION = "/user/role/relation/global/add/batch"; public final String URL_USER_ROLE_RELATION = "/system/user/add/batch/user-role";
private final MockMvc mockMvc; private final MockMvc mockMvc;
private final String sessionId; private final String sessionId;
@ -70,17 +70,6 @@ public class UserRequestUtils {
.andExpect(content().contentType(MediaType.APPLICATION_JSON)); .andExpect(content().contentType(MediaType.APPLICATION_JSON));
} }
//参数是string
public void requestPostString(String url, String param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(param)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
public void requestGet(String url, ResultMatcher resultMatcher) throws Exception { public void requestGet(String url, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(url) mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId) .header(SessionConstants.HEADER_TOKEN, sessionId)