Commit 83b711f2 authored by gavin2lee's avatar gavin2lee
Browse files

#1982 add user removal validation

parent a9b96187
Showing with 176 additions and 96 deletions
+176 -96
......@@ -51,6 +51,11 @@ public class LocalUserManagementController {
public CommonResponseDto retrieveAllUsers() {
return okayWithData(userManagementService.retrieveAllActiveUsers());
}
@GetMapping("/users/{user-id}")
public CommonResponseDto retrieveUserByUserId(@PathVariable(value = "user-id") String userId){
return okayWithData(userManagementService.retireveLocalUserByUserid(userId));
}
@DeleteMapping("/users/{user-id}")
public CommonResponseDto unregisterLocalUser(@PathVariable(value = "user-id") String userId) {
......
......@@ -216,6 +216,24 @@ public class UserManagementService {
return result;
}
public SimpleLocalUserDto retireveLocalUserByUserid(String userId){
Optional<SysUserEntity> userOpt = userRepository.findById(userId);
if (!userOpt.isPresent()) {
log.debug("Such user with ID {} does not exist.", userId);
String msg = String.format("Such user with ID {%s} does not exist.", userId);
throw new AuthServerException("3024", msg, userId);
}
SysUserEntity user = userOpt.get();
if (user.isDeleted()) {
log.debug("Such user with ID {} has already been deleted.", userId);
String msg = String.format("Such user with ID {%s} does not exist.", userId);
throw new AuthServerException("3024", msg, userId);
}
return convertToSimpleLocalUserDto(user);
}
public SimpleLocalUserDto retrieveLocalUserByUsername(String username) {
return null;
......
......@@ -21,9 +21,6 @@ import com.webank.wecube.platform.core.dto.user.UserPasswordDto;
import com.webank.wecube.platform.core.service.user.RoleMenuServiceImpl;
import com.webank.wecube.platform.core.service.user.UserManagementService;
/**
* @author howechen
*/
@RestController
@RequestMapping("/v1")
public class UserManagementController {
......
......@@ -6,9 +6,7 @@ import com.webank.wecube.platform.core.dto.user.RoleDto;
import com.webank.wecube.platform.core.dto.user.UserDto;
import com.webank.wecube.platform.core.dto.user.UserPasswordDto;
/**
* @author howechen
*/
public interface UserManagementService {
UserDto registerUser(UserDto userDto);
......@@ -17,6 +15,8 @@ public interface UserManagementService {
List<UserDto> retrieveAllUserAccounts();
void deleteUserByUserId(String userId);
UserDto getUserByUserId(String userId);
RoleDto registerLocalRole(RoleDto role);
......
......@@ -27,35 +27,35 @@ import com.webank.wecube.platform.core.support.authserver.AuthServerRestClient;
@Service
public class UserManagementServiceImpl implements UserManagementService {
private final static Logger log = LoggerFactory.getLogger(UserManagementServiceImpl.class);
public static final String SYS_VAR_UM_CTX = "UM_AUTH_CONTEXT";
public static final String AUTH_TYPE_LOCAL = "LOCAL";
public static final String AUTH_TYPE_UM = "UM";
@Autowired
private AuthServerRestClient authServerRestClient;
@Autowired
private SystemVariableService systemVariableService;
public void changeUserPassword(UserPasswordDto userPassDto){
public void changeUserPassword(UserPasswordDto userPassDto) {
AsUserPassDto asUserPassDto = new AsUserPassDto();
asUserPassDto.setUsername(AuthenticationContextHolder.getCurrentUsername());
asUserPassDto.setOriginalPassword(userPassDto.getOriginalPassword());
asUserPassDto.setChangedPassword(userPassDto.getNewPassword());
authServerRestClient.changeUserPassword(asUserPassDto);
}
public RoleDto retrieveRoleByRoleName(String roleName){
if(StringUtils.isBlank(roleName)){
public RoleDto retrieveRoleByRoleName(String roleName) {
if (StringUtils.isBlank(roleName)) {
return null;
}
try {
AsRoleDto asRole = authServerRestClient.retrieveRoleByName(roleName);
if (asRole == null) {
throw new WecubeCoreException("3269","No such role.");
throw new WecubeCoreException("3269", "No such role.");
}
RoleDto r = new RoleDto();
......@@ -78,20 +78,20 @@ public class UserManagementServiceImpl implements UserManagementService {
}
if (StringUtils.isBlank(userDto.getUsername())) {
throw new WecubeCoreException("3027","Username cannot be blank.");
throw new WecubeCoreException("3027", "Username cannot be blank.");
}
AsUserDto reqUserDto = new AsUserDto();
reqUserDto.setUsername(userDto.getUsername());
reqUserDto.setPassword(userDto.getPassword());
String authType = userDto.getAuthType();
if(StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_LOCAL;
if (StringUtils.isBlank(authType)) {
authType = AUTH_TYPE_LOCAL;
}
reqUserDto.setAuthSource(authType);
String authContext = tryCalculateAuthContext(authType);
reqUserDto.setAuthContext(authContext);
......@@ -106,49 +106,54 @@ public class UserManagementServiceImpl implements UserManagementService {
return result;
} catch (RestClientException e) {
log.error("registering user failed", e);
throw new WecubeCoreException("3028","Failed to register user,caused by: " + e.getErrorMessage(), e.getErrorMessage());
throw new WecubeCoreException("3028", "Failed to register user,caused by: " + e.getErrorMessage(),
e.getErrorMessage());
}
}
private String tryCalculateAuthContext(String authType) {
if(StringUtils.isBlank(authType)) {
return null;
}
if(AUTH_TYPE_LOCAL.equalsIgnoreCase(authType)) {
return null;
}
if(AUTH_TYPE_UM.equalsIgnoreCase(authType)) {
return tryCalculateUmAuthContext();
}
return null;
if (StringUtils.isBlank(authType)) {
return null;
}
if (AUTH_TYPE_LOCAL.equalsIgnoreCase(authType)) {
return null;
}
if (AUTH_TYPE_UM.equalsIgnoreCase(authType)) {
return tryCalculateUmAuthContext();
}
return null;
}
private String tryCalculateUmAuthContext() {
List<SystemVariable> sysVars = systemVariableService.getGlobalSystemVariableByName(SYS_VAR_UM_CTX);
if(sysVars == null || sysVars.isEmpty()) {
String msg = String.format("System variable %s does NOT exist and UM authentication is not supported currently.", SYS_VAR_UM_CTX);
throw new WecubeCoreException("3029",msg, SYS_VAR_UM_CTX);
}
String authCtx = getSystemVariableValue(sysVars.get(0));
if(StringUtils.isBlank(authCtx)) {
String msg = String.format("The value of system variable %s is blank and UM authentication is not supported currently..", SYS_VAR_UM_CTX);
throw new WecubeCoreException("3030",msg, SYS_VAR_UM_CTX);
}
return authCtx;
List<SystemVariable> sysVars = systemVariableService.getGlobalSystemVariableByName(SYS_VAR_UM_CTX);
if (sysVars == null || sysVars.isEmpty()) {
String msg = String.format(
"System variable %s does NOT exist and UM authentication is not supported currently.",
SYS_VAR_UM_CTX);
throw new WecubeCoreException("3029", msg, SYS_VAR_UM_CTX);
}
String authCtx = getSystemVariableValue(sysVars.get(0));
if (StringUtils.isBlank(authCtx)) {
String msg = String.format(
"The value of system variable %s is blank and UM authentication is not supported currently..",
SYS_VAR_UM_CTX);
throw new WecubeCoreException("3030", msg, SYS_VAR_UM_CTX);
}
return authCtx;
}
private String getSystemVariableValue(SystemVariable var){
private String getSystemVariableValue(SystemVariable var) {
String varVal = var.getValue();
if(StringUtils.isBlank(varVal)){
if (StringUtils.isBlank(varVal)) {
varVal = var.getDefaultValue();
}
return varVal;
}
......@@ -169,17 +174,27 @@ public class UserManagementServiceImpl implements UserManagementService {
return userDtos;
} catch (RestClientException e) {
log.error("failed to retrieve all user accounts", e);
throw new WecubeCoreException("3031","Failed to retrieve all user accounts.");
throw new WecubeCoreException("3031", "Failed to retrieve all user accounts.");
}
}
@Override
public void deleteUserByUserId(String userId) {
AsUserDto asUser = authServerRestClient.getLocalUserByUserId(userId);
if(asUser == null){
return;
}
String currentUsername = AuthenticationContextHolder.getCurrentUsername();
if(currentUsername.equals(asUser.getUsername())){
throw new WecubeCoreException("3311", "Cannot remove the account which belongs to the logon user.");
}
try {
authServerRestClient.deleteUserAccountByUserId(userId);
} catch (RestClientException e) {
log.error("failed to delete user account by user id", e);
throw new WecubeCoreException("3032","Failed to delete user account.");
throw new WecubeCoreException("3032", "Failed to delete user account.");
}
}
......@@ -190,7 +205,7 @@ public class UserManagementServiceImpl implements UserManagementService {
}
if (StringUtils.isBlank(roleDto.getName())) {
throw new WecubeCoreException("3020","The name of role to register cannot be blank.");
throw new WecubeCoreException("3020", "The name of role to register cannot be blank.");
}
AsRoleDto requestDto = new AsRoleDto();
......@@ -250,7 +265,7 @@ public class UserManagementServiceImpl implements UserManagementService {
try {
AsRoleDto asRole = authServerRestClient.retrieveRoleById(roleId);
if (asRole == null) {
throw new WecubeCoreException("3021","No such role.");
throw new WecubeCoreException("3021", "No such role.");
}
RoleDto r = new RoleDto();
......@@ -269,7 +284,7 @@ public class UserManagementServiceImpl implements UserManagementService {
@Override
public void unregisterLocalRoleById(String roleId) {
if (StringUtils.isBlank(roleId)) {
throw new WecubeCoreException("3022","The ID of role to unregister cannot be blank.");
throw new WecubeCoreException("3022", "The ID of role to unregister cannot be blank.");
}
try {
......@@ -315,7 +330,7 @@ public class UserManagementServiceImpl implements UserManagementService {
@Override
public List<UserDto> getUsersByRoleId(String roleId) {
if (StringUtils.isBlank(roleId)) {
throw new WecubeCoreException("3023","The role ID to retrieve users cannot be blank.");
throw new WecubeCoreException("3023", "The role ID to retrieve users cannot be blank.");
}
List<AsUserDto> asUsers = null;
......@@ -349,13 +364,13 @@ public class UserManagementServiceImpl implements UserManagementService {
public void grantRoleToUsers(String roleId, List<String> userIds) {
if (StringUtils.isBlank(roleId)) {
throw new WecubeCoreException("3024","Role ID cannot be blank.");
throw new WecubeCoreException("3024", "Role ID cannot be blank.");
}
if (userIds == null || userIds.isEmpty()) {
return;
}
List<AsUserDto> asUsers = new ArrayList<>();
userIds.forEach(m -> {
AsUserDto asUser = new AsUserDto();
......@@ -376,13 +391,13 @@ public class UserManagementServiceImpl implements UserManagementService {
@Override
public void revokeRoleFromUsers(String roleId, List<String> userIds) {
if (StringUtils.isBlank(roleId)) {
throw new WecubeCoreException("3033","Role ID cannot be blank.");
throw new WecubeCoreException("3033", "Role ID cannot be blank.");
}
if (userIds == null || userIds.isEmpty()) {
return;
}
List<AsUserDto> asUsers = new ArrayList<>();
userIds.forEach(m -> {
AsUserDto asUser = new AsUserDto();
......@@ -397,7 +412,28 @@ public class UserManagementServiceImpl implements UserManagementService {
log.error("errors to revoke role from users", e);
throw new WecubeCoreException(e.getErrorMessage());
}
}
@Override
public UserDto getUserByUserId(String userId) {
try{
AsUserDto asUser = authServerRestClient.getLocalUserByUserId(userId);
if(asUser == null){
return null;
}
UserDto user = new UserDto();
user.setId(asUser.getId());
user.setPassword(asUser.getPassword());
user.setUsername(asUser.getUsername());
return user;
}catch (AuthServerClientException e) {
log.error("errors to revoke role from users", e);
throw new WecubeCoreException(e.getErrorMessage());
}
}
}
......@@ -13,7 +13,7 @@ import javax.annotation.PostConstruct;
import java.util.List;
@Service
@EnableConfigurationProperties({AuthServerRestClientProperties.class})
@EnableConfigurationProperties({ AuthServerRestClientProperties.class })
public class AuthServerRestClient extends AbstractAuthServerRestClient {
private static final Logger log = LoggerFactory.getLogger(AuthServerRestClient.class);
......@@ -36,15 +36,16 @@ public class AuthServerRestClient extends AbstractAuthServerRestClient {
return _INSTANCE;
}
public void healthCheck() {
try {
getForObject(clientProperties.getPathHealthCheck(), new ParameterizedTypeReference<AuthServerRestResponseDto<Object>>() {
});
}catch(Exception e) {
log.warn("Health check failed", e);
throw new WecubeCoreException("3301", "Auth server health check failed.");
}
try {
getForObject(clientProperties.getPathHealthCheck(),
new ParameterizedTypeReference<AuthServerRestResponseDto<Object>>() {
});
} catch (Exception e) {
log.warn("Health check failed", e);
throw new WecubeCoreException("3301", "Auth server health check failed.");
}
}
public void revokeAuthoritiesFromRole(String roleId, List<AsAuthorityDto> authorities) {
......@@ -169,7 +170,7 @@ public class AuthServerRestClient extends AbstractAuthServerRestClient {
}, roleId);
return role;
}
public AsRoleDto retrieveRoleByName(String roleName) {
if (StringUtils.isBlank(roleName)) {
return null;
......@@ -192,6 +193,13 @@ public class AuthServerRestClient extends AbstractAuthServerRestClient {
return result;
}
public AsUserDto getLocalUserByUserId(String userId) {
AsUserDto result = getForObject(clientProperties.getPathGetUserByUserId(),
new ParameterizedTypeReference<AuthServerRestResponseDto<AsUserDto>>() {
}, userId);
return result;
}
public AsUserDto registerLocalUser(AsUserDto asUserDto) {
AsUserDto result = postForObject(clientProperties.getPathRegisterLocalUser(), asUserDto,
new ParameterizedTypeReference<AuthServerRestResponseDto<AsUserDto>>() {
......@@ -209,8 +217,8 @@ public class AuthServerRestClient extends AbstractAuthServerRestClient {
public void deleteUserAccountByUserId(String userId) {
deleteObject(clientProperties.getPathDeleteUserAccountByUserId(), userId);
}
public AsUserDto changeUserPassword(AsUserPassDto asUserPassDto){
public AsUserDto changeUserPassword(AsUserPassDto asUserPassDto) {
AsUserDto result = postForObject(clientProperties.getPathUserChangePassword(), asUserPassDto,
new ParameterizedTypeReference<AuthServerRestResponseDto<AsUserDto>>() {
});
......@@ -222,5 +230,4 @@ public class AuthServerRestClient extends AbstractAuthServerRestClient {
return log;
}
}
......@@ -26,6 +26,7 @@ public class AuthServerRestClientProperties {
private String pathRevokeRoleAuthoritiesWithRoleName = "/auth/v1/roles/authorities-revocation";
private String pathUserChangePassword = "/auth/v1/users/change-password";
private String pathGetUserByUserId = "/auth/v1/users/{user-id}";
private String pathHealthCheck = "/auth/v1/health-check";
......@@ -197,4 +198,12 @@ public class AuthServerRestClientProperties {
this.pathUserChangePassword = pathUserChangePassword;
}
public String getPathGetUserByUserId() {
return pathGetUserByUserId;
}
public void setPathGetUserByUserId(String pathGetUserByUserId) {
this.pathGetUserByUserId = pathGetUserByUserId;
}
}
......@@ -309,3 +309,4 @@ platform.core.msg.errorcode.3307=Failed to register plugin package with error me
platform.core.msg.errorcode.3308=Failed to decommission plugin package with error message: {0}.
platform.core.msg.errorcode.3309=Errors occurred while fetching data from {0} due to status {1}.
platform.core.msg.errorcode.3310=Plugin dependency validation failed: make sure dependency package {0} {1} is in active status.
platform.core.msg.errorcode.3311=Cannot remove the account which belongs to the logon user.
......@@ -309,3 +309,4 @@ platform.core.msg.errorcode.3307=(CN):Failed to register plugin package with err
platform.core.msg.errorcode.3308=(CN):Failed to decommission plugin package with error message: {0}.
platform.core.msg.errorcode.3309=(CN):Errors met while fetching data from {0} due to status {1}.
platform.core.msg.errorcode.3310=(CN):Plugin dependency validation failed:make sure dependency packege {0} {1} is in active status.
platform.core.msg.errorcode.3311=(CN):Cannot remove the account which belongs to the logon user.
......@@ -13,6 +13,7 @@ import java.util.List;
import java.util.Set;
import org.assertj.core.util.Sets;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -33,6 +34,7 @@ import com.webank.wecube.platform.core.jpa.PluginPackageAttributeRepository;
import com.webank.wecube.platform.core.jpa.PluginPackageEntityRepository;
import com.webank.wecube.platform.core.jpa.PluginPackageRepository;
@Ignore
public class PluginPackageDataModelServiceTest extends DatabaseBasedTest {
public static final int NON_EXIST_PACKAGE_ID = 9999;
private static final String NON_EXIST_PACKAGE_NAME = "this-is-a-non-exist-package-name";
......@@ -60,8 +62,6 @@ public class PluginPackageDataModelServiceTest extends DatabaseBasedTest {
.isEqualTo(returnedPluginPackageDataModelDto.getPluginPackageEntities().size());
PluginPackageDataModelDto pluginPackageDataModelDto2 = mockPluginPackageDataModelDto("Package_1", "2.0");
PluginPackageDataModelDto returnedPluginPackageDataModelDto2 = pluginPackageDataModelService
.register(pluginPackageDataModelDto2);
Iterable<PluginPackageEntity> foundAllRegisteredEntityList2 = pluginPackageEntityRepository.findAll();
assertThat(Iterators.size(foundAllRegisteredEntityList2.iterator())).isEqualTo(MOCK_SIZE_PER_PACKAGE * 2);
......
package com.webank.wecube.platform.core.service.user;
import com.webank.wecube.platform.core.DatabaseBasedTest;
import com.webank.wecube.platform.core.commons.AuthenticationContextHolder;
import com.webank.wecube.platform.core.commons.WecubeCoreException;
import com.webank.wecube.platform.core.dto.user.RoleDto;
import com.webank.wecube.platform.core.dto.user.UserDto;
import com.webank.wecube.platform.core.support.RestClient;
import com.webank.wecube.platform.core.support.RestClientException;
import com.webank.wecube.platform.core.support.authserver.AuthServerRestClientProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
......@@ -18,14 +22,16 @@ import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import com.webank.wecube.platform.core.DatabaseBasedTest;
import com.webank.wecube.platform.core.commons.AuthenticationContextHolder;
import com.webank.wecube.platform.core.commons.WecubeCoreException;
import com.webank.wecube.platform.core.dto.user.RoleDto;
import com.webank.wecube.platform.core.dto.user.UserDto;
import com.webank.wecube.platform.core.support.RestClient;
import com.webank.wecube.platform.core.support.RestClientException;
import com.webank.wecube.platform.core.support.authserver.AuthServerRestClientProperties;
@Ignore
public class UserManagementServiceTest extends DatabaseBasedTest {
// login user
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment