diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UsersController.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UsersController.java index 391ece2a6640..f0100d24a666 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UsersController.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/controller/UsersController.java @@ -87,32 +87,22 @@ public class UsersController extends BaseController { @ResponseStatus(HttpStatus.CREATED) @ApiException(CREATE_USER_ERROR) @OperatorLog(auditType = AuditType.USER_CREATE) - public Result createUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userName") String userName, - @RequestParam(value = "userPassword") String userPassword, - @RequestParam(value = "tenantId") int tenantId, - @RequestParam(value = "queue", required = false, defaultValue = "") String queue, - @RequestParam(value = "email") String email, - @RequestParam(value = "phone", required = false) String phone, - @RequestParam(value = "state", required = false) int state) throws Exception { + public Result createUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userName") String userName, + @RequestParam(value = "userPassword") String userPassword, + @RequestParam(value = "tenantId") int tenantId, + @RequestParam(value = "queue", required = false, defaultValue = "") String queue, + @RequestParam(value = "email") String email, + @RequestParam(value = "phone", required = false) String phone, + @RequestParam(value = "state", required = false) int state) throws Exception { Result verifyRet = usersService.verifyUserName(userName); if (verifyRet.getCode() != Status.SUCCESS.getCode()) { return verifyRet; } - Map result = - usersService.createUser(loginUser, userName, userPassword, email, tenantId, phone, queue, state); - return returnDataList(result); + User user = usersService.createUser(loginUser, userName, userPassword, email, tenantId, phone, queue, state); + return Result.success(user); } - /** - * query user list paging - * - * @param loginUser login user - * @param pageNo page number - * @param searchVal search avlue - * @param pageSize page size - * @return user list page - */ @Operation(summary = "queryUserList", description = "QUERY_USER_LIST_NOTES") @Parameters({ @Parameter(name = "pageNo", description = "PAGE_NO", required = true, schema = @Schema(implementation = int.class, example = "1")), @@ -131,19 +121,6 @@ public Result queryUserList(@Parameter(hidden = true) @RequestAttribute(value = return usersService.queryUserList(loginUser, searchVal, pageNo, pageSize); } - /** - * update user - * - * @param loginUser login user - * @param id user id - * @param userName user name - * @param userPassword user password - * @param email email - * @param tenantId tennat id - * @param phone phone - * @param queue queue - * @return update result code - */ @Operation(summary = "updateUser", description = "UPDATE_USER_NOTES") @Parameters({ @Parameter(name = "id", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @@ -182,13 +159,6 @@ public Result updateUser(@Parameter(hidden = true) @RequestAttribute(value return Result.success(user); } - /** - * delete user by id - * - * @param loginUser login user - * @param id user id - * @return delete result code - */ @Operation(summary = "delUserById", description = "DELETE_USER_BY_ID_NOTES") @Parameters({ @Parameter(name = "id", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")) @@ -197,20 +167,12 @@ public Result updateUser(@Parameter(hidden = true) @RequestAttribute(value @ResponseStatus(HttpStatus.OK) @ApiException(DELETE_USER_BY_ID_ERROR) @OperatorLog(auditType = AuditType.USER_DELETE) - public Result delUserById(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "id") int id) throws Exception { - Map result = usersService.deleteUserById(loginUser, id); - return returnDataList(result); + public Result delUserById(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "id") int id) throws Exception { + usersService.deleteUserById(loginUser, id); + return Result.success(); } - /** - * revoke project By Id - * - * @param loginUser login user - * @param userId user id - * @param projectIds project id array - * @return revoke result code - */ @Operation(summary = "revokeProjectById", description = "REVOKE_PROJECT_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @@ -219,21 +181,13 @@ public Result delUserById(@Parameter(hidden = true) @RequestAttribute(value = Co @PostMapping(value = "/revoke-project-by-id") @ResponseStatus(HttpStatus.OK) @ApiException(REVOKE_PROJECT_ERROR) - public Result revokeProjectById(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userId") int userId, - @RequestParam(value = "projectIds") String projectIds) { - Map result = usersService.revokeProjectById(loginUser, userId, projectIds); - return returnDataList(result); + public Result revokeProjectById(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userId") int userId, + @RequestParam(value = "projectIds") String projectIds) { + usersService.revokeProjectById(loginUser, userId, projectIds); + return Result.success(); } - /** - * grant project with read permission - * - * @param loginUser login user - * @param userId user id - * @param projectIds project id array - * @return grant result code - */ @Operation(summary = "grantProjectWithReadPerm", description = "GRANT_PROJECT_WITH_READ_PERM_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @@ -242,21 +196,13 @@ public Result revokeProjectById(@Parameter(hidden = true) @RequestAttribute(valu @PostMapping(value = "/grant-project-with-read-perm") @ResponseStatus(HttpStatus.OK) @ApiException(GRANT_PROJECT_ERROR) - public Result grantProjectWithReadPerm(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userId") int userId, - @RequestParam(value = "projectIds") String projectIds) { - Map result = usersService.grantProjectWithReadPerm(loginUser, userId, projectIds); - return returnDataList(result); + public Result grantProjectWithReadPerm(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userId") int userId, + @RequestParam(value = "projectIds") String projectIds) { + usersService.grantProjectWithReadPerm(loginUser, userId, projectIds); + return Result.success(); } - /** - * grant project - * - * @param loginUser login user - * @param userId user id - * @param projectIds project id array - * @return grant result code - */ @Operation(summary = "grantProject", description = "GRANT_PROJECT_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @@ -265,21 +211,13 @@ public Result grantProjectWithReadPerm(@Parameter(hidden = true) @RequestAttribu @PostMapping(value = "/grant-project") @ResponseStatus(HttpStatus.OK) @ApiException(GRANT_PROJECT_ERROR) - public Result grantProject(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userId") int userId, - @RequestParam(value = "projectIds") String projectIds) { - Map result = usersService.grantProject(loginUser, userId, projectIds); - return returnDataList(result); + public Result grantProject(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userId") int userId, + @RequestParam(value = "projectIds") String projectIds) { + usersService.grantProject(loginUser, userId, projectIds); + return Result.success(); } - /** - * grant project by code - * - * @param loginUser login user - * @param userId user id - * @param projectCode project code - * @return grant result code - */ @Operation(summary = "grantProjectByCode", description = "GRANT_PROJECT_BY_CODE_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @@ -288,21 +226,13 @@ public Result grantProject(@Parameter(hidden = true) @RequestAttribute(value = C @PostMapping(value = "/grant-project-by-code") @ResponseStatus(HttpStatus.OK) @ApiException(GRANT_PROJECT_ERROR) - public Result grantProjectByCode(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userId") int userId, - @RequestParam(value = "projectCode") long projectCode) { - Map result = this.usersService.grantProjectByCode(loginUser, userId, projectCode); - return this.returnDataList(result); + public Result grantProjectByCode(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userId") int userId, + @RequestParam(value = "projectCode") long projectCode) { + usersService.grantProjectByCode(loginUser, userId, projectCode); + return Result.success(); } - /** - * revoke project - * - * @param loginUser login user - * @param userId user id - * @param projectCode project code - * @return revoke result code - */ @Operation(summary = "revokeProject", description = "REVOKE_PROJECT_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @@ -311,21 +241,13 @@ public Result grantProjectByCode(@Parameter(hidden = true) @RequestAttribute(val @PostMapping(value = "/revoke-project") @ResponseStatus(HttpStatus.OK) @ApiException(REVOKE_PROJECT_ERROR) - public Result revokeProject(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userId") int userId, - @RequestParam(value = "projectCode") long projectCode) { - Map result = this.usersService.revokeProject(loginUser, userId, projectCode); - return returnDataList(result); + public Result revokeProject(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userId") int userId, + @RequestParam(value = "projectCode") long projectCode) { + usersService.revokeProject(loginUser, userId, projectCode); + return Result.success(); } - /** - * grant namespace - * - * @param loginUser login user - * @param userId user id - * @param namespaceIds namespace id array - * @return grant result code - */ @Operation(summary = "grantNamespace", description = "GRANT_NAMESPACE_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @@ -334,21 +256,13 @@ public Result revokeProject(@Parameter(hidden = true) @RequestAttribute(value = @PostMapping(value = "/grant-namespace") @ResponseStatus(HttpStatus.OK) @ApiException(GRANT_K8S_NAMESPACE_ERROR) - public Result grantNamespace(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userId") int userId, - @RequestParam(value = "namespaceIds") String namespaceIds) { - Map result = usersService.grantNamespaces(loginUser, userId, namespaceIds); - return returnDataList(result); + public Result grantNamespace(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userId") int userId, + @RequestParam(value = "namespaceIds") String namespaceIds) { + usersService.grantNamespaces(loginUser, userId, namespaceIds); + return Result.success(); } - /** - * grant datasource - * - * @param loginUser login user - * @param userId user id - * @param datasourceIds data source id array - * @return grant result code - */ @Operation(summary = "grantDataSource", description = "GRANT_DATASOURCE_NOTES") @Parameters({ @Parameter(name = "userId", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")), @@ -357,64 +271,37 @@ public Result grantNamespace(@Parameter(hidden = true) @RequestAttribute(value = @PostMapping(value = "/grant-datasource") @ResponseStatus(HttpStatus.OK) @ApiException(GRANT_DATASOURCE_ERROR) - public Result grantDataSource(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userId") int userId, - @RequestParam(value = "datasourceIds") String datasourceIds) { - Map result = usersService.grantDataSource(loginUser, userId, datasourceIds); - return returnDataList(result); + public Result grantDataSource(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userId") int userId, + @RequestParam(value = "datasourceIds") String datasourceIds) { + usersService.grantDataSource(loginUser, userId, datasourceIds); + return Result.success(); } - /** - * get user info - * - * @param loginUser login user - * @return user info - */ @Operation(summary = "getUserInfo", description = "GET_USER_INFO_NOTES") @GetMapping(value = "/get-user-info") @ResponseStatus(HttpStatus.OK) @ApiException(GET_USER_INFO_ERROR) - public Result getUserInfo(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser) { - Map result = usersService.getUserInfo(loginUser); - return returnDataList(result); + public Result getUserInfo(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser) { + User user = usersService.getUserInfo(loginUser); + return Result.success(user); } - /** - * user list no paging - * - * @param loginUser login user - * @return user list - */ @Operation(summary = "listUser", description = "LIST_USER_NOTES") @GetMapping(value = "/list") @ResponseStatus(HttpStatus.OK) @ApiException(USER_LIST_ERROR) - public Result listUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser) { - Map result = usersService.queryAllGeneralUsers(loginUser); - return returnDataList(result); + public Result> listUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser) { + return Result.success(usersService.queryAllGeneralUsers(loginUser)); } - /** - * user list no paging - * - * @param loginUser login user - * @return user list - */ @GetMapping(value = "/list-all") @ResponseStatus(HttpStatus.OK) @ApiException(USER_LIST_ERROR) - public Result listAll(@RequestAttribute(value = Constants.SESSION_USER) User loginUser) { - Map result = usersService.queryUserList(loginUser); - return returnDataList(result); + public Result> listAll(@RequestAttribute(value = Constants.SESSION_USER) User loginUser) { + return Result.success(usersService.queryUserList(loginUser)); } - /** - * verify username - * - * @param loginUser login user - * @param userName user name - * @return true if user name not exists, otherwise return false - */ @Operation(summary = "verifyUserName", description = "VERIFY_USER_NAME_NOTES") @Parameters({ @Parameter(name = "userName", description = "USER_NAME", required = true, schema = @Schema(implementation = String.class)) @@ -427,13 +314,6 @@ public Result verifyUserName(@Parameter(hidden = true) @RequestAttribute(value = return usersService.verifyUserName(userName); } - /** - * unauthorized user - * - * @param loginUser login user - * @param alertgroupId alert group id - * @return unauthorize result code - */ @Operation(summary = "unauthorizedUser", description = "UNAUTHORIZED_USER_NOTES") @Parameters({ @Parameter(name = "alertgroupId", description = "ALERT_GROUP_ID", required = true, schema = @Schema(implementation = String.class)) @@ -441,19 +321,11 @@ public Result verifyUserName(@Parameter(hidden = true) @RequestAttribute(value = @GetMapping(value = "/unauth-user") @ResponseStatus(HttpStatus.OK) @ApiException(UNAUTHORIZED_USER_ERROR) - public Result unauthorizedUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam("alertgroupId") Integer alertgroupId) { - Map result = usersService.unauthorizedUser(loginUser, alertgroupId); - return returnDataList(result); + public Result> unauthorizedUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam("alertgroupId") Integer alertgroupId) { + return Result.success(usersService.unauthorizedUser(loginUser, alertgroupId)); } - /** - * authorized user - * - * @param loginUser login user - * @param alertgroupId alert group id - * @return authorized result code - */ @Operation(summary = "authorizedUser", description = "AUTHORIZED_USER_NOTES") @Parameters({ @Parameter(name = "alertgroupId", description = "ALERT_GROUP_ID", required = true, schema = @Schema(implementation = String.class)) @@ -461,25 +333,11 @@ public Result unauthorizedUser(@Parameter(hidden = true) @RequestAttribute(value @GetMapping(value = "/authed-user") @ResponseStatus(HttpStatus.OK) @ApiException(AUTHORIZED_USER_ERROR) - public Result authorizedUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam("alertgroupId") Integer alertgroupId) { - try { - Map result = usersService.authorizedUser(loginUser, alertgroupId); - return returnDataList(result); - } catch (Exception e) { - log.error(Status.AUTHORIZED_USER_ERROR.getMsg(), e); - return error(Status.AUTHORIZED_USER_ERROR.getCode(), Status.AUTHORIZED_USER_ERROR.getMsg()); - } + public Result> authorizedUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam("alertgroupId") Integer alertgroupId) { + return Result.success(usersService.authorizedUser(loginUser, alertgroupId)); } - /** - * user registry - * - * @param userName user name - * @param userPassword user password - * @param repeatPassword repeat password - * @param email user email - */ @Operation(summary = "registerUser", description = "REGISTER_USER_NOTES") @Parameters({ @Parameter(name = "userName", description = "USER_NAME", required = true, schema = @Schema(implementation = String.class)), @@ -490,27 +348,21 @@ public Result authorizedUser(@Parameter(hidden = true) @RequestAttribute(value = @PostMapping("/register") @ResponseStatus(HttpStatus.OK) @ApiException(CREATE_USER_ERROR) - public Result registerUser(@RequestParam(value = "userName") String userName, - @RequestParam(value = "userPassword") String userPassword, - @RequestParam(value = "repeatPassword") String repeatPassword, - @RequestParam(value = "email") String email) throws Exception { + public Result registerUser(@RequestParam(value = "userName") String userName, + @RequestParam(value = "userPassword") String userPassword, + @RequestParam(value = "repeatPassword") String repeatPassword, + @RequestParam(value = "email") String email) throws Exception { userName = ParameterUtils.handleEscapes(userName); userPassword = ParameterUtils.handleEscapes(userPassword); repeatPassword = ParameterUtils.handleEscapes(repeatPassword); email = ParameterUtils.handleEscapes(email); Result verifyRet = usersService.verifyUserName(userName); if (verifyRet.getCode() != Status.SUCCESS.getCode()) { - return verifyRet; + return new Result<>(verifyRet.getCode(), verifyRet.getMsg()); } - Map result = usersService.registerUser(userName, userPassword, repeatPassword, email); - return returnDataList(result); + return Result.success(usersService.registerUser(userName, userPassword, repeatPassword, email)); } - /** - * user activate - * - * @param userName user name - */ @Operation(summary = "activateUser", description = "ACTIVATE_USER_NOTES") @Parameters({ @Parameter(name = "userName", description = "USER_NAME", schema = @Schema(implementation = String.class)), @@ -518,18 +370,12 @@ public Result registerUser(@RequestParam(value = "userName") String user @PostMapping("/activate") @ResponseStatus(HttpStatus.OK) @ApiException(UPDATE_USER_ERROR) - public Result activateUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestParam(value = "userName") String userName) { + public Result activateUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestParam(value = "userName") String userName) { userName = ParameterUtils.handleEscapes(userName); - Map result = usersService.activateUser(loginUser, userName); - return returnDataList(result); + return Result.success(usersService.activateUser(loginUser, userName)); } - /** - * user batch activate - * - * @param userNames user names - */ @Operation(summary = "batchActivateUser", description = "BATCH_ACTIVATE_USER_NOTES") @Parameters({ @Parameter(name = "userNames", description = "USER_NAMES", required = true, schema = @Schema(implementation = List.class)), @@ -537,11 +383,10 @@ public Result activateUser(@Parameter(hidden = true) @RequestAttribute(v @PostMapping("/batch/activate") @ResponseStatus(HttpStatus.OK) @ApiException(UPDATE_USER_ERROR) - public Result batchActivateUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, - @RequestBody List userNames) { + public Result> batchActivateUser(@Parameter(hidden = true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser, + @RequestBody List userNames) { List formatUserNames = userNames.stream().map(ParameterUtils::handleEscapes).collect(Collectors.toList()); - Map result = usersService.batchActivateUser(loginUser, formatUserNames); - return returnDataList(result); + return Result.success(usersService.batchActivateUser(loginUser, formatUserNames)); } } diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java index cb048d0ce75a..487b7170f965 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/UsersService.java @@ -29,19 +29,9 @@ public interface UsersService { /** * create user, only system admin have permission - * - * @param loginUser login user - * @param userName user name - * @param userPassword user password - * @param email email - * @param tenantId tenant id - * @param phone phone - * @param queue queue - * @return create result code - * @throws Exception exception */ - Map createUser(User loginUser, String userName, String userPassword, String email, - int tenantId, String phone, String queue, int state) throws Exception; + User createUser(User loginUser, String userName, String userPassword, String email, + int tenantId, String phone, String queue, int state) throws Exception; User createUser(String userName, String userPassword, String email, int tenantId, String phone, String queue, int state); @@ -53,69 +43,43 @@ User createUser(String userName, String userPassword, String email, /** * get user by user name - * - * @param userName user name - * @return exist user or null */ User getUserByUserName(String userName); /** * query user by id - * - * @param id id - * @return user info */ User queryUser(int id); /** * query user by ids - * - * @param ids id list - * @return user list */ List queryUser(List ids); /** * query user - * - * @param name name - * @return user info */ User queryUser(String name); /** * query user - * - * @param name name - * @param password password - * @return user info */ User queryUser(String name, String password); /** * get user id by user name * - * @param name user name * @return if name empty 0, user not exists -1, user exist user id */ int getUserIdByName(String name); /** * query user list - * - * @param loginUser login user - * @param pageNo page number - * @param searchVal search value - * @param pageSize page size - * @return user list page */ Result queryUserList(User loginUser, String searchVal, Integer pageNo, Integer pageSize); /** * Update an existing user entity. - * - * @param user The user object to update. - * @return The updated user object. */ User updateUser(User user); @@ -132,159 +96,88 @@ User updateUser(User loginUser, /** * delete user - * - * @param loginUser login user - * @param id user id - * @return delete result code - * @throws Exception exception when operate hdfs */ - Map deleteUserById(User loginUser, int id) throws IOException; + void deleteUserById(User loginUser, int id) throws IOException; /** * grant project - * - * @param loginUser login user - * @param userId user id - * @param projectIds project id array - * @return grant result code */ - Map grantProject(User loginUser, int userId, String projectIds); + void grantProject(User loginUser, int userId, String projectIds); /** * grant project with read permission - * - * @param loginUser login user - * @param userId user id - * @param projectIds project id array - * @return grant result code */ - Map grantProjectWithReadPerm(User loginUser, int userId, String projectIds); + void grantProjectWithReadPerm(User loginUser, int userId, String projectIds); /** * grant project by code - * - * @param loginUser login user - * @param userId user id - * @param projectCode project code - * @return grant result code */ - Map grantProjectByCode(User loginUser, int userId, long projectCode); + void grantProjectByCode(User loginUser, int userId, long projectCode); /** * revoke the project permission for specified user by id - * @param loginUser Login user - * @param userId User id - * @param projectIds project id array - * @return */ - Map revokeProjectById(User loginUser, int userId, String projectIds); + void revokeProjectById(User loginUser, int userId, String projectIds); /** - * revoke the project permission for specified user. - * @param loginUser Login user - * @param userId User id - * @param projectCode Project Code - * @return + * revoke the project permission for specified user by project code */ - Map revokeProject(User loginUser, int userId, long projectCode); + void revokeProject(User loginUser, int userId, long projectCode); /** * grant namespace - * - * @param loginUser login user - * @param userId user id - * @param namespaceIds namespace id array - * @return grant result code */ - Map grantNamespaces(User loginUser, int userId, String namespaceIds); + void grantNamespaces(User loginUser, int userId, String namespaceIds); /** * grant datasource - * - * @param loginUser login user - * @param userId user id - * @param datasourceIds data source id array - * @return grant result code */ - Map grantDataSource(User loginUser, int userId, String datasourceIds); + void grantDataSource(User loginUser, int userId, String datasourceIds); /** - * query user info - * - * @param loginUser login user - * @return user info + * query user info (with tenantCode / alertGroup / timeZone populated, password stripped) */ - Map getUserInfo(User loginUser); + User getUserInfo(User loginUser); /** - * query user list - * - * @param loginUser login user - * @return user list + * query general user list */ - Map queryAllGeneralUsers(User loginUser); + List queryAllGeneralUsers(User loginUser); /** - * query user list - * - * @param loginUser login user - * @return user list + * query enabled user list */ - Map queryUserList(User loginUser); + List queryUserList(User loginUser); /** * verify user name exists - * - * @param userName user name - * @return true if user name not exists, otherwise return false */ Result verifyUserName(String userName); /** - * unauthorized user - * - * @param loginUser login user - * @param alertGroupId alert group id - * @return unauthorize result code + * users not yet authorized to the given alert group */ - Map unauthorizedUser(User loginUser, Integer alertGroupId); + List unauthorizedUser(User loginUser, Integer alertGroupId); /** - * authorized user - * - * @param loginUser login user - * @param alertGroupId alert group id - * @return authorized result code + * users authorized to the given alert group */ - Map authorizedUser(User loginUser, Integer alertGroupId); + List authorizedUser(User loginUser, Integer alertGroupId); /** * registry user, default state is 0, default tenant_id is 1, no phone, no queue - * - * @param userName user name - * @param userPassword user password - * @param repeatPassword repeat password - * @param email email - * @return registry result code - * @throws Exception exception */ - Map registerUser(String userName, String userPassword, String repeatPassword, String email); + User registerUser(String userName, String userPassword, String repeatPassword, String email); /** * activate user, only system admin have permission, change user state code 0 to 1 - * - * @param loginUser login user - * @param userName user name - * @return create result code */ - Map activateUser(User loginUser, String userName); + User activateUser(User loginUser, String userName); /** - * activate user, only system admin have permission, change users state code 0 to 1 - * - * @param loginUser login user - * @param userNames user name - * @return create result code + * activate users, only system admin have permission, change users state code 0 to 1. + * Returns a map with two buckets: {@code success} and {@code failed}, each carrying a + * {@code sum} count plus per-user details, matching the historical wire shape. */ Map batchActivateUser(User loginUser, List userNames); @@ -292,15 +185,6 @@ User updateUser(User loginUser, * Make sure user with given name exists, and create the user if not exists *

* ONLY for python gateway server, and should not use this in web ui function - * - * @param userName user name - * @param userPassword user password - * @param email user email - * @param phone user phone - * @param tenantCode tenant code - * @param queue queue - * @param state state - * @return create result code */ User createUserIfNotExists(String userName, String userPassword, String email, String phone, String tenantCode, String queue, diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/UsersServiceImpl.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/UsersServiceImpl.java index ec112ef55453..111b508598df 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/UsersServiceImpl.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/impl/UsersServiceImpl.java @@ -52,7 +52,6 @@ import org.apache.commons.lang3.StringUtils; import java.io.IOException; -import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -119,41 +118,32 @@ public class UsersServiceImpl extends BaseServiceImpl implements UsersService { */ @Override @Transactional(rollbackFor = Exception.class) - public Map createUser(User loginUser, - String userName, - String userPassword, - String email, - int tenantId, - String phone, - String queue, - int state) throws Exception { - Map result = new HashMap<>(); - - // check all user params - String msg = this.checkUserParams(userName, userPassword, email, phone); - + public User createUser(User loginUser, + String userName, + String userPassword, + String email, + int tenantId, + String phone, + String queue, + int state) throws Exception { if (!isAdmin(loginUser)) { - putMsg(result, Status.USER_NO_OPERATION_PERM); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } + // check all user params + String msg = this.checkUserParams(userName, userPassword, email, phone); if (!StringUtils.isEmpty(msg)) { - putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, msg); - return result; + throw new ServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, msg); } if (!checkTenantExists(tenantId)) { log.warn("Tenant does not exist, tenantId:{}.", tenantId); - putMsg(result, Status.TENANT_NOT_EXIST); - return result; + throw new ServiceException(Status.TENANT_NOT_EXIST); } User user = createUser(userName, userPassword, email, tenantId, phone, queue, state); - log.info("User is created and id is {}.", user.getId()); - result.put(Constants.DATA_LIST, user); - putMsg(result, Status.SUCCESS); - return result; + return user; } @Override @@ -434,31 +424,26 @@ public User updateUser(User loginUser, */ @Override @Transactional - public Map deleteUserById(User loginUser, int id) throws IOException { - Map result = new HashMap<>(); - + public void deleteUserById(User loginUser, int id) throws IOException { // only admin can operate if (!isAdmin(loginUser)) { log.warn("User does not have permission for this feature, userId:{}, userName:{}.", loginUser.getId(), loginUser.getUserName()); - putMsg(result, Status.USER_NO_OPERATION_PERM, id); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM, id); } // check exist User tempUser = userMapper.selectById(id); if (tempUser == null) { log.error("User does not exist, userId:{}.", id); - putMsg(result, Status.USER_NOT_EXIST, id); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, id); } // check if is a project owner List projects = projectMapper.queryProjectCreatedByUser(id); if (CollectionUtils.isNotEmpty(projects)) { String projectNames = projects.stream().map(Project::getName).collect(Collectors.joining(",")); - putMsg(result, Status.TRANSFORM_PROJECT_OWNERSHIP, projectNames); log.warn("Please transfer the project ownership before deleting the user, userId:{}, projects:{}.", id, projectNames); - return result; + throw new ServiceException(Status.TRANSFORM_PROJECT_OWNERSHIP, projectNames); } // delete user userMapper.queryTenantCodeByUserId(id); @@ -466,15 +451,11 @@ public Map deleteUserById(User loginUser, int id) throws IOExcep accessTokenMapper.deleteAccessTokenByUserId(id); sessionService.expireSession(id); - if (userMapper.deleteById(id) > 0) { - log.info("User is deleted and id is :{}.", id); - putMsg(result, Status.SUCCESS); - return result; - } else { + if (userMapper.deleteById(id) <= 0) { log.error("User delete error, userId:{}.", id); - putMsg(result, Status.DELETE_USER_BY_ID_ERROR); - return result; + throw new ServiceException(Status.DELETE_USER_BY_ID_ERROR); } + log.info("User is deleted and id is :{}.", id); } /** @@ -487,35 +468,26 @@ public Map deleteUserById(User loginUser, int id) throws IOExcep */ @Override @Transactional(rollbackFor = RuntimeException.class) - public Map revokeProjectById(User loginUser, int userId, String projectIds) { - Map result = new HashMap<>(); - result.put(Constants.STATUS, false); - + public void revokeProjectById(User loginUser, int userId, String projectIds) { // 1. only admin can operate - if (this.check(result, !this.isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) { - return result; + if (!this.isAdmin(loginUser)) { + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } // 2. check if user is existed User user = this.userMapper.selectById(userId); if (user == null) { - this.putMsg(result, Status.USER_NOT_EXIST, userId); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, userId); } Arrays.stream(projectIds.split(",")).distinct().forEach(projectId -> { // 3. check if project is existed Project project = this.projectMapper.queryDetailById(Integer.parseInt(projectId)); - if (project == null) { - this.putMsg(result, Status.PROJECT_NOT_FOUND, Integer.parseInt(projectId)); - } else { + if (project != null) { // 4. delete the relationship between project and user this.projectUserMapper.deleteProjectRelation(project.getId(), user.getId()); } }); - - this.putMsg(result, Status.SUCCESS); - return result; } /** @@ -528,24 +500,19 @@ public Map revokeProjectById(User loginUser, int userId, String */ @Override @Transactional(rollbackFor = RuntimeException.class) - public Map grantProjectWithReadPerm(User loginUser, int userId, String projectIds) { - Map result = new HashMap<>(); - result.put(Constants.STATUS, false); - + public void grantProjectWithReadPerm(User loginUser, int userId, String projectIds) { if (!isAdmin(loginUser)) { - putMsg(result, Status.NO_CURRENT_OPERATING_PERMISSION); - return result; + throw new ServiceException(Status.NO_CURRENT_OPERATING_PERMISSION); } // check exist User tempUser = userMapper.selectById(userId); if (tempUser == null) { - putMsg(result, Status.USER_NOT_EXIST, userId); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, userId); } - if (check(result, StringUtils.isEmpty(projectIds), Status.SUCCESS)) { - return result; + if (StringUtils.isEmpty(projectIds)) { + return; } Arrays.stream(projectIds.split(Constants.COMMA)).distinct().forEach(projectId -> { ProjectUser projectUserOld = projectUserMapper.queryProjectRelation(Integer.parseInt(projectId), userId); @@ -561,9 +528,6 @@ public Map grantProjectWithReadPerm(User loginUser, int userId, projectUser.setUpdateTime(now); projectUserMapper.insert(projectUser); }); - putMsg(result, Status.SUCCESS); - - return result; } /** @@ -576,26 +540,21 @@ public Map grantProjectWithReadPerm(User loginUser, int userId, */ @Override @Transactional - public Map grantProject(User loginUser, int userId, String projectIds) { - Map result = new HashMap<>(); - result.put(Constants.STATUS, false); - + public void grantProject(User loginUser, int userId, String projectIds) { // check exist User tempUser = userMapper.selectById(userId); if (tempUser == null) { log.error("User does not exist, userId:{}.", userId); - putMsg(result, Status.USER_NOT_EXIST, userId); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, userId); } if (!isAdmin(loginUser)) { - putMsg(result, Status.NO_CURRENT_OPERATING_PERMISSION); - return result; + throw new ServiceException(Status.NO_CURRENT_OPERATING_PERMISSION); } - if (check(result, StringUtils.isEmpty(projectIds), Status.SUCCESS)) { + if (StringUtils.isEmpty(projectIds)) { log.warn("Parameter projectIds is empty."); - return result; + return; } Arrays.stream(projectIds.split(",")).distinct().forEach(projectId -> { ProjectUser projectUserOld = projectUserMapper.queryProjectRelation(Integer.parseInt(projectId), userId); @@ -611,9 +570,6 @@ public Map grantProject(User loginUser, int userId, String proje projectUser.setUpdateTime(now); projectUserMapper.insert(projectUser); }); - putMsg(result, Status.SUCCESS); - - return result; } /** @@ -625,32 +581,26 @@ public Map grantProject(User loginUser, int userId, String proje * @return grant result code */ @Override - public Map grantProjectByCode(final User loginUser, final int userId, final long projectCode) { - Map result = new HashMap<>(); - result.put(Constants.STATUS, false); - + public void grantProjectByCode(final User loginUser, final int userId, final long projectCode) { // 1. check if user is existed User tempUser = this.userMapper.selectById(userId); if (tempUser == null) { log.error("User does not exist, userId:{}.", userId); - this.putMsg(result, Status.USER_NOT_EXIST, userId); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, userId); } // 2. check if project is existed Project project = this.projectMapper.queryByCode(projectCode); if (project == null) { log.error("Project does not exist, projectCode:{}.", projectCode); - this.putMsg(result, Status.PROJECT_NOT_FOUND, projectCode); - return result; + throw new ServiceException(Status.PROJECT_NOT_FOUND, projectCode); } // 3. only project owner can operate if (!this.canOperator(loginUser, project.getUserId())) { log.warn("User does not have permission for project, userId:{}, userName:{}, projectCode:{}.", loginUser.getId(), loginUser.getUserName(), projectCode); - this.putMsg(result, Status.USER_NO_OPERATION_PERM); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } // 4. maintain the relationship between project and user if not exists @@ -666,8 +616,6 @@ public Map grantProjectByCode(final User loginUser, final int us this.projectUserMapper.insert(projectUser); } log.info("User is granted permission for projects, userId:{}, projectCode:{}.", userId, projectCode); - this.putMsg(result, Status.SUCCESS); - return result; } /** @@ -679,37 +627,30 @@ public Map grantProjectByCode(final User loginUser, final int us * @return */ @Override - public Map revokeProject(User loginUser, int userId, long projectCode) { - Map result = new HashMap<>(); - result.put(Constants.STATUS, false); - + public void revokeProject(User loginUser, int userId, long projectCode) { // 1. only admin can operate - if (this.check(result, !this.isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) { + if (!this.isAdmin(loginUser)) { log.warn("Only admin can revoke the project permission."); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } // 2. check if user is existed User user = this.userMapper.selectById(userId); if (user == null) { log.error("User does not exist, userId:{}.", userId); - this.putMsg(result, Status.USER_NOT_EXIST, userId); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, userId); } // 3. check if project is existed Project project = this.projectMapper.queryByCode(projectCode); if (project == null) { log.error("Project does not exist, projectCode:{}.", projectCode); - this.putMsg(result, Status.PROJECT_NOT_FOUND, projectCode); - return result; + throw new ServiceException(Status.PROJECT_NOT_FOUND, projectCode); } // 4. delete th relationship between project and user this.projectUserMapper.deleteProjectRelation(project.getId(), user.getId()); log.info("User is revoked permission for projects, userId:{}, projectCode:{}.", userId, projectCode); - this.putMsg(result, Status.SUCCESS); - return result; } /** @@ -722,21 +663,18 @@ public Map revokeProject(User loginUser, int userId, long projec */ @Override @Transactional - public Map grantNamespaces(User loginUser, int userId, String namespaceIds) { - Map result = new HashMap<>(); - result.put(Constants.STATUS, false); + public void grantNamespaces(User loginUser, int userId, String namespaceIds) { // only admin can operate - if (this.check(result, !this.isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) { + if (!this.isAdmin(loginUser)) { log.warn("Only admin can grant namespaces."); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } // check exist User tempUser = userMapper.selectById(userId); if (tempUser == null) { log.error("User does not exist, userId:{}.", userId); - putMsg(result, Status.USER_NOT_EXIST, userId); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, userId); } k8sNamespaceUserMapper.deleteNamespaceRelation(0, userId); @@ -755,10 +693,6 @@ public Map grantNamespaces(User loginUser, int userId, String na } log.info("User is granted permission for namespace, userId:{}.", tempUser.getId()); - - putMsg(result, Status.SUCCESS); - - return result; } /** @@ -771,25 +705,21 @@ public Map grantNamespaces(User loginUser, int userId, String na */ @Override @Transactional - public Map grantDataSource(User loginUser, int userId, String datasourceIds) { - Map result = new HashMap<>(); - result.put(Constants.STATUS, false); - + public void grantDataSource(User loginUser, int userId, String datasourceIds) { // only admin can operate - if (this.check(result, !this.isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) { + if (!this.isAdmin(loginUser)) { log.warn("Only admin can grant datasource."); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } User user = userMapper.selectById(userId); if (user == null) { - putMsg(result, Status.USER_NOT_EXIST, userId); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, userId); } datasourceUserMapper.deleteByUserId(userId); - if (check(result, StringUtils.isEmpty(datasourceIds), Status.SUCCESS)) { - return result; + if (StringUtils.isEmpty(datasourceIds)) { + return; } String[] datasourceIdArr = datasourceIds.split(","); @@ -805,10 +735,6 @@ public Map grantDataSource(User loginUser, int userId, String da datasourceUser.setUpdateTime(now); datasourceUserMapper.insert(datasourceUser); } - - putMsg(result, Status.SUCCESS); - - return result; } /** @@ -818,11 +744,8 @@ public Map grantDataSource(User loginUser, int userId, String da * @return user info */ @Override - public Map getUserInfo(User loginUser) { - - Map result = new HashMap<>(); - - User user = null; + public User getUserInfo(User loginUser) { + User user; if (loginUser.getUserType() == UserType.ADMIN_USER) { user = loginUser; } else { @@ -853,11 +776,7 @@ public Map getUserInfo(User loginUser) { // remove password user.setUserPassword(null); - - result.put(Constants.DATA_LIST, user); - - putMsg(result, Status.SUCCESS); - return result; + return user; } /** @@ -867,19 +786,13 @@ public Map getUserInfo(User loginUser) { * @return user list */ @Override - public Map queryAllGeneralUsers(User loginUser) { - Map result = new HashMap<>(); + public List queryAllGeneralUsers(User loginUser) { // only admin can operate - if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) { + if (!isAdmin(loginUser)) { log.warn("Only admin can query all general users."); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } - - List userList = userMapper.queryAllGeneralUser(); - result.put(Constants.DATA_LIST, userList); - putMsg(result, Status.SUCCESS); - - return result; + return userMapper.queryAllGeneralUser(); } /** @@ -889,18 +802,12 @@ public Map queryAllGeneralUsers(User loginUser) { * @return user list */ @Override - public Map queryUserList(User loginUser) { - Map result = new HashMap<>(); + public List queryUserList(User loginUser) { // only admin can operate if (!canOperatorPermissions(loginUser, null, AuthorizationType.ACCESS_TOKEN, USER_MANAGER)) { - putMsg(result, Status.USER_NO_OPERATION_PERM); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } - List userList = userMapper.queryEnabledUsers(); - result.put(Constants.DATA_LIST, userList); - putMsg(result, Status.SUCCESS); - - return result; + return userMapper.queryEnabledUsers(); } /** @@ -931,34 +838,28 @@ public Result verifyUserName(String userName) { * @return unauthorize result code */ @Override - public Map unauthorizedUser(User loginUser, Integer alertgroupId) { - - Map result = new HashMap<>(); + public List unauthorizedUser(User loginUser, Integer alertgroupId) { // only admin can operate - if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) { + if (!isAdmin(loginUser)) { log.warn("Only admin can deauthorize user."); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } List userList = userMapper.selectList(null); List resultUsers = new ArrayList<>(); - Set userSet = null; + Set userSet; if (userList != null && !userList.isEmpty()) { userSet = new HashSet<>(userList); List authedUserList = userMapper.queryUserListByAlertGroupId(alertgroupId); - Set authedUserSet = null; if (authedUserList != null && !authedUserList.isEmpty()) { - authedUserSet = new HashSet<>(authedUserList); + Set authedUserSet = new HashSet<>(authedUserList); userSet.removeAll(authedUserSet); } resultUsers = new ArrayList<>(userSet); } - result.put(Constants.DATA_LIST, resultUsers); - putMsg(result, Status.SUCCESS); - - return result; + return resultUsers; } /** @@ -969,18 +870,13 @@ public Map unauthorizedUser(User loginUser, Integer alertgroupId * @return authorized result code */ @Override - public Map authorizedUser(User loginUser, Integer alertGroupId) { - Map result = new HashMap<>(); + public List authorizedUser(User loginUser, Integer alertGroupId) { // only admin can operate - if (check(result, !isAdmin(loginUser), Status.USER_NO_OPERATION_PERM)) { + if (!isAdmin(loginUser)) { log.warn("Only admin can authorize user."); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } - List userList = userMapper.queryUserListByAlertGroupId(alertGroupId); - result.put(Constants.DATA_LIST, userList); - putMsg(result, Status.SUCCESS); - - return result; + return userMapper.queryUserListByAlertGroupId(alertGroupId); } /** @@ -1026,24 +922,17 @@ private String checkUserParams(String userName, String password, String email, S */ @Override @Transactional - public Map registerUser(String userName, String userPassword, String repeatPassword, String email) { - Map result = new HashMap<>(); - + public User registerUser(String userName, String userPassword, String repeatPassword, String email) { // check user params String msg = this.checkUserParams(userName, userPassword, email, ""); if (!StringUtils.isEmpty(msg)) { - putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, msg); - return result; + throw new ServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, msg); } if (!userPassword.equals(repeatPassword)) { - putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, "two passwords are not same"); - return result; + throw new ServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, "two passwords are not same"); } - User user = createUser(userName, userPassword, email, -1, "", "", Flag.NO.ordinal()); - putMsg(result, Status.SUCCESS); - result.put(Constants.DATA_LIST, user); - return result; + return createUser(userName, userPassword, email, -1, "", "", Flag.NO.ordinal()); } /** @@ -1054,40 +943,30 @@ public Map registerUser(String userName, String userPassword, St * @return create result code */ @Override - public Map activateUser(User loginUser, String userName) { - Map result = new HashMap<>(); - result.put(Constants.STATUS, false); + public User activateUser(User loginUser, String userName) { if (!isAdmin(loginUser)) { - putMsg(result, Status.USER_NO_OPERATION_PERM); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } if (!CheckUtils.checkUserName(userName)) { - putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, userName); - return result; + throw new ServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, userName); } User user = userMapper.queryByUserNameAccurately(userName); if (user == null) { - putMsg(result, Status.USER_NOT_EXIST, userName); - return result; + throw new ServiceException(Status.USER_NOT_EXIST, userName); } if (user.getState() != Flag.NO.ordinal()) { - putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, userName); - return result; + throw new ServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, userName); } user.setState(Flag.YES.ordinal()); - Date now = new Date(); - user.setUpdateTime(now); + user.setUpdateTime(new Date()); userMapper.updateById(user); - User responseUser = userMapper.queryByUserNameAccurately(userName); - putMsg(result, Status.SUCCESS); - result.put(Constants.DATA_LIST, responseUser); - return result; + return userMapper.queryByUserNameAccurately(userName); } /** @@ -1099,44 +978,37 @@ public Map activateUser(User loginUser, String userName) { */ @Override public Map batchActivateUser(User loginUser, List userNames) { - Map result = new HashMap<>(); - if (!isAdmin(loginUser)) { - putMsg(result, Status.USER_NO_OPERATION_PERM); - return result; + throw new ServiceException(Status.USER_NO_OPERATION_PERM); } int totalSuccess = 0; List successUserNames = new ArrayList<>(); - Map successRes = new HashMap<>(); int totalFailed = 0; List> failedInfo = new ArrayList<>(); - Map failedRes = new HashMap<>(); for (String userName : userNames) { - Map tmpResult = activateUser(loginUser, userName); - if (tmpResult.get(Constants.STATUS) != Status.SUCCESS) { + try { + activateUser(loginUser, userName); + totalSuccess++; + successUserNames.add(userName); + } catch (ServiceException e) { totalFailed++; Map failedBody = new HashMap<>(); failedBody.put("userName", userName); - Status status = (Status) tmpResult.get(Constants.STATUS); - String errorMessage = MessageFormat.format(status.getMsg(), userName); - failedBody.put("msg", errorMessage); + failedBody.put("msg", e.getMessage()); failedInfo.add(failedBody); - } else { - totalSuccess++; - successUserNames.add(userName); } } + Map successRes = new HashMap<>(); successRes.put("sum", totalSuccess); successRes.put("userName", successUserNames); + Map failedRes = new HashMap<>(); failedRes.put("sum", totalFailed); failedRes.put("info", failedInfo); Map res = new HashMap<>(); res.put("success", successRes); res.put("failed", failedRes); - putMsg(result, Status.SUCCESS); - result.put(Constants.DATA_LIST, res); - return result; + return res; } /** diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java index a972c2567848..7c071a93a377 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java @@ -30,7 +30,6 @@ import org.apache.dolphinscheduler.api.service.impl.UsersServiceImpl; import org.apache.dolphinscheduler.api.utils.PageInfo; import org.apache.dolphinscheduler.api.utils.Result; -import org.apache.dolphinscheduler.common.constants.Constants; import org.apache.dolphinscheduler.common.enums.AuthorizationType; import org.apache.dolphinscheduler.common.enums.UserType; import org.apache.dolphinscheduler.common.utils.EncryptionUtils; @@ -47,8 +46,6 @@ import org.apache.dolphinscheduler.dao.mapper.TenantMapper; import org.apache.dolphinscheduler.dao.mapper.UserMapper; -import org.apache.commons.collections4.CollectionUtils; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -73,8 +70,6 @@ @MockitoSettings(strictness = Strictness.LENIENT) public class UsersServiceTest { - private static final Logger logger = LoggerFactory.getLogger(UsersServiceTest.class); - @InjectMocks private UsersServiceImpl usersService; @@ -121,58 +116,64 @@ public void testCreateUserForLdap() { } @Test - public void testCreateUser() { - User user = new User(); - user.setUserType(UserType.ADMIN_USER); + public void testCreateUser() throws Exception { + User loginUser = new User(); + loginUser.setUserType(UserType.ADMIN_USER); String userName = "userTest0001~"; String userPassword = "userTest"; String email = "123@qq.com"; int tenantId = Integer.MAX_VALUE; String phone = "13456432345"; int state = 1; - try { - // userName error - Map result = - usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); - logger.info(result.toString()); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - userName = "userTest0001"; - userPassword = "userTest000111111111111111"; - // password error - result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); - logger.info(result.toString()); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - userPassword = "userTest0001"; - email = "1q.com"; - // email error - result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); - logger.info(result.toString()); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - email = "122222@qq.com"; - phone = "2233"; - // phone error - result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); - logger.info(result.toString()); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - phone = "13456432345"; - // tenantId not exists - result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); - logger.info(result.toString()); - Assertions.assertEquals(Status.TENANT_NOT_EXIST, result.get(Constants.STATUS)); - // success - Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - result = usersService.createUser(user, userName, userPassword, email, 1, phone, queueName, state); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - - } catch (Exception e) { - logger.error(Status.CREATE_USER_ERROR.getMsg(), e); - Assertions.assertTrue(false); - } + + // userName error + final String userNameInvalid = userName; + final String passwordInitial = userPassword; + final String emailInitial = email; + final String phoneInitial = phone; + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.createUser(loginUser, userNameInvalid, passwordInitial, emailInitial, tenantId, + phoneInitial, queueName, state)); + + // password error + userName = "userTest0001"; + userPassword = "userTest000111111111111111"; + final String userNameOk = userName; + final String passwordInvalid = userPassword; + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.createUser(loginUser, userNameOk, passwordInvalid, emailInitial, tenantId, + phoneInitial, queueName, state)); + + // email error + userPassword = "userTest0001"; + email = "1q.com"; + final String passwordOk = userPassword; + final String emailInvalid = email; + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.createUser(loginUser, userNameOk, passwordOk, emailInvalid, tenantId, phoneInitial, + queueName, state)); + + // phone error + email = "122222@qq.com"; + phone = "2233"; + final String emailOk = email; + final String phoneInvalid = phone; + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.createUser(loginUser, userNameOk, passwordOk, emailOk, tenantId, phoneInvalid, + queueName, state)); + + // tenantId not exists + phone = "13456432345"; + final String phoneOk = phone; + assertThrowsServiceException(Status.TENANT_NOT_EXIST, + () -> usersService.createUser(loginUser, userNameOk, passwordOk, emailOk, tenantId, phoneOk, queueName, + state)); + + // success + Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); + User created = + usersService.createUser(loginUser, userNameOk, passwordOk, emailOk, 1, phoneOk, queueName, state); + Assertions.assertNotNull(created); } @Test @@ -182,8 +183,7 @@ public void testQueryUser() { when(userMapper.queryUserByNamePassword(userName, EncryptionUtils.getMd5(userPassword))) .thenReturn(getGeneralUser()); User queryUser = usersService.queryUser(userName, userPassword); - logger.info(queryUser.toString()); - Assertions.assertTrue(queryUser != null); + Assertions.assertNotNull(queryUser); } @Test @@ -231,20 +231,14 @@ public void testQueryUserList() { USER_MANAGER, serviceLogger)).thenReturn(true); Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, serviceLogger)).thenReturn(false); - Map result = usersService.queryUserList(user); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, () -> usersService.queryUserList(user)); // success - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ACCESS_TOKEN, 1, - USER_MANAGER, serviceLogger)).thenReturn(true); Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, serviceLogger)).thenReturn(true); - user.setUserType(UserType.ADMIN_USER); when(userMapper.queryEnabledUsers()).thenReturn(getUserList()); - result = usersService.queryUserList(user); - List userList = (List) result.get(Constants.DATA_LIST); - Assertions.assertTrue(userList.size() > 0); + List users = usersService.queryUserList(user); + Assertions.assertFalse(users.isEmpty()); } @Test @@ -256,7 +250,6 @@ public void testQueryUserListPage() { // no operate Result result = usersService.queryUserList(user, "userTest", 1, 10); - logger.info(result.toString()); Assertions.assertEquals(Status.USER_NO_OPERATION_PERM.getCode(), (int) result.getCode()); // success @@ -264,7 +257,7 @@ public void testQueryUserListPage() { result = usersService.queryUserList(user, "userTest", 1, 10); Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); PageInfo pageInfo = (PageInfo) result.getData(); - Assertions.assertTrue(pageInfo.getTotalList().size() > 0); + Assertions.assertFalse(pageInfo.getTotalList().isEmpty()); } @Test @@ -342,36 +335,26 @@ public void testUpdateUserSimple() { @Test public void testDeleteUserById() { User loginUser = new User(); - try { - when(userMapper.queryTenantCodeByUserId(1)).thenReturn(getUser()); - when(userMapper.selectById(1)).thenReturn(getUser()); - when(userMapper.deleteById(1)).thenReturn(1); - // no operate - Map result = usersService.deleteUserById(loginUser, 3); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); - - // user not exist - loginUser.setUserType(UserType.ADMIN_USER); - result = usersService.deleteUserById(loginUser, 3); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); - - // user is project owner - Mockito.when(projectMapper.queryProjectCreatedByUser(1)).thenReturn(Lists.newArrayList(new Project())); - result = usersService.deleteUserById(loginUser, 1); - Assertions.assertEquals(Status.TRANSFORM_PROJECT_OWNERSHIP, result.get(Constants.STATUS)); - - // success - Mockito.when(projectMapper.queryProjectCreatedByUser(1)).thenReturn(null); - result = usersService.deleteUserById(loginUser, 1); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - } catch (Exception e) { - logger.error("delete user error", e); - Assertions.assertTrue(false); - } + when(userMapper.queryTenantCodeByUserId(1)).thenReturn(getUser()); + when(userMapper.selectById(1)).thenReturn(getUser()); + when(userMapper.deleteById(1)).thenReturn(1); + // no operate + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.deleteUserById(loginUser, 3)); + + // user not exist + loginUser.setUserType(UserType.ADMIN_USER); + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.deleteUserById(loginUser, 3)); + + // user is project owner + Mockito.when(projectMapper.queryProjectCreatedByUser(1)).thenReturn(Lists.newArrayList(new Project())); + assertThrowsServiceException(Status.TRANSFORM_PROJECT_OWNERSHIP, + () -> usersService.deleteUserById(loginUser, 1)); + // success + Mockito.when(projectMapper.queryProjectCreatedByUser(1)).thenReturn(null); + assertDoesNotThrow(() -> usersService.deleteUserById(loginUser, 1)); } @Test @@ -384,23 +367,19 @@ public void testGrantProject() { loginUser.setId(1); loginUser.setUserType(UserType.ADMIN_USER); when(userMapper.selectById(userId)).thenReturn(null); - Map result = usersService.grantProject(loginUser, userId, projectIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.grantProject(loginUser, userId, projectIds)); // SUCCESS when(userMapper.selectById(userId)).thenReturn(getUser()); - result = usersService.grantProject(loginUser, userId, projectIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + assertDoesNotThrow(() -> usersService.grantProject(loginUser, userId, projectIds)); // ERROR: NO_CURRENT_OPERATING_PERMISSION loginUser.setId(3); loginUser.setUserType(UserType.GENERAL_USER); when(userMapper.selectById(3)).thenReturn(loginUser); - result = this.usersService.grantProject(loginUser, userId, projectIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.NO_CURRENT_OPERATING_PERMISSION, + () -> usersService.grantProject(loginUser, userId, projectIds)); } @Test @@ -413,23 +392,19 @@ public void testGrantProjectWithReadPerm() { loginUser.setId(1); loginUser.setUserType(UserType.ADMIN_USER); when(userMapper.selectById(userId)).thenReturn(null); - Map result = usersService.grantProjectWithReadPerm(loginUser, userId, projectIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.grantProjectWithReadPerm(loginUser, userId, projectIds)); // SUCCESS when(userMapper.selectById(userId)).thenReturn(getUser()); - result = usersService.grantProjectWithReadPerm(loginUser, userId, projectIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + assertDoesNotThrow(() -> usersService.grantProjectWithReadPerm(loginUser, userId, projectIds)); // ERROR: NO_CURRENT_OPERATING_PERMISSION loginUser.setId(3); loginUser.setUserType(UserType.GENERAL_USER); when(userMapper.selectById(3)).thenReturn(loginUser); - result = this.usersService.grantProjectWithReadPerm(loginUser, userId, projectIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.NO_CURRENT_OPERATING_PERMISSION, + () -> usersService.grantProjectWithReadPerm(loginUser, userId, projectIds)); } @Test @@ -444,35 +419,28 @@ public void testGrantProjectByCode() { // ERROR: USER_NOT_EXIST User loginUser = new User(); - Map result = this.usersService.grantProjectByCode(loginUser, 999, projectCode); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.grantProjectByCode(loginUser, 999, projectCode)); // ERROR: PROJECT_NOT_FOUNT - result = this.usersService.grantProjectByCode(loginUser, authorizer, 999); - logger.info(result.toString()); - Assertions.assertEquals(Status.PROJECT_NOT_FOUND, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.PROJECT_NOT_FOUND, + () -> usersService.grantProjectByCode(loginUser, authorizer, 999)); // ERROR: USER_NO_OPERATION_PERM loginUser.setId(999); loginUser.setUserType(UserType.GENERAL_USER); - result = this.usersService.grantProjectByCode(loginUser, authorizer, projectCode); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.grantProjectByCode(loginUser, authorizer, projectCode)); // SUCCESS: USER IS PROJECT OWNER loginUser.setId(projectCreator); loginUser.setUserType(UserType.GENERAL_USER); - result = this.usersService.grantProjectByCode(loginUser, authorizer, projectCode); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + assertDoesNotThrow(() -> usersService.grantProjectByCode(loginUser, authorizer, projectCode)); // SUCCESS: USER IS ADMINISTRATOR loginUser.setId(999); loginUser.setUserType(UserType.ADMIN_USER); - result = this.usersService.grantProjectByCode(loginUser, authorizer, projectCode); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + assertDoesNotThrow(() -> usersService.grantProjectByCode(loginUser, authorizer, projectCode)); } @Test @@ -484,23 +452,19 @@ public void testRevokeProject() { // user no permission User loginUser = new User(); loginUser.setId(0); - Map result = this.usersService.revokeProject(loginUser, 1, projectCode); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.revokeProject(loginUser, 1, projectCode)); // user not exist loginUser.setUserType(UserType.ADMIN_USER); - result = this.usersService.revokeProject(loginUser, 2, projectCode); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.revokeProject(loginUser, 2, projectCode)); // success Project project = new Project(); project.setId(0); Mockito.when(this.projectMapper.queryByCode(Mockito.anyLong())).thenReturn(project); - result = this.usersService.revokeProject(loginUser, 1, projectCode); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + assertDoesNotThrow(() -> usersService.revokeProject(loginUser, 1, projectCode)); } @Test @@ -511,21 +475,17 @@ public void testRevokeProjectById() { // user no permission User loginUser = new User(); - Map result = this.usersService.revokeProjectById(loginUser, 1, projectId); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.revokeProjectById(loginUser, 1, projectId)); // user not exist loginUser.setUserType(UserType.ADMIN_USER); - result = this.usersService.revokeProjectById(loginUser, 2, projectId); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.revokeProjectById(loginUser, 2, projectId)); // success Mockito.when(this.projectMapper.queryByCode(Mockito.anyLong())).thenReturn(new Project()); - result = this.usersService.revokeProjectById(loginUser, 1, projectId); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + assertDoesNotThrow(() -> usersService.revokeProjectById(loginUser, 1, projectId)); } @Test @@ -536,14 +496,11 @@ public void testGrantNamespaces() { // user not exist loginUser.setUserType(UserType.ADMIN_USER); - Map result = usersService.grantNamespaces(loginUser, 2, namespaceIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.grantNamespaces(loginUser, 2, namespaceIds)); // success when(k8sNamespaceUserMapper.deleteNamespaceRelation(0, 1)).thenReturn(1); - result = usersService.grantNamespaces(loginUser, 1, namespaceIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + assertDoesNotThrow(() -> usersService.grantNamespaces(loginUser, 1, namespaceIds)); } @Test @@ -556,24 +513,19 @@ public void testGrantDataSource() { loginUser.setId(1); loginUser.setUserType(UserType.ADMIN_USER); when(userMapper.selectById(userId)).thenReturn(null); - Map result = usersService.grantDataSource(loginUser, userId, datasourceIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.grantDataSource(loginUser, userId, datasourceIds)); // test admin user when(userMapper.selectById(userId)).thenReturn(getUser()); when(datasourceUserMapper.deleteByUserId(Mockito.anyInt())).thenReturn(1); - result = usersService.grantDataSource(loginUser, userId, datasourceIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + assertDoesNotThrow(() -> usersService.grantDataSource(loginUser, userId, datasourceIds)); // test non-admin user loginUser.setId(2); loginUser.setUserType(UserType.GENERAL_USER); - result = usersService.grantDataSource(loginUser, userId, datasourceIds); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); - + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.grantDataSource(loginUser, userId, datasourceIds)); } private User getLoginUser() { @@ -589,53 +541,39 @@ public void getUserInfo() { loginUser.setUserName("admin"); loginUser.setUserType(UserType.ADMIN_USER); // get admin user - Map result = usersService.getUserInfo(loginUser); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - User tempUser = (User) result.get(Constants.DATA_LIST); - // check userName - Assertions.assertEquals("admin", tempUser.getUserName()); + User adminInfo = usersService.getUserInfo(loginUser); + Assertions.assertEquals("admin", adminInfo.getUserName()); // get general user loginUser.setUserType(null); loginUser.setId(1); when(userMapper.queryDetailsById(1)).thenReturn(getGeneralUser()); when(alertGroupMapper.queryByUserId(1)).thenReturn(getAlertGroups()); - result = usersService.getUserInfo(loginUser); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - tempUser = (User) result.get(Constants.DATA_LIST); - // check userName - Assertions.assertEquals("userTest0001", tempUser.getUserName()); + User generalInfo = usersService.getUserInfo(loginUser); + Assertions.assertEquals("userTest0001", generalInfo.getUserName()); } @Test public void testQueryAllGeneralUsers() { User loginUser = new User(); // no operate - Map result = usersService.queryAllGeneralUsers(loginUser); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.queryAllGeneralUsers(loginUser)); // success loginUser.setUserType(UserType.ADMIN_USER); when(userMapper.queryAllGeneralUser()).thenReturn(getUserList()); - result = usersService.queryAllGeneralUsers(loginUser); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - List userList = (List) result.get(Constants.DATA_LIST); - Assertions.assertTrue(CollectionUtils.isNotEmpty(userList)); + List users = usersService.queryAllGeneralUsers(loginUser); + Assertions.assertFalse(users.isEmpty()); } @Test public void testVerifyUserName() { // not exist user Result result = usersService.verifyUserName("admin89899"); - logger.info(result.toString()); Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); // exist user when(userMapper.queryByUserNameAccurately("userTest0001")).thenReturn(getUser()); result = usersService.verifyUserName("userTest0001"); - logger.info(result.toString()); Assertions.assertEquals(Status.USER_NAME_EXIST.getMsg(), result.getMsg()); } @@ -645,14 +583,12 @@ public void testUnauthorizedUser() { when(userMapper.selectList(null)).thenReturn(getUserList()); when(userMapper.queryUserListByAlertGroupId(2)).thenReturn(getUserList()); // no operate - Map result = usersService.unauthorizedUser(loginUser, 2); - logger.info(result.toString()); - loginUser.setUserType(UserType.ADMIN_USER); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.unauthorizedUser(loginUser, 2)); // success - result = usersService.unauthorizedUser(loginUser, 2); - logger.info(result.toString()); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + loginUser.setUserType(UserType.ADMIN_USER); + List users = usersService.unauthorizedUser(loginUser, 2); + Assertions.assertNotNull(users); } @Test @@ -660,16 +596,12 @@ public void testAuthorizedUser() { User loginUser = new User(); when(userMapper.queryUserListByAlertGroupId(2)).thenReturn(getUserList()); // no operate - Map result = usersService.authorizedUser(loginUser, 2); - logger.info(result.toString()); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.authorizedUser(loginUser, 2)); // success loginUser.setUserType(UserType.ADMIN_USER); - result = usersService.authorizedUser(loginUser, 2); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - List userList = (List) result.get(Constants.DATA_LIST); - logger.info(result.toString()); - Assertions.assertTrue(CollectionUtils.isNotEmpty(userList)); + List users = usersService.authorizedUser(loginUser, 2); + Assertions.assertFalse(users.isEmpty()); } @Test @@ -678,37 +610,43 @@ public void testRegisterUser() { String userPassword = "userTest"; String repeatPassword = "userTest"; String email = "123@qq.com"; - try { - // userName error - Map result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - userName = "userTest0002"; - userPassword = "userTest000111111111111111"; - // password error - result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - userPassword = "userTest0002"; - email = "1q.com"; - // email error - result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - // repeatPassword error - email = "7400@qq.com"; - repeatPassword = "userPassword"; - result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - // success - repeatPassword = "userTest0002"; - result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - - } catch (Exception e) { - Assertions.assertTrue(false); - } + + // userName error + final String userNameInvalid = userName; + final String passwordInitial = userPassword; + final String repeatInitial = repeatPassword; + final String emailInitial = email; + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.registerUser(userNameInvalid, passwordInitial, repeatInitial, emailInitial)); + + userName = "userTest0002"; + userPassword = "userTest000111111111111111"; + // password error + final String userNameOk = userName; + final String passwordTooLong = userPassword; + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.registerUser(userNameOk, passwordTooLong, repeatInitial, emailInitial)); + + userPassword = "userTest0002"; + email = "1q.com"; + // email error + final String passwordOk = userPassword; + final String emailInvalid = email; + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.registerUser(userNameOk, passwordOk, repeatInitial, emailInvalid)); + + // repeatPassword error + email = "7400@qq.com"; + repeatPassword = "userPassword"; + final String emailOk = email; + final String repeatMismatch = repeatPassword; + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.registerUser(userNameOk, passwordOk, repeatMismatch, emailOk)); + + // success + repeatPassword = "userTest0002"; + User registered = usersService.registerUser(userNameOk, passwordOk, repeatPassword, emailOk); + Assertions.assertNotNull(registered); } @Test @@ -716,34 +654,34 @@ public void testActivateUser() { User user = new User(); user.setUserType(UserType.GENERAL_USER); String userName = "userTest0002~"; - try { - // not admin - Map result = usersService.activateUser(user, userName); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); - - // userName error - user.setUserType(UserType.ADMIN_USER); - result = usersService.activateUser(user, userName); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - // user not exist - userName = "userTest10013"; - result = usersService.activateUser(user, userName); - Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); - - // user state error - userName = "userTest0001"; - when(userMapper.queryByUserNameAccurately(userName)).thenReturn(getUser()); - result = usersService.activateUser(user, userName); - Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); - - // success - when(userMapper.queryByUserNameAccurately(userName)).thenReturn(getDisabledUser()); - result = usersService.activateUser(user, userName); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - } catch (Exception e) { - Assertions.assertTrue(false); - } + + // not admin + final String invalidName = userName; + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.activateUser(user, invalidName)); + + // userName error + user.setUserType(UserType.ADMIN_USER); + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.activateUser(user, invalidName)); + + // user not exist + userName = "userTest10013"; + final String missingName = userName; + assertThrowsServiceException(Status.USER_NOT_EXIST, + () -> usersService.activateUser(user, missingName)); + + // user state error + userName = "userTest0001"; + final String existingName = userName; + when(userMapper.queryByUserNameAccurately(existingName)).thenReturn(getUser()); + assertThrowsServiceException(Status.REQUEST_PARAMS_NOT_VALID_ERROR, + () -> usersService.activateUser(user, existingName)); + + // success + when(userMapper.queryByUserNameAccurately(existingName)).thenReturn(getDisabledUser()); + User activated = usersService.activateUser(user, existingName); + Assertions.assertNotNull(activated); } @Test @@ -756,29 +694,23 @@ public void testBatchActivateUser() { userNames.add("userTest0003~"); userNames.add("userTest0004"); - try { - // not admin - Map result = usersService.batchActivateUser(user, userNames); - Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + // not admin + assertThrowsServiceException(Status.USER_NO_OPERATION_PERM, + () -> usersService.batchActivateUser(user, userNames)); - // batch activate user names - user.setUserType(UserType.ADMIN_USER); - when(userMapper.queryByUserNameAccurately("userTest0001")).thenReturn(getUser()); - when(userMapper.queryByUserNameAccurately("userTest0002")).thenReturn(getDisabledUser()); - result = usersService.batchActivateUser(user, userNames); - Map responseData = (Map) result.get(Constants.DATA_LIST); - Map successData = (Map) responseData.get("success"); - int totalSuccess = (Integer) successData.get("sum"); + // batch activate user names + user.setUserType(UserType.ADMIN_USER); + when(userMapper.queryByUserNameAccurately("userTest0001")).thenReturn(getUser()); + when(userMapper.queryByUserNameAccurately("userTest0002")).thenReturn(getDisabledUser()); + Map result = usersService.batchActivateUser(user, userNames); + Map successData = (Map) result.get("success"); + int totalSuccess = (Integer) successData.get("sum"); - Map failedData = (Map) responseData.get("failed"); - int totalFailed = (Integer) failedData.get("sum"); + Map failedData = (Map) result.get("failed"); + int totalFailed = (Integer) failedData.get("sum"); - Assertions.assertEquals(1, totalSuccess); - Assertions.assertEquals(3, totalFailed); - Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - } catch (Exception e) { - Assertions.assertTrue(false); - } + Assertions.assertEquals(1, totalSuccess); + Assertions.assertEquals(3, totalFailed); } @Test @@ -822,8 +754,6 @@ private User getDisabledUser() { /** * Get project - * - * @return */ private Project getProject() { Project project = new Project(); @@ -868,11 +798,8 @@ private User getUser() { /** * get non-admin user - * - * @return user */ private User getNonAdminUser() { - User user = new User(); user.setId(2); user.setUserType(UserType.GENERAL_USER); @@ -885,8 +812,6 @@ private User getNonAdminUser() { /** * get tenant - * - * @return tenant */ private Tenant getTenant() { Tenant tenant = new Tenant(); @@ -900,5 +825,4 @@ private List getAlertGroups() { alertGroups.add(alertGroup); return alertGroups; } - }