Search in sources :

Example 11 with IdentityProviderException

use of org.wso2.carbon.apimgt.core.exception.IdentityProviderException in project carbon-apimgt by wso2.

the class AuthenticatorAPIFactoryTestCase method getService.

@Test
public void getService() throws APIMgtDAOException, IdentityProviderException {
    AuthenticatorService expectedService = AuthenticatorAPIFactory.getInstance().getService();
    AuthenticatorService actualService = AuthenticatorAPIFactory.getInstance().getService();
    Assert.assertSame(expectedService, actualService);
    Assert.assertNotNull(expectedService);
}
Also used : AuthenticatorService(org.wso2.carbon.apimgt.rest.api.authenticator.AuthenticatorService) Test(org.junit.Test)

Example 12 with IdentityProviderException

use of org.wso2.carbon.apimgt.core.exception.IdentityProviderException in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetIdOfUser.

@Test
public void testGetIdOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("invalid_user")).thenReturn("invalid_user");
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("John")).thenReturn("John");
    Mockito.when(userNameMapper.getLoggedInUserIDFromPseudoName("invalid_user_giving_null_response")).thenReturn("invalid_user_giving_null_response");
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserName = "John";
    final String validUserSearchQuery = "userName Eq " + validUserName;
    final String expectedUserId = "cfbde56e-8422-498e-b6dc-85a6f1f8b058";
    String invalidUserName = "invalid_user";
    final String invalidUserSearchQuery = "userName Eq " + invalidUserName;
    String userReturningNullResponse = "invalid_user_giving_null_response";
    final String userReturningNullResponseSearchQuery = "userName Eq " + userReturningNullResponse;
    // happy path
    String responseBody = "{\"totalResults\":1,\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"Resources\":" + "[{\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/cfbde56e-8422-498e-b6dc-85a6f1f8b058\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"id\":\"cfbde56e-8422-498e-b6dc-85a6f1f8b058\",\"userName\":\"John\"}]}";
    Response createdResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(responseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchUsers(validUserSearchQuery)).thenReturn(createdResponse);
    try {
        String userId = idpImpl.getIdOfUser(validUserName);
        Assert.assertEquals(userId, expectedUserId);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error path
    // Assuming the user cannot be found - When the request did not return a 200 OK response
    String errorResponse = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response createdResponseNoSuchUser = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponse.getBytes()).build();
    Mockito.when(scimServiceStub.searchUsers(invalidUserSearchQuery)).thenReturn(createdResponseNoSuchUser);
    try {
        idpImpl.getIdOfUser(invalidUserName);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of user " + invalidUserName + ". Error : User not found in the user store.");
    }
    // error path
    // Assuming the response is null
    Mockito.when(scimServiceStub.searchUsers(userReturningNullResponseSearchQuery)).thenReturn(null);
    try {
        idpImpl.getIdOfUser(userReturningNullResponse);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of user " + userReturningNullResponse + ". Error : Response is null.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 13 with IdentityProviderException

use of org.wso2.carbon.apimgt.core.exception.IdentityProviderException in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleId.

@Test
public void testGetRoleId() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validRoleName = "engineer";
    final String validRoleSearchQuery = "displayName Eq " + validRoleName;
    final String expectedRoleId = "ac093278-9343-466c-8a71-af47921a575b";
    String invalidRoleName = "invalid_role";
    final String invalidRoleSearchQuery = "displayName Eq " + invalidRoleName;
    String roleReturningNullResponse = "invalid_user_giving_null_response";
    final String roleReturningNullResponseSearchQuery = "displayName Eq " + roleReturningNullResponse;
    // happy path
    String responseBody = "{\"totalResults\":1,\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"Resources\":" + "[{\"displayName\":\"PRIMARY/engineer\",\"meta\":{\"created\":\"2017-06-02T10:14:42\"," + "\"location\":\"https://localhost:9443/wso2/scim/Groups/ac093278-9343-466c-8a71-af47921a575b\"," + "\"lastModified\":\"2017-06-02T10:14:42\"},\"id\":\"ac093278-9343-466c-8a71-af47921a575b\"}]}";
    Response createdResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(responseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchGroups(validRoleSearchQuery)).thenReturn(createdResponse);
    try {
        String roleId = idpImpl.getRoleId(validRoleName);
        Assert.assertEquals(roleId, expectedRoleId);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error path
    // Assuming the role cannot be found - when returning a not 200 response
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"Group not found in the user store.\"}]}";
    Response createdResponseNoSuchRole = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchGroups(invalidRoleSearchQuery)).thenReturn(createdResponseNoSuchRole);
    try {
        idpImpl.getRoleId(invalidRoleName);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of role " + invalidRoleName + ". Error : Group not found in the user store.");
    }
    // error path
    // Assuming the response is null
    Mockito.when(scimServiceStub.searchGroups(roleReturningNullResponseSearchQuery)).thenReturn(null);
    try {
        idpImpl.getRoleId(roleReturningNullResponse);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of role " + roleReturningNullResponse + ". Error : Response is null.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 14 with IdentityProviderException

use of org.wso2.carbon.apimgt.core.exception.IdentityProviderException in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleIdsOfUser.

@Test
public void testGetRoleIdsOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserId = "a42b4760-120d-432e-8042-4a7f12e3346c";
    String roleName1 = "subscriber";
    String roleId1 = "fb5aaf9c-1fdf-4b2d-86bc-6e3203b99618";
    String roleName2 = "manager";
    String roleId2 = "097435bc-c460-402b-9137-8ab65fd28c3e";
    String roleName3 = "engineer";
    String roleId3 = "ac093278-9343-466c-8a71-af47921a575b";
    List<String> roleIds = new ArrayList<>();
    roleIds.add(roleId1);
    roleIds.add(roleId2);
    roleIds.add(roleId3);
    String successResponseBody = "{\"emails\":[{\"type\":\"home\",\"value\":\"john_home.com\"},{\"type\":\"work\"" + ",\"value\":\"john_work.com\"}],\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/" + validUserId + "\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"name\":{\"familyName\":" + "\"Smith\",\"givenName\":\"John\"},\"groups\":[{\"display\":\"" + roleName1 + "\",\"value\":\"" + roleId1 + "\"},{\"display\":\"" + roleName2 + "\",\"value\":\"" + roleId2 + "\"},{\"display\":\"" + roleName3 + "\",\"value\":\"" + roleId3 + "\"}],\"id\":\"" + validUserId + "\",\"userName\":" + "\"John\"}";
    Response successfulResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(successResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(validUserId)).thenReturn(successfulResponse);
    List<String> roles = idpImpl.getRoleIdsOfUser(validUserId);
    Assert.assertEquals(roleIds.size(), roles.size());
    roles.forEach(roleId -> Assert.assertTrue(roleIds.contains(roleId)));
    // Error case - When response is null
    String invalidUserIdResponseNull = "invalidUserId_Response_Null";
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseNull)).thenReturn(null);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseNull);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with Id " + invalidUserIdResponseNull + ". Error : Response is null.");
    }
    // Error case - When the request did not return a 200 OK response
    String invalidUserIdNot200OK = "invalidUserId_Not_200_OK";
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response errorResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdNot200OK)).thenReturn(errorResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdNot200OK);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role Ids of user with Id " + invalidUserIdNot200OK + ". Error : User not found in the user store.");
    }
    // Error case - When response body is empty
    String invalidUserIdResponseEmpty = "invalidUserId_Response_Empty";
    Response emptyResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body("".getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseEmpty)).thenReturn(emptyResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseEmpty);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with user Id " + invalidUserIdResponseEmpty + " from SCIM endpoint. Response body is null or empty.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) ArrayList(java.util.ArrayList) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 15 with IdentityProviderException

use of org.wso2.carbon.apimgt.core.exception.IdentityProviderException in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImpl method registerUser.

@Override
public void registerUser(User user) throws IdentityProviderException {
    SCIMUser scimUser = new SCIMUser();
    scimUser.setUsername(user.getUsername());
    scimUser.setPassword(new String(user.getPassword()));
    scimUser.setName(new SCIMUser.SCIMName(user.getFirstName(), user.getLastName()));
    List<SCIMUser.SCIMUserEmails> emails = new ArrayList<>();
    emails.add(new SCIMUser.SCIMUserEmails(user.getEmail(), HOME_EMAIL, true));
    scimUser.setEmails(emails);
    Response response = scimServiceStub.addUser(scimUser);
    if (response == null || response.status() != APIMgtConstants.HTTPStatusCodes.SC_201_CREATED) {
        StringBuilder errorMessage = new StringBuilder("Error occurred while creating user. ");
        if (response == null) {
            errorMessage.append("Response is null");
        } else {
            String msg = getErrorMessage(response);
            if (!StringUtils.isEmpty(msg)) {
                errorMessage.append(msg);
            }
        }
        throw new IdentityProviderException(errorMessage.toString(), ExceptionCodes.USER_CREATION_FAILED);
    } else {
        String message = "User  " + user.getUsername() + " is successfully created";
        if (log.isDebugEnabled()) {
            log.debug(message);
        }
    }
}
Also used : Response(feign.Response) SCIMUser(org.wso2.carbon.apimgt.core.auth.dto.SCIMUser) ArrayList(java.util.ArrayList) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException)

Aggregations

IdentityProviderException (org.wso2.carbon.apimgt.core.exception.IdentityProviderException)19 Response (feign.Response)13 Test (org.testng.annotations.Test)9 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 ArrayList (java.util.ArrayList)7 UserNameMapper (org.wso2.carbon.apimgt.core.api.UserNameMapper)6 SCIMServiceStub (org.wso2.carbon.apimgt.core.auth.SCIMServiceStub)6 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)4 SCIMUser (org.wso2.carbon.apimgt.core.auth.dto.SCIMUser)4 JsonObject (com.google.gson.JsonObject)3 JsonParser (com.google.gson.JsonParser)3 GsonDecoder (feign.gson.GsonDecoder)3 IOException (java.io.IOException)3 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)3 API (org.wso2.carbon.apimgt.core.models.API)3 JsonArray (com.google.gson.JsonArray)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 JSONArray (org.json.simple.JSONArray)2 JSONObject (org.json.simple.JSONObject)2