Search in sources :

Example 16 with IdentityProviderException

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

the class DefaultIdentityProviderImpl method getRoleIdsOfUser.

@Override
public List<String> getRoleIdsOfUser(String userId) throws IdentityProviderException {
    List<String> roleIds = new ArrayList<>();
    Response response = scimServiceStub.getUser(userId);
    if (response == null) {
        String errorMessage = "Error occurred while retrieving user with Id " + userId + ". Error : Response is null.";
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    try {
        if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
            SCIMUser scimUser = (SCIMUser) new GsonDecoder().decode(response, SCIMUser.class);
            if (scimUser != null) {
                List<SCIMUser.SCIMUserGroups> roles = scimUser.getGroups();
                if (roles != null) {
                    roles.forEach(role -> roleIds.add(role.getValue()));
                    String message = "Role Ids of user " + scimUser.getName() + " are successfully retrieved as " + StringUtils.join(roleIds, ", ") + ".";
                    if (log.isDebugEnabled()) {
                        log.debug(message);
                    }
                }
            } else {
                String errorMessage = "Error occurred while retrieving user with user Id " + userId + " from SCIM endpoint. " + "Response body is null or empty.";
                log.error(errorMessage);
                throw new IdentityProviderException("Error occurred while retrieving user with user Id " + userId + " from SCIM endpoint. " + "Response body is null or empty.", ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
            }
        } else {
            String errorMessage = "Error occurred while retrieving role Ids of user with Id " + userId + ". Error : " + getErrorMessage(response);
            log.error(errorMessage);
            throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
        }
    } catch (IOException e) {
        String errorMessage = "Error occurred while parsing response from SCIM endpoint.";
        log.error(errorMessage);
        throw new IdentityProviderException("Error occurred while parsing response from SCIM endpoint for ", e, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    return roleIds;
}
Also used : Response(feign.Response) SCIMUser(org.wso2.carbon.apimgt.core.auth.dto.SCIMUser) ArrayList(java.util.ArrayList) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException)

Example 17 with IdentityProviderException

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

the class DefaultIdentityProviderImpl method getRoleName.

@Override
public String getRoleName(String roleId) throws IdentityProviderException {
    Response response = scimServiceStub.getGroup(roleId);
    if (response == null) {
        String errorMessage = "Error occurred while retrieving name of role with Id " + roleId + ". Error : Response is null.";
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    String displayName;
    try {
        if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
            SCIMGroup scimGroup = (SCIMGroup) new GsonDecoder().decode(response, SCIMGroup.class);
            if (scimGroup != null) {
                displayName = scimGroup.getDisplayName();
                String message = "Display name of role with Id " + roleId + " is successfully retrieved as " + displayName;
                if (log.isDebugEnabled()) {
                    log.debug(message);
                }
            } else {
                String errorMessage = "Error occurred while retrieving role name with role Id " + roleId + " from SCIM endpoint. " + "Response body is null or empty.";
                log.error(errorMessage);
                throw new IdentityProviderException("Error occurred while retrieving role name with role Id " + roleId + " from SCIM endpoint. " + "Response body is null or empty.", ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
            }
        } else {
            String errorMessage = "Error occurred while retrieving name of role with Id " + roleId + ". Error : " + getErrorMessage(response);
            log.error(errorMessage);
            throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
        }
    } catch (IOException e) {
        String errorMessage = "Error occurred while parsing response from SCIM endpoint.";
        log.error(errorMessage);
        throw new IdentityProviderException("Error occurred while parsing response from SCIM endpoint for ", e, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    return displayName;
}
Also used : Response(feign.Response) SCIMGroup(org.wso2.carbon.apimgt.core.auth.dto.SCIMGroup) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException)

Example 18 with IdentityProviderException

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

the class APIPublisherImplTestCase method testUpdateAPIIdentityProviderException.

@Test(description = "IdentityProviderException when updating API when getting permissions of logged in user")
public void testUpdateAPIIdentityProviderException() throws APIManagementException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(ALTERNATIVE_USER, identityProvider, apiDAO);
    API.APIBuilder api = SampleTestObjectCreator.createDefaultAPI();
    String uuid = api.getId();
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api.build());
    Mockito.when(identityProvider.getIdOfUser(ALTERNATIVE_USER)).thenThrow(IdentityProviderException.class);
    try {
        apiPublisher.updateAPI(api);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while calling SCIM endpoint to retrieve user " + ALTERNATIVE_USER + "'s information");
    }
// 
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) API(org.wso2.carbon.apimgt.core.models.API) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Test(org.testng.annotations.Test)

Example 19 with IdentityProviderException

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

the class DefaultIdentityProviderImplTestCase method testGetRoleName.

@Test
public void testGetRoleName() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validRoleId = "ac093278-9343-466c-8a71-af47921a575b";
    String expectedRoleName = "engineer";
    // happy path
    String successfulResponseBody = "{\"displayName\":\"" + expectedRoleName + "\",\"meta\":{\"created\":" + "\"2017-06-26T16:30:42\",\"location\":\"https://localhost:9443/wso2/scim/Groups/" + validRoleId + "\"" + ",\"lastModified\":\"2017-06-26T16:30:42\"},\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"id\":\"" + validRoleId + "\"}";
    Response successfulResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(successfulResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getGroup(validRoleId)).thenReturn(successfulResponse);
    try {
        String roleName = idpImpl.getRoleName(validRoleId);
        Assert.assertEquals(roleName, expectedRoleName);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error path
    // When response is null
    String invalidRoleIdResponseNull = "invalidRoleId_Response_Null";
    Mockito.when(scimServiceStub.getGroup(invalidRoleIdResponseNull)).thenReturn(null);
    try {
        idpImpl.getRoleName(invalidRoleIdResponseNull);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving name of role with Id " + invalidRoleIdResponseNull + ". Error : Response is null.");
    }
    // error path
    // When the request did not return a 200 OK response
    String invalidRoleIdNot200OK = "invalidRoleId_Not_200_OK";
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"Group 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.getGroup(invalidRoleIdNot200OK)).thenReturn(errorResponse);
    try {
        idpImpl.getRoleName(invalidRoleIdNot200OK);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving name of role with Id " + invalidRoleIdNot200OK + ". Error : Group not found in the user store.");
    }
    // Error case - When response body is empty
    String invalidRoleIdResponseEmpty = "invalidRoleId_Response_Empty";
    Response emptyResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body("".getBytes()).build();
    Mockito.when(scimServiceStub.getGroup(invalidRoleIdResponseEmpty)).thenReturn(emptyResponse);
    try {
        idpImpl.getRoleName(invalidRoleIdResponseEmpty);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role name with role Id " + invalidRoleIdResponseEmpty + " from SCIM endpoint. " + "Response body is null or empty.");
    }
}
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 20 with IdentityProviderException

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

the class DefaultIdentityProviderImplTestCase method testRegisterUser.

@Test
public void testRegisterUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    // happy path
    User user = new User();
    user.setFirstName("john");
    user.setLastName("doe");
    user.setUsername("johnd");
    user.setEmail("john@wso2.com");
    user.setPassword(new char[] { 'p', 'a', 's', 's' });
    SCIMUser scimUser = new SCIMUser();
    SCIMUser.SCIMName scimName = new SCIMUser.SCIMName();
    scimName.setGivenName(user.getFirstName());
    scimName.setFamilyName(user.getLastName());
    scimUser.setName(scimName);
    SCIMUser.SCIMUserEmails scimUserEmails = new SCIMUser.SCIMUserEmails(user.getEmail(), "home", true);
    List<SCIMUser.SCIMUserEmails> scimUserEmailList = new ArrayList<>();
    scimUserEmailList.add(scimUserEmails);
    scimUser.setEmails(scimUserEmailList);
    scimUser.setUsername(user.getUsername());
    scimUser.setPassword(String.valueOf(user.getPassword()));
    Response createdResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_201_CREATED).headers(new HashMap<>()).build();
    Mockito.when(scimServiceStub.addUser(scimUser)).thenReturn(createdResponse);
    try {
        idpImpl.registerUser(user);
        Assert.assertTrue(true);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error path
    final int errorSc = APIMgtConstants.HTTPStatusCodes.SC_409_CONFLICT;
    final String errorMsg = "{\"Errors\":[{\"code\":\"409\",\"description\":\"Error in adding the user: test to " + "the user store.\"}]}";
    Response errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(scimServiceStub.addUser(any(SCIMUser.class))).thenReturn(errorResponse);
    try {
        idpImpl.registerUser(user);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (IdentityProviderException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while creating user."));
    }
}
Also used : SCIMUser(org.wso2.carbon.apimgt.core.auth.dto.SCIMUser) User(org.wso2.carbon.apimgt.core.models.User) SCIMUser(org.wso2.carbon.apimgt.core.auth.dto.SCIMUser) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) 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) Test(org.testng.annotations.Test)

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