This is an automated email from the ASF dual-hosted git repository.
ruanwenjun pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/dolphinscheduler.git
The following commit(s) were added to refs/heads/dev by this push:
new b589e4fef7 [Improvement-18224][API] Migrate UsersService
Map<String,Object> returns to typed returns (#18234)
b589e4fef7 is described below
commit b589e4fef759309f38746015d218d15823f610f0
Author: Wenjun Ruan <[email protected]>
AuthorDate: Sun May 10 22:18:31 2026 +0800
[Improvement-18224][API] Migrate UsersService Map<String,Object> returns to
typed returns (#18234)
Refactor 17 UsersService methods that returned Map<String, Object> to
typed returns / void with ServiceException, mirroring the pattern
established by EnvironmentService.
Methods migrated:
- createUser(8 args) -> User
- deleteUserById -> void
- grantProject / grantProjectWithReadPerm / grantProjectByCode -> void
- revokeProject / revokeProjectById -> void
- grantNamespaces / grantDataSource -> void
- getUserInfo -> User (tenantCode / alertGroup / timeZone populated,
password stripped)
- queryAllGeneralUsers / queryUserList(User) -> List<User>
- unauthorizedUser / authorizedUser -> List<User>
- registerUser / activateUser -> User
- batchActivateUser -> Map<String, Object> (kept Map; nested success/failed
buckets keep wire field names byte-for-byte)
batchActivateUser switches its inner loop to a try/catch around
activateUser since activateUser now throws ServiceException; the wire
shape (success.{sum, userName} / failed.{sum, info}) is unchanged.
UsersController forwards typed values via Result.success and the
authorizedUser endpoint drops its bespoke try/catch since
ApiException + ApiExceptionHandler now provide the equivalent fallback.
PythonGateway.deleteUser already discarded the return value, so the
void return causes no Py4J impact. The other Py4J / SSO callers all
use the already-typed createUser overloads.
Full module test suite: 682 tests, 0 failures.
---
.../api/controller/UsersController.java | 303 ++++---------
.../dolphinscheduler/api/service/UsersService.java | 168 ++-----
.../api/service/impl/UsersServiceImpl.java | 320 ++++----------
.../api/service/UsersServiceTest.java | 492 +++++++++------------
4 files changed, 404 insertions(+), 879 deletions(-)
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 391ece2a66..f0100d24a6 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<User> 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<String, Object> 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 class UsersController extends BaseController {
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 class UsersController extends BaseController {
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 class UsersController extends BaseController {
@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<String, Object> result = usersService.deleteUserById(loginUser,
id);
- return returnDataList(result);
+ public Result<Void> 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 class UsersController extends BaseController {
@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<String, Object> result = usersService.revokeProjectById(loginUser,
userId, projectIds);
- return returnDataList(result);
+ public Result<Void> 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 class UsersController extends BaseController {
@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<String, Object> result =
usersService.grantProjectWithReadPerm(loginUser, userId, projectIds);
- return returnDataList(result);
+ public Result<Void> 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 class UsersController extends BaseController {
@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<String, Object> result = usersService.grantProject(loginUser,
userId, projectIds);
- return returnDataList(result);
+ public Result<Void> 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 class UsersController extends BaseController {
@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<String, Object> result =
this.usersService.grantProjectByCode(loginUser, userId, projectCode);
- return this.returnDataList(result);
+ public Result<Void> 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 class UsersController extends BaseController {
@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<String, Object> result =
this.usersService.revokeProject(loginUser, userId, projectCode);
- return returnDataList(result);
+ public Result<Void> 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 class UsersController extends BaseController {
@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<String, Object> result = usersService.grantNamespaces(loginUser,
userId, namespaceIds);
- return returnDataList(result);
+ public Result<Void> 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 class UsersController extends BaseController {
@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<String, Object> result = usersService.grantDataSource(loginUser,
userId, datasourceIds);
- return returnDataList(result);
+ public Result<Void> 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<String, Object> result = usersService.getUserInfo(loginUser);
- return returnDataList(result);
+ public Result<User> 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<String, Object> result =
usersService.queryAllGeneralUsers(loginUser);
- return returnDataList(result);
+ public Result<List<User>> 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<String, Object> result = usersService.queryUserList(loginUser);
- return returnDataList(result);
+ public Result<List<User>> 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 class UsersController extends BaseController {
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 class UsersController extends BaseController {
@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<String, Object> result = usersService.unauthorizedUser(loginUser,
alertgroupId);
- return returnDataList(result);
+ public Result<List<User>> 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 class UsersController extends BaseController {
@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<String, Object> 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<List<User>> 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 class UsersController extends BaseController {
@PostMapping("/register")
@ResponseStatus(HttpStatus.OK)
@ApiException(CREATE_USER_ERROR)
- public Result<Object> 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<User> 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<Object> verifyRet = usersService.verifyUserName(userName);
if (verifyRet.getCode() != Status.SUCCESS.getCode()) {
- return verifyRet;
+ return new Result<>(verifyRet.getCode(), verifyRet.getMsg());
}
- Map<String, Object> 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 class UsersController extends BaseController {
@PostMapping("/activate")
@ResponseStatus(HttpStatus.OK)
@ApiException(UPDATE_USER_ERROR)
- public Result<Object> activateUser(@Parameter(hidden = true)
@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestParam(value = "userName")
String userName) {
+ public Result<User> activateUser(@Parameter(hidden = true)
@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
+ @RequestParam(value = "userName") String
userName) {
userName = ParameterUtils.handleEscapes(userName);
- Map<String, Object> 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 class UsersController extends BaseController {
@PostMapping("/batch/activate")
@ResponseStatus(HttpStatus.OK)
@ApiException(UPDATE_USER_ERROR)
- public Result<Object> batchActivateUser(@Parameter(hidden = true)
@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
- @RequestBody List<String>
userNames) {
+ public Result<Map<String, Object>> batchActivateUser(@Parameter(hidden =
true) @RequestAttribute(value = Constants.SESSION_USER) User loginUser,
+ @RequestBody
List<String> userNames) {
List<String> formatUserNames =
userNames.stream().map(ParameterUtils::handleEscapes).collect(Collectors.toList());
- Map<String, Object> 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 cb048d0ce7..487b7170f9 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<String, Object> 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 @@ public interface UsersService {
/**
* 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<User> queryUser(List<Integer> 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 @@ public interface UsersService {
/**
* delete user
- *
- * @param loginUser login user
- * @param id user id
- * @return delete result code
- * @throws Exception exception when operate hdfs
*/
- Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> getUserInfo(User loginUser);
+ User getUserInfo(User loginUser);
/**
- * query user list
- *
- * @param loginUser login user
- * @return user list
+ * query general user list
*/
- Map<String, Object> queryAllGeneralUsers(User loginUser);
+ List<User> queryAllGeneralUsers(User loginUser);
/**
- * query user list
- *
- * @param loginUser login user
- * @return user list
+ * query enabled user list
*/
- Map<String, Object> queryUserList(User loginUser);
+ List<User> queryUserList(User loginUser);
/**
* verify user name exists
- *
- * @param userName user name
- * @return true if user name not exists, otherwise return false
*/
Result<Object> 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<String, Object> unauthorizedUser(User loginUser, Integer alertGroupId);
+ List<User> 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<String, Object> authorizedUser(User loginUser, Integer alertGroupId);
+ List<User> 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<String, Object> 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<String, Object> 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<String, Object> batchActivateUser(User loginUser, List<String>
userNames);
@@ -292,15 +185,6 @@ public interface UsersService {
* Make sure user with given name exists, and create the user if not exists
* <p>
* 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 ec112ef554..111b508598 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.collections4.CollectionUtils;
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<String, Object> createUser(User loginUser,
- String userName,
- String userPassword,
- String email,
- int tenantId,
- String phone,
- String queue,
- int state) throws Exception {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
*/
@Override
@Transactional
- public Map<String, Object> deleteUserById(User loginUser, int id) throws
IOException {
- Map<String, Object> 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<Project> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
*/
@Override
@Transactional(rollbackFor = RuntimeException.class)
- public Map<String, Object> revokeProjectById(User loginUser, int userId,
String projectIds) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
*/
@Override
@Transactional(rollbackFor = RuntimeException.class)
- public Map<String, Object> grantProjectWithReadPerm(User loginUser, int
userId, String projectIds) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
projectUser.setUpdateTime(now);
projectUserMapper.insert(projectUser);
});
- putMsg(result, Status.SUCCESS);
-
- return result;
}
/**
@@ -576,26 +540,21 @@ public class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
*/
@Override
@Transactional
- public Map<String, Object> grantProject(User loginUser, int userId, String
projectIds) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
projectUser.setUpdateTime(now);
projectUserMapper.insert(projectUser);
});
- putMsg(result, Status.SUCCESS);
-
- return result;
}
/**
@@ -625,32 +581,26 @@ public class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
* @return grant result code
*/
@Override
- public Map<String, Object> grantProjectByCode(final User loginUser, final
int userId, final long projectCode) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
* @return
*/
@Override
- public Map<String, Object> revokeProject(User loginUser, int userId, long
projectCode) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
*/
@Override
@Transactional
- public Map<String, Object> grantNamespaces(User loginUser, int userId,
String namespaceIds) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
}
log.info("User is granted permission for namespace, userId:{}.",
tempUser.getId());
-
- putMsg(result, Status.SUCCESS);
-
- return result;
}
/**
@@ -771,25 +705,21 @@ public class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
*/
@Override
@Transactional
- public Map<String, Object> grantDataSource(User loginUser, int userId,
String datasourceIds) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
datasourceUser.setUpdateTime(now);
datasourceUserMapper.insert(datasourceUser);
}
-
- putMsg(result, Status.SUCCESS);
-
- return result;
}
/**
@@ -818,11 +744,8 @@ public class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
* @return user info
*/
@Override
- public Map<String, Object> getUserInfo(User loginUser) {
-
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
// remove password
user.setUserPassword(null);
-
- result.put(Constants.DATA_LIST, user);
-
- putMsg(result, Status.SUCCESS);
- return result;
+ return user;
}
/**
@@ -867,19 +786,13 @@ public class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
* @return user list
*/
@Override
- public Map<String, Object> queryAllGeneralUsers(User loginUser) {
- Map<String, Object> result = new HashMap<>();
+ public List<User> 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<User> userList = userMapper.queryAllGeneralUser();
- result.put(Constants.DATA_LIST, userList);
- putMsg(result, Status.SUCCESS);
-
- return result;
+ return userMapper.queryAllGeneralUser();
}
/**
@@ -889,18 +802,12 @@ public class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
* @return user list
*/
@Override
- public Map<String, Object> queryUserList(User loginUser) {
- Map<String, Object> result = new HashMap<>();
+ public List<User> 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<User> userList = userMapper.queryEnabledUsers();
- result.put(Constants.DATA_LIST, userList);
- putMsg(result, Status.SUCCESS);
-
- return result;
+ return userMapper.queryEnabledUsers();
}
/**
@@ -931,34 +838,28 @@ public class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
* @return unauthorize result code
*/
@Override
- public Map<String, Object> unauthorizedUser(User loginUser, Integer
alertgroupId) {
-
- Map<String, Object> result = new HashMap<>();
+ public List<User> 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<User> userList = userMapper.selectList(null);
List<User> resultUsers = new ArrayList<>();
- Set<User> userSet = null;
+ Set<User> userSet;
if (userList != null && !userList.isEmpty()) {
userSet = new HashSet<>(userList);
List<User> authedUserList =
userMapper.queryUserListByAlertGroupId(alertgroupId);
- Set<User> authedUserSet = null;
if (authedUserList != null && !authedUserList.isEmpty()) {
- authedUserSet = new HashSet<>(authedUserList);
+ Set<User> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
* @return authorized result code
*/
@Override
- public Map<String, Object> authorizedUser(User loginUser, Integer
alertGroupId) {
- Map<String, Object> result = new HashMap<>();
+ public List<User> 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<User> userList =
userMapper.queryUserListByAlertGroupId(alertGroupId);
- result.put(Constants.DATA_LIST, userList);
- putMsg(result, Status.SUCCESS);
-
- return result;
+ return userMapper.queryUserListByAlertGroupId(alertGroupId);
}
/**
@@ -1026,24 +922,17 @@ public class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
*/
@Override
@Transactional
- public Map<String, Object> registerUser(String userName, String
userPassword, String repeatPassword, String email) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
* @return create result code
*/
@Override
- public Map<String, Object> activateUser(User loginUser, String userName) {
- Map<String, Object> 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 class UsersServiceImpl extends BaseServiceImpl
implements UsersService {
*/
@Override
public Map<String, Object> batchActivateUser(User loginUser, List<String>
userNames) {
- Map<String, Object> 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<String> successUserNames = new ArrayList<>();
- Map<String, Object> successRes = new HashMap<>();
int totalFailed = 0;
List<Map<String, String>> failedInfo = new ArrayList<>();
- Map<String, Object> failedRes = new HashMap<>();
for (String userName : userNames) {
- Map<String, Object> tmpResult = activateUser(loginUser, userName);
- if (tmpResult.get(Constants.STATUS) != Status.SUCCESS) {
+ try {
+ activateUser(loginUser, userName);
+ totalSuccess++;
+ successUserNames.add(userName);
+ } catch (ServiceException e) {
totalFailed++;
Map<String, String> 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<String, Object> successRes = new HashMap<>();
successRes.put("sum", totalSuccess);
successRes.put("userName", successUserNames);
+ Map<String, Object> failedRes = new HashMap<>();
failedRes.put("sum", totalFailed);
failedRes.put("info", failedInfo);
Map<String, Object> 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 a972c25678..7c071a93a3 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.BaseServiceImpl;
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.ProjectUserMapper;
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 @@ import com.google.common.collect.Lists;
@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 class UsersServiceTest {
}
@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 = "[email protected]";
int tenantId = Integer.MAX_VALUE;
String phone = "13456432345";
int state = 1;
- try {
- // userName error
- Map<String, Object> 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 = "[email protected]";
- 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 = "[email protected]";
+ 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 class UsersServiceTest {
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 class UsersServiceTest {
USER_MANAGER, serviceLogger)).thenReturn(true);
Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN,
null, 0,
serviceLogger)).thenReturn(false);
- Map<String, Object> 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<User> userList = (List<User>) result.get(Constants.DATA_LIST);
- Assertions.assertTrue(userList.size() > 0);
+ List<User> users = usersService.queryUserList(user);
+ Assertions.assertFalse(users.isEmpty());
}
@Test
@@ -256,7 +250,6 @@ public class UsersServiceTest {
// 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 class UsersServiceTest {
result = usersService.queryUserList(user, "userTest", 1, 10);
Assertions.assertEquals(Status.SUCCESS.getCode(), (int)
result.getCode());
PageInfo<User> pageInfo = (PageInfo<User>) result.getData();
- Assertions.assertTrue(pageInfo.getTotalList().size() > 0);
+ Assertions.assertFalse(pageInfo.getTotalList().isEmpty());
}
@Test
@@ -342,36 +335,26 @@ public class UsersServiceTest {
@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<String, Object> 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 class UsersServiceTest {
loginUser.setId(1);
loginUser.setUserType(UserType.ADMIN_USER);
when(userMapper.selectById(userId)).thenReturn(null);
- Map<String, Object> 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 class UsersServiceTest {
loginUser.setId(1);
loginUser.setUserType(UserType.ADMIN_USER);
when(userMapper.selectById(userId)).thenReturn(null);
- Map<String, Object> 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 class UsersServiceTest {
// ERROR: USER_NOT_EXIST
User loginUser = new User();
- Map<String, Object> 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 class UsersServiceTest {
// user no permission
User loginUser = new User();
loginUser.setId(0);
- Map<String, Object> 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 class UsersServiceTest {
// user no permission
User loginUser = new User();
- Map<String, Object> 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 class UsersServiceTest {
// user not exist
loginUser.setUserType(UserType.ADMIN_USER);
- Map<String, Object> 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 class UsersServiceTest {
loginUser.setId(1);
loginUser.setUserType(UserType.ADMIN_USER);
when(userMapper.selectById(userId)).thenReturn(null);
- Map<String, Object> 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 class UsersServiceTest {
loginUser.setUserName("admin");
loginUser.setUserType(UserType.ADMIN_USER);
// get admin user
- Map<String, Object> 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<String, Object> 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<User> userList = (List<User>) result.get(Constants.DATA_LIST);
- Assertions.assertTrue(CollectionUtils.isNotEmpty(userList));
+ List<User> 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 class UsersServiceTest {
when(userMapper.selectList(null)).thenReturn(getUserList());
when(userMapper.queryUserListByAlertGroupId(2)).thenReturn(getUserList());
// no operate
- Map<String, Object> 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<User> users = usersService.unauthorizedUser(loginUser, 2);
+ Assertions.assertNotNull(users);
}
@Test
@@ -660,16 +596,12 @@ public class UsersServiceTest {
User loginUser = new User();
when(userMapper.queryUserListByAlertGroupId(2)).thenReturn(getUserList());
// no operate
- Map<String, Object> 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<User> userList = (List<User>) result.get(Constants.DATA_LIST);
- logger.info(result.toString());
- Assertions.assertTrue(CollectionUtils.isNotEmpty(userList));
+ List<User> users = usersService.authorizedUser(loginUser, 2);
+ Assertions.assertFalse(users.isEmpty());
}
@Test
@@ -678,37 +610,43 @@ public class UsersServiceTest {
String userPassword = "userTest";
String repeatPassword = "userTest";
String email = "[email protected]";
- try {
- // userName error
- Map<String, Object> 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 = "[email protected]";
- 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 = "[email protected]";
+ 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 class UsersServiceTest {
User user = new User();
user.setUserType(UserType.GENERAL_USER);
String userName = "userTest0002~";
- try {
- // not admin
- Map<String, Object> 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 class UsersServiceTest {
userNames.add("userTest0003~");
userNames.add("userTest0004");
- try {
- // not admin
- Map<String, Object> 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<String, Object> responseData = (Map<String, Object>)
result.get(Constants.DATA_LIST);
- Map<String, Object> successData = (Map<String, Object>)
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<String, Object> result = usersService.batchActivateUser(user,
userNames);
+ Map<String, Object> successData = (Map<String, Object>)
result.get("success");
+ int totalSuccess = (Integer) successData.get("sum");
- Map<String, Object> failedData = (Map<String, Object>)
responseData.get("failed");
- int totalFailed = (Integer) failedData.get("sum");
+ Map<String, Object> failedData = (Map<String, Object>)
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 @@ public class UsersServiceTest {
/**
* Get project
- *
- * @return
*/
private Project getProject() {
Project project = new Project();
@@ -868,11 +798,8 @@ public class UsersServiceTest {
/**
* 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 @@ public class UsersServiceTest {
/**
* get tenant
- *
- * @return tenant
*/
private Tenant getTenant() {
Tenant tenant = new Tenant();
@@ -900,5 +825,4 @@ public class UsersServiceTest {
alertGroups.add(alertGroup);
return alertGroups;
}
-
}