diff --git a/core/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java b/core/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java index 05f957fd69..c148b226db 100644 --- a/core/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java @@ -53,6 +53,7 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.jasypt.util.text.BasicTextEncryptor; import org.springframework.beans.factory.annotation.Autowired; @@ -646,7 +647,7 @@ public ApiResponse addNewUser(UserInfoModel newUser, boolean isExternal) throws } catch (Exception e1) { log.error("Try deleting user"); } - if (e.getMessage().contains("should not exist")) { + if (StringUtils.isNotBlank(e.getMessage()) && e.getMessage().contains("should not exist")) { return ApiResponse.notOk(TEAMS_ERR_110); } else { log.error("Error ", e); diff --git a/core/src/test/java/io/aiven/klaw/UtilMethods.java b/core/src/test/java/io/aiven/klaw/UtilMethods.java index 566641faad..ad969be641 100644 --- a/core/src/test/java/io/aiven/klaw/UtilMethods.java +++ b/core/src/test/java/io/aiven/klaw/UtilMethods.java @@ -12,6 +12,7 @@ import io.aiven.klaw.dao.KwKafkaConnector; import io.aiven.klaw.dao.KwTenants; import io.aiven.klaw.dao.MessageSchema; +import io.aiven.klaw.dao.RegisterUserInfo; import io.aiven.klaw.dao.SchemaRequest; import io.aiven.klaw.dao.ServiceAccounts; import io.aiven.klaw.dao.Team; @@ -37,6 +38,7 @@ import io.aiven.klaw.model.enums.KafkaFlavors; import io.aiven.klaw.model.enums.KafkaSupportedProtocol; import io.aiven.klaw.model.enums.MetadataOperationType; +import io.aiven.klaw.model.enums.NewUserStatus; import io.aiven.klaw.model.enums.OperationalRequestType; import io.aiven.klaw.model.enums.PermissionType; import io.aiven.klaw.model.enums.RequestEntityType; @@ -197,6 +199,37 @@ public List getUserInfoListModel(String username, String return userInfoList; } + public RegisterUserInfo getRegisterUserInfoMock(String newUserName, String pwd) { + RegisterUserInfo regUser = new RegisterUserInfo(); + regUser.setUsername(newUserName); + regUser.setFullname("John Doe"); + regUser.setStatus(NewUserStatus.PENDING.value); + regUser.setPwd(pwd); + regUser.setMailid("mail@mail.com"); + regUser.setTeamId(TEST_TENANT_ID + 1); + regUser.setTenantId(TEST_TENANT_ID); + regUser.setRole("USER"); + return regUser; + } + + public List getRegisterUserInfoList( + Map tenantMapMock, int count, String usernamePrefix) { + List userInfoList = new ArrayList<>(); + for (int i = 0; i < count; i++) { + RegisterUserInfo userInfo = new RegisterUserInfo(); + userInfo.setTeamId(i + 1); + userInfo.setUsername(usernamePrefix + i); + userInfo.setMailid(String.format("%s@mail.com", userInfo.getUsername())); + userInfo.setStatus(NewUserStatus.PENDING.value); + userInfo.setTenantId(i + count); + userInfoList.add(userInfo); + + tenantMapMock.put(userInfo.getTenantId(), String.format("tenant%s", userInfo.getTenantId())); + } + + return userInfoList; + } + public Team getTeamDaoMock() { ServiceAccounts serviceAccounts = new ServiceAccounts(); serviceAccounts.setNumberOfAllowedAccounts(-1); diff --git a/core/src/test/java/io/aiven/klaw/service/UsersTeamsControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/UsersTeamsControllerServiceTest.java index e13015e2c6..0f64e86c7f 100644 --- a/core/src/test/java/io/aiven/klaw/service/UsersTeamsControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/UsersTeamsControllerServiceTest.java @@ -2,18 +2,22 @@ import static io.aiven.klaw.error.KlawErrorMessages.TEAMS_ERR_106; import static io.aiven.klaw.error.KlawErrorMessages.TEAMS_ERR_109; +import static io.aiven.klaw.error.KlawErrorMessages.TEAMS_ERR_111; import static io.aiven.klaw.error.KlawErrorMessages.TEAMS_ERR_115; import static io.aiven.klaw.error.KlawErrorMessages.TEAMS_ERR_117; import static io.aiven.klaw.error.KlawErrorMessages.TEAMS_ERR_119; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.aiven.klaw.UtilMethods; @@ -27,6 +31,7 @@ import io.aiven.klaw.helpers.db.rdbms.HandleDbRequestsJdbc; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.enums.ApiResultStatus; +import io.aiven.klaw.model.enums.AuthenticationType; import io.aiven.klaw.model.enums.EntityType; import io.aiven.klaw.model.enums.MetadataOperationType; import io.aiven.klaw.model.enums.NewUserStatus; @@ -35,6 +40,7 @@ import io.aiven.klaw.model.requests.RegisterUserInfoModel; import io.aiven.klaw.model.requests.TeamModel; import io.aiven.klaw.model.requests.UserInfoModel; +import io.aiven.klaw.model.response.RegisterUserInfoModelResponse; import io.aiven.klaw.model.response.ResetPasswordInfo; import io.aiven.klaw.model.response.TeamModelResponse; import io.aiven.klaw.model.response.UserInfoModelResponse; @@ -50,6 +56,7 @@ import java.util.Set; import java.util.UUID; import java.util.stream.Stream; +import org.jasypt.util.text.BasicTextEncryptor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer; @@ -59,6 +66,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.platform.commons.util.StringUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; @@ -67,6 +75,7 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -79,6 +88,11 @@ public class UsersTeamsControllerServiceTest { private static final int TEST_TENANT_ID = 101; private static final int TEST_TEAM_ID = 3; private static final String TEST_TENANT_NAME = "testTenantName"; + private static final String TEST_NEW_USER_UNAME = "newUserUname"; + private static final String ENCRYPTOR_SECRET_KEY = "encryptorSecretKey"; + private static final String TEST_NEW_USER_PWD_PLAIN_TEXT = "newUserPwd"; + private static final String TEST_AUTHENTICATED_USER_UNAME = "authenticatedUserName"; + private static final String TEST_LOGIN_URL = "http://klaw.com/login"; private UtilMethods utilMethods; @Mock InMemoryUserDetailsManager inMemoryUserDetailsManager; @@ -91,13 +105,21 @@ public class UsersTeamsControllerServiceTest { private UsersTeamsControllerService usersTeamsControllerService; private UserInfo userInfo; + private RegisterUserInfo testNewRegUser; private ArgumentCaptor teamCaptor; + private ArgumentCaptor userDetailsArgCaptor; + private ArgumentCaptor userInfoArgCaptor; @BeforeEach public void setUp() { utilMethods = new UtilMethods(); usersTeamsControllerService = new UsersTeamsControllerService(); teamCaptor = ArgumentCaptor.forClass(Team.class); + userDetailsArgCaptor = ArgumentCaptor.forClass(UserDetails.class); + userInfoArgCaptor = ArgumentCaptor.forClass(UserInfo.class); + testNewRegUser = + utilMethods.getRegisterUserInfoMock( + TEST_NEW_USER_UNAME, encodePwd(TEST_NEW_USER_PWD_PLAIN_TEXT)); ReflectionTestUtils.setField( usersTeamsControllerService, "inMemoryUserDetailsManager", inMemoryUserDetailsManager); ReflectionTestUtils.setField(usersTeamsControllerService, "manageDatabase", manageDatabase); @@ -105,7 +127,7 @@ public void setUp() { ReflectionTestUtils.setField( usersTeamsControllerService, "commonUtilsService", commonUtilsService); ReflectionTestUtils.setField( - usersTeamsControllerService, "encryptorSecretKey", "Testsecretkey"); + usersTeamsControllerService, "encryptorSecretKey", ENCRYPTOR_SECRET_KEY); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); userInfo = utilMethods.getUserInfoMockDao(); loginMock(); @@ -942,17 +964,332 @@ public static Stream registerUserInternal() { TEAMS_ERR_115)); } + @ParameterizedTest + @MethodSource + public void getNewUserRequestsSuccess(int count) throws KlawNotAuthorizedException { + int authenticatedUserTenantId = TEST_TENANT_ID; + Map tenantMapMock = utilMethods.getTenantMapMock(); + List regUserList = + utilMethods.getRegisterUserInfoList(tenantMapMock, count, "testUser"); + + when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); + when(commonUtilsService.getTenantId(TEST_AUTHENTICATED_USER_UNAME)) + .thenReturn(authenticatedUserTenantId); + when(handleDbRequests.getAllRegisterUsersInformation()).thenReturn(regUserList); + when(manageDatabase.getTenantMap()).thenReturn(tenantMapMock); + + for (RegisterUserInfo regUser : regUserList) { + when(manageDatabase.getTeamNameFromTeamId(authenticatedUserTenantId, regUser.getTeamId())) + .thenReturn(String.format("%s%s", OCTOPUS, regUser.getTeamId())); + } + + List responseList = + usersTeamsControllerService.getNewUserRequests(); + + assertThat(responseList.size()).isEqualTo(count); + for (int i = 0; i < responseList.size(); i++) { + assertThat(responseList.get(i).getUsername()).isEqualTo(regUserList.get(i).getUsername()); + assertThat(responseList.get(i).getMailid()).isEqualTo(regUserList.get(i).getMailid()); + assertThat(responseList.get(i).getTeam()) + .isEqualTo(String.format("%s%s", OCTOPUS, regUserList.get(i).getTeamId())); + assertThat(responseList.get(i).getStatus()).isEqualTo(regUserList.get(i).getStatus()); + assertThat(responseList.get(i).getTenantId()).isEqualTo(regUserList.get(i).getTenantId()); + assertThat(responseList.get(i).getTenantName()) + .isEqualTo(tenantMapMock.get(regUserList.get(i).getTenantId())); + assertThat(StringUtils.isBlank(responseList.get(i).getPwd())).isTrue(); + } + } + + public static Stream getNewUserRequestsSuccess() { + return Stream.of(Arguments.of(1), Arguments.of(2), Arguments.of(0)); + } + + @Test + public void getNewUserRequestsWithNoRequestsInDBNullPointerException() { + when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); + when(commonUtilsService.getTenantId(TEST_AUTHENTICATED_USER_UNAME)).thenReturn(TEST_TENANT_ID); + when(handleDbRequests.getAllRegisterUsersInformation()).thenReturn(null); + + assertThatExceptionOfType(NullPointerException.class) + .isThrownBy(() -> usersTeamsControllerService.getNewUserRequests()); + + verify(manageDatabase, never()).getTenantMap(); + verify(manageDatabase, never()).getTeamNameFromTeamId(anyInt(), anyInt()); + } + + @Test + public void getNewUserRequestsWithUnAuthorizedUser() { + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(true); + + assertThatExceptionOfType(KlawNotAuthorizedException.class) + .isThrownBy(() -> usersTeamsControllerService.getNewUserRequests()) + .withMessage("You are not authorized to view this information."); + + verify(commonUtilsService, never()).getTenantId(anyString()); + } + + @ParameterizedTest + @MethodSource + public void approveNewUserRequestSuccess(AuthenticationType authType, boolean isExternal) + throws KlawException { + when(handleDbRequests.addNewUser(userInfoArgCaptor.capture())) + .thenReturn(ApiResultStatus.SUCCESS.value); + approveNewUserRequestsSetupTest(authType); + + ApiResponse response = + usersTeamsControllerService.approveNewUserRequests( + testNewRegUser.getUsername(), isExternal, Integer.MIN_VALUE, null); + + assertThat(response.isSuccess()).isTrue(); + approveNewUserRequestsVerifyServiceInteractions(authType, isExternal, 1); + approveNewUserRequestsValidateCapturedUserInfo(authType); + if (authType == AuthenticationType.DATABASE) { + approveNewUserRequestsValidateCapturedUserDetails(); + } + } + + public static Stream approveNewUserRequestSuccess() { + return Stream.of( + Arguments.of(AuthenticationType.DATABASE, true), + Arguments.of(AuthenticationType.DATABASE, false), + Arguments.of(AuthenticationType.ACTIVE_DIRECTORY, true), + Arguments.of(AuthenticationType.ACTIVE_DIRECTORY, false), + Arguments.of(AuthenticationType.LDAP, false)); + } + + @Test + public void approveNewUserRequestSuccessWithEmailAsUname() throws KlawException { + testNewRegUser.setUsername("newuser@klaw.com"); + when(handleDbRequests.addNewUser(userInfoArgCaptor.capture())) + .thenReturn(ApiResultStatus.SUCCESS.value); + approveNewUserRequestsSetupTest(AuthenticationType.DATABASE); + + ApiResponse response = + usersTeamsControllerService.approveNewUserRequests( + testNewRegUser.getUsername(), true, Integer.MIN_VALUE, null); + + assertThat(response.isSuccess()).isTrue(); + approveNewUserRequestsVerifyServiceInteractions(AuthenticationType.DATABASE, true, 1); + approveNewUserRequestsValidateCapturedUserInfo(AuthenticationType.DATABASE); + approveNewUserRequestsValidateCapturedUserDetails(); + } + + @Test + public void approveNewUserRequestsSuccessWithTenantIDNotSet() throws KlawException { + when(handleDbRequests.addNewUser(userInfoArgCaptor.capture())) + .thenReturn(ApiResultStatus.SUCCESS.value); + testNewRegUser.setTenantId(0); + approveNewUserRequestsSetupTest(AuthenticationType.DATABASE); + + ApiResponse response = + usersTeamsControllerService.approveNewUserRequests( + testNewRegUser.getUsername(), true, Integer.MIN_VALUE, null); + + assertThat(response.isSuccess()).isTrue(); + testNewRegUser.setTenantId(TEST_TENANT_ID); + approveNewUserRequestsVerifyServiceInteractions(AuthenticationType.DATABASE, true, 2); + approveNewUserRequestsValidateCapturedUserInfo(AuthenticationType.DATABASE); + approveNewUserRequestsValidateCapturedUserDetails(); + } + + @Test + public void approveNewUserRequestsFailureWithLDAPAuth() { + when(handleDbRequests.addNewUser(userInfoArgCaptor.capture())) + .thenReturn(ApiResultStatus.SUCCESS.value); + approveNewUserRequestsSetupTest(AuthenticationType.LDAP); + + assertThatExceptionOfType(KlawException.class) + .isThrownBy( + () -> + usersTeamsControllerService.approveNewUserRequests( + testNewRegUser.getUsername(), true, Integer.MIN_VALUE, null)) + .withMessage(TEAMS_ERR_111); + + verify(commonUtilsService) + .updateMetadata( + TEST_TENANT_ID, + EntityType.USERS, + MetadataOperationType.CREATE, + testNewRegUser.getUsername()); + verify(commonUtilsService).getTenantId(TEST_AUTHENTICATED_USER_UNAME); + verify(inMemoryUserDetailsManager, never()).createUser(any()); + verify(handleDbRequests, never()).updateNewUserRequest(anyString(), anyString(), anyBoolean()); + verify(mailService, never()).sendMail(anyString(), anyString(), any(), anyString()); + + approveNewUserRequestsValidateCapturedUserInfo(AuthenticationType.LDAP); + } + + @Test + public void approveNewUserRequestsFailureWithUnAuthorizedUser() throws KlawException { + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(true); + + ApiResponse response = + usersTeamsControllerService.approveNewUserRequests( + testNewRegUser.getUsername(), true, Integer.MIN_VALUE, null); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getMessage()).isEqualTo(ApiResponse.NOT_AUTHORIZED.getMessage()); + verifyNoInteractions(handleDbRequests); + verifyNoInteractions(inMemoryUserDetailsManager); + verify(commonUtilsService, never()).getTenantId(anyString()); + verify(commonUtilsService, never()).updateMetadata(anyInt(), any(), any(), anyString()); + verify(commonUtilsService, never()).getLoginUrl(); + verify(mailService, never()).sendMail(anyString(), anyString(), any(), anyString()); + } + @Test - public void getNewUserRequests() {} + public void approveNewUserRequestWithDBApiFailure() throws KlawException { + when(handleDbRequests.addNewUser(userInfoArgCaptor.capture())) + .thenReturn(ApiResultStatus.FAILURE.value); + approveNewUserRequestsSetupTest(AuthenticationType.DATABASE); + + ApiResponse response = + usersTeamsControllerService.approveNewUserRequests( + testNewRegUser.getUsername(), true, Integer.MIN_VALUE, null); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getMessage()).isEqualTo(ApiResultStatus.FAILURE.value); + + verify(inMemoryUserDetailsManager).createUser(userDetailsArgCaptor.capture()); + verify(mailService) + .sendMail( + testNewRegUser.getUsername(), + TEST_NEW_USER_PWD_PLAIN_TEXT, + handleDbRequests, + TEST_LOGIN_URL); + verify(commonUtilsService, never()).getTenantId(anyString()); + verify(commonUtilsService, never()).updateMetadata(anyInt(), any(), any(), anyString()); + verify(handleDbRequests, never()).updateNewUserRequest(anyString(), anyString(), anyBoolean()); + verify(inMemoryUserDetailsManager, never()).deleteUser(anyString()); + + approveNewUserRequestsValidateCapturedUserInfo(AuthenticationType.DATABASE); + approveNewUserRequestsValidateCapturedUserDetails(); + } @Test - public void approveNewUserRequests() {} + public void approveNewUserRequestWithDBExceptionFailure() throws KlawException { + when(handleDbRequests.addNewUser(userInfoArgCaptor.capture())) + .thenThrow(new RuntimeException("This User should not exist")); + approveNewUserRequestsSetupTest(AuthenticationType.DATABASE); + + ApiResponse response = + usersTeamsControllerService.approveNewUserRequests( + testNewRegUser.getUsername(), true, Integer.MIN_VALUE, null); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getMessage()).isEqualTo(ApiResponse.FAILURE.getMessage()); + + verify(inMemoryUserDetailsManager).createUser(userDetailsArgCaptor.capture()); + verify(inMemoryUserDetailsManager).deleteUser(testNewRegUser.getUsername()); + verify(mailService, never()).sendMail(anyString(), anyString(), any(), anyString()); + verify(commonUtilsService, never()).getTenantId(anyString()); + verify(commonUtilsService, never()).updateMetadata(anyInt(), any(), any(), anyString()); + verify(handleDbRequests, never()).updateNewUserRequest(anyString(), anyString(), anyBoolean()); + + approveNewUserRequestsValidateCapturedUserInfo(AuthenticationType.DATABASE); + approveNewUserRequestsValidateCapturedUserDetails(); + } + + @ParameterizedTest + @MethodSource + public void approveNewUserRequestWithInvalidUnameFailure(String invalidUname) + throws KlawException { + testNewRegUser.setUsername(invalidUname); + approveNewUserRequestsSetupTest(AuthenticationType.DATABASE); + + ApiResponse response = + usersTeamsControllerService.approveNewUserRequests( + testNewRegUser.getUsername(), true, Integer.MIN_VALUE, null); + + assertThat(response.isSuccess()).isFalse(); + verify(commonUtilsService, never()).getTenantId(anyString()); + verify(inMemoryUserDetailsManager, never()).createUser(any()); + verify(mailService, never()).sendMail(anyString(), anyString(), any(), anyString()); + verify(handleDbRequests, never()).addNewUser(any()); + verify(commonUtilsService, never()).updateMetadata(anyInt(), any(), any(), anyString()); + verify(inMemoryUserDetailsManager, never()).deleteUser(anyString()); + verify(commonUtilsService, never()).getLoginUrl(); + verify(handleDbRequests, never()).updateNewUserRequest(anyString(), anyString(), anyBoolean()); + } + + public static Stream approveNewUserRequestWithInvalidUnameFailure() { + return Stream.of(Arguments.of("ss"), Arguments.of("sdflk&&klsjdf")); + } @Test - public void declineNewUserRequests() {} + public void declineNewUserRequests() throws KlawException { + when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); + + ApiResponse response = usersTeamsControllerService.declineNewUserRequests(TEST_NEW_USER_UNAME); + + assertThat(response.isSuccess()).isTrue(); + assertThat(response.getMessage()).isEqualTo(ApiResponse.SUCCESS.getMessage()); + verify(handleDbRequests) + .updateNewUserRequest(TEST_NEW_USER_UNAME, TEST_AUTHENTICATED_USER_UNAME, false); + } + + @Test + public void declineNewUserRequestsDBFailure() { + String errMsg = "DB Error"; + when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); + doThrow(new RuntimeException(errMsg)) + .when(handleDbRequests) + .updateNewUserRequest(TEST_NEW_USER_UNAME, TEST_AUTHENTICATED_USER_UNAME, false); + + assertThatExceptionOfType(KlawException.class) + .isThrownBy(() -> usersTeamsControllerService.declineNewUserRequests(TEST_NEW_USER_UNAME)) + .withMessage(errMsg); + } @Test - public void getRegistrationInfoFromId() {} + public void declineNewUserRequestsAuthenticationFailure() throws KlawException { + when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(true); + + ApiResponse response = usersTeamsControllerService.declineNewUserRequests(TEST_NEW_USER_UNAME); + + assertThat(response.isSuccess()).isFalse(); + assertThat(response.getMessage()).isEqualTo(ApiResponse.NOT_AUTHORIZED.getMessage()); + verify(handleDbRequests, never()).updateNewUserRequest(anyString(), anyString(), anyBoolean()); + } + + @Test + public void getRegistrationInfoFromId() { + String testRegId = "testRegId"; + String testStatus = "status"; + when(handleDbRequests.getRegistrationDetails(testRegId, testStatus)).thenReturn(testNewRegUser); + + RegisterUserInfoModelResponse response = + usersTeamsControllerService.getRegistrationInfoFromId(testRegId, testStatus); + + assertThat(response.getUsername()).isEqualTo(testNewRegUser.getUsername()); + assertThat(response.getMailid()).isEqualTo(testNewRegUser.getMailid()); + assertThat(response.getTeam()).isEqualTo(testNewRegUser.getTeam()); + assertThat(response.getStatus()).isEqualTo(testNewRegUser.getStatus()); + assertThat(response.getTenantId()).isEqualTo(testNewRegUser.getTenantId()); + assertThat(response.getFullname()).isEqualTo(testNewRegUser.getFullname()); + assertThat(response.getRole()).isEqualTo(testNewRegUser.getRole()); + assertThat(response.getPwd()).isEqualTo(testNewRegUser.getPwd()); + } + + @Test + public void getRegistrationInfoFromIdNoRegistrationInfo() { + String testRegId = "testRegId"; + String testStatus = "status"; + when(handleDbRequests.getRegistrationDetails(testRegId, testStatus)).thenReturn(null); + + RegisterUserInfoModelResponse response = + usersTeamsControllerService.getRegistrationInfoFromId(testRegId, testStatus); + + assertThat(response).isNull(); + } @Test public void getEnvDetailsFromId() {} @@ -1015,6 +1352,25 @@ public UserInfo generateUser(String username) { return info; } + private BasicTextEncryptor getJasyptEncryptor() { + BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); + textEncryptor.setPasswordCharArray(ENCRYPTOR_SECRET_KEY.toCharArray()); + + return textEncryptor; + } + + private String encodePwd(String pwd) { + return getJasyptEncryptor().encrypt(pwd); + } + + private String decodePwd(String pwd) { + if (pwd != null) { + return getJasyptEncryptor().decrypt(pwd); + } else { + return ""; + } + } + private void getTeamDetailsSetupTest( Map tenantMapMock, Team teamDaoMock, String testUserName) { when(manageDatabase.getTenantMap()).thenReturn(tenantMapMock); @@ -1165,4 +1521,73 @@ private void getMyProfileInfoVerifySwitchTeam( assertThat(userInfoModelResponse.getSwitchAllowedTeamNames().size()).isEqualTo(1); assertThat(userInfoModelResponse.getSwitchAllowedTeamNames().contains(switchTeamName)).isTrue(); } + + private void approveNewUserRequestsSetupTest(AuthenticationType authType) { + ReflectionTestUtils.setField(usersTeamsControllerService, "authenticationType", authType.value); + when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); + when(handleDbRequests.getPendingRegisterUsersInfo(testNewRegUser.getUsername())) + .thenReturn(testNewRegUser); + when(commonUtilsService.getTenantId(TEST_AUTHENTICATED_USER_UNAME)).thenReturn(TEST_TENANT_ID); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); + when(commonUtilsService.getLoginUrl()).thenReturn(TEST_LOGIN_URL); + } + + private void approveNewUserRequestsVerifyServiceInteractions( + AuthenticationType authType, boolean isExternal, int getTenantIdCallCount) { + String sentMailPwd; + if (authType == AuthenticationType.DATABASE) { + verify(inMemoryUserDetailsManager).createUser(userDetailsArgCaptor.capture()); + sentMailPwd = TEST_NEW_USER_PWD_PLAIN_TEXT; + } else { + verify(inMemoryUserDetailsManager, never()).createUser(any()); + sentMailPwd = UsersTeamsControllerService.UNUSED_PASSWD; + } + verify(handleDbRequests) + .updateNewUserRequest(testNewRegUser.getUsername(), TEST_AUTHENTICATED_USER_UNAME, true); + verify(commonUtilsService) + .updateMetadata( + TEST_TENANT_ID, + EntityType.USERS, + MetadataOperationType.CREATE, + testNewRegUser.getUsername()); + verify(commonUtilsService, times(getTenantIdCallCount)) + .getTenantId(TEST_AUTHENTICATED_USER_UNAME); + verify(inMemoryUserDetailsManager, never()).deleteUser(anyString()); + if (isExternal) { + verify(mailService) + .sendMail(testNewRegUser.getUsername(), sentMailPwd, handleDbRequests, TEST_LOGIN_URL); + } else { + verify(commonUtilsService, never()).isNotAuthorizedUser(any(), any(PermissionType.class)); + verify(commonUtilsService, never()).getLoginUrl(); + verify(mailService, never()).sendMail(anyString(), anyString(), any(), anyString()); + } + } + + private void approveNewUserRequestsValidateCapturedUserInfo(AuthenticationType authType) { + UserInfo capturedUserInfo = userInfoArgCaptor.getValue(); + assertThat(capturedUserInfo.getUsername()).isEqualTo(testNewRegUser.getUsername()); + assertThat(capturedUserInfo.getMailid()).isEqualTo(testNewRegUser.getMailid()); + assertThat(capturedUserInfo.getTenantId()).isEqualTo(testNewRegUser.getTenantId()); + assertThat(capturedUserInfo.getTeamId()).isEqualTo(testNewRegUser.getTeamId()); + assertThat(capturedUserInfo.getRole()).isEqualTo(testNewRegUser.getRole()); + assertThat(capturedUserInfo.getFullname()).isEqualTo(testNewRegUser.getFullname()); + if (authType == AuthenticationType.DATABASE) { + assertThat(decodePwd(capturedUserInfo.getPwd())).isEqualTo(TEST_NEW_USER_PWD_PLAIN_TEXT); + } else { + assertThat(capturedUserInfo.getPwd()).isEqualTo(UsersTeamsControllerService.UNUSED_PASSWD); + } + } + + private void approveNewUserRequestsValidateCapturedUserDetails() { + UserDetails capturedUserDetails = userDetailsArgCaptor.getValue(); + assertThat(capturedUserDetails.getUsername()).isEqualTo(testNewRegUser.getUsername()); + assertThat(capturedUserDetails.getAuthorities().size()).isEqualTo(1); + assertThat(capturedUserDetails.getAuthorities().iterator().next().getAuthority()) + .isEqualTo(String.format("ROLE_%s", testNewRegUser.getRole())); + assertThat( + PasswordEncoderFactories.createDelegatingPasswordEncoder() + .matches(TEST_NEW_USER_PWD_PLAIN_TEXT, capturedUserDetails.getPassword())) + .isTrue(); + } }