Search in sources :

Example 11 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImpl method getRoleNamesOfUser.

@Override
public List<String> getRoleNamesOfUser(String userId) throws IdentityProviderException {
    List<String> roleNames = 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 -> roleNames.add(role.getDisplay()));
                    String message = "Role names of user " + scimUser.getName() + " are successfully retrieved as " + StringUtils.join(roleNames, ", ") + ".";
                    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 names 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 roleNames;
}
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 12 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImpl method getRoleId.

@Override
public String getRoleId(String roleName) throws IdentityProviderException {
    Response roleResponse = scimServiceStub.searchGroups(FILTER_PREFIX_ROLE + roleName);
    String roleId;
    if (roleResponse == null) {
        String errorMessage = "Error occurred while retrieving Id of role " + roleName + ". Error : Response is null.";
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    if (roleResponse.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        String responseBody = roleResponse.body().toString();
        JsonParser parser = new JsonParser();
        JsonObject parsedResponseBody = (JsonObject) parser.parse(responseBody);
        JsonArray role = (JsonArray) parsedResponseBody.get(RESOURCES);
        JsonObject scimGroup = (JsonObject) role.get(0);
        roleId = scimGroup.get(ID).getAsString();
        String message = "Id " + roleId + " of role " + scimGroup.get(GROUPNAME).getAsString() + " is successfully retrieved from SCIM endpoint.";
        if (log.isDebugEnabled()) {
            log.debug(message);
        }
    } else {
        String errorMessage = "Error occurred while retrieving Id of role " + roleName + ". Error : " + getErrorMessage(roleResponse);
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    return roleId;
}
Also used : Response(feign.Response) JsonArray(com.google.gson.JsonArray) JsonObject(com.google.gson.JsonObject) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) JsonParser(com.google.gson.JsonParser)

Example 13 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class APIPublisherImpl method getAPIPermissionArray.

/**
 * This method will return map with role names and its permission values.
 *
 * @param permissionJsonString Permission json object a string
 * @return Map of permission values.
 * @throws ParseException If failed to parse the json string.
 */
private HashMap<String, Integer> getAPIPermissionArray(String permissionJsonString) throws ParseException, APIManagementException {
    HashMap<String, Integer> rolePermissionList = new HashMap<String, Integer>();
    JSONParser jsonParser = new JSONParser();
    JSONArray baseJsonArray = (JSONArray) jsonParser.parse(permissionJsonString);
    for (Object aBaseJsonArray : baseJsonArray) {
        JSONObject jsonObject = (JSONObject) aBaseJsonArray;
        String groupId = jsonObject.get(APIMgtConstants.Permission.GROUP_ID).toString();
        JSONArray subJsonArray = (JSONArray) jsonObject.get(APIMgtConstants.Permission.PERMISSION);
        int totalPermissionValue = 0;
        for (Object aSubJsonArray : subJsonArray) {
            if (APIMgtConstants.Permission.READ.equals(aSubJsonArray.toString().trim())) {
                totalPermissionValue += APIMgtConstants.Permission.READ_PERMISSION;
            } else if (APIMgtConstants.Permission.UPDATE.equals(aSubJsonArray.toString().trim())) {
                totalPermissionValue += APIMgtConstants.Permission.UPDATE_PERMISSION;
            } else if (APIMgtConstants.Permission.DELETE.equals(aSubJsonArray.toString().trim())) {
                totalPermissionValue += APIMgtConstants.Permission.DELETE_PERMISSION;
            } else if (APIMgtConstants.Permission.MANAGE_SUBSCRIPTION.equals(aSubJsonArray.toString().trim())) {
                totalPermissionValue += APIMgtConstants.Permission.MANAGE_SUBSCRIPTION_PERMISSION;
            }
        }
        rolePermissionList.put(groupId, totalPermissionValue);
    }
    return rolePermissionList;
}
Also used : JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint)

Example 14 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class APIPublisherImpl method replaceGroupIdWithName.

/**
 * This method replaces the groupId field's value of the api permissions string to the role name before sending to
 * frontend
 *
 * @param permissionString - permissions string containing role ids in the groupId field
 * @return the permission string replacing the groupId field's value to role name
 * @throws ParseException         - if there is an error parsing the permission json
 * @throws APIManagementException - if there is an error getting the IdentityProvider instance
 */
private String replaceGroupIdWithName(String permissionString) throws ParseException, APIManagementException {
    JSONArray updatedPermissionArray = new JSONArray();
    JSONParser jsonParser = new JSONParser();
    JSONArray originalPermissionArray = (JSONArray) jsonParser.parse(permissionString);
    for (Object permissionObj : originalPermissionArray) {
        JSONObject jsonObject = (JSONObject) permissionObj;
        String groupId = (String) jsonObject.get(APIMgtConstants.Permission.GROUP_ID);
        try {
            String groupName = getIdentityProvider().getRoleName(groupId);
            JSONObject updatedPermissionJsonObj = new JSONObject();
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.GROUP_ID, groupName);
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.PERMISSION, jsonObject.get(APIMgtConstants.Permission.PERMISSION));
            updatedPermissionArray.add(updatedPermissionJsonObj);
        } catch (IdentityProviderException e) {
            // lets the execution continue after logging the exception
            String errorMessage = "Error occurred while calling SCIM endpoint to retrieve role name of role " + "with Id " + groupId;
            log.warn(errorMessage, e);
        }
    }
    return updatedPermissionArray.toJSONString();
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException)

Example 15 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class APIStoreImpl method searchCompositeAPIs.

@Override
public List<CompositeAPI> searchCompositeAPIs(String query, int offset, int limit) throws APIManagementException {
    List<CompositeAPI> apiResults;
    // this should be current logged in user
    String user = getUsername();
    // role list of current user
    Set<String> roles = APIUtils.getAllRolesOfUser(user);
    try {
        if (query != null && !query.isEmpty()) {
            apiResults = getApiDAO().searchCompositeAPIs(roles, user, query, offset, limit);
        } else {
            apiResults = getApiDAO().getCompositeAPIs(roles, user, offset, limit);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while updating searching APIs - " + query;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
    return apiResults;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI)

Aggregations

Test (org.testng.annotations.Test)85 ArrayList (java.util.ArrayList)74 UserStoreException (org.wso2.carbon.user.api.UserStoreException)56 HashMap (java.util.HashMap)52 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)42 Connection (java.sql.Connection)36 SQLException (java.sql.SQLException)34 Role (org.wso2.charon3.core.objects.Role)33 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)31 CharonException (org.wso2.charon3.core.exceptions.CharonException)29 RoleBasicInfo (org.wso2.carbon.identity.role.mgt.core.RoleBasicInfo)26 PreparedStatement (java.sql.PreparedStatement)25 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 RoleMapping (org.wso2.carbon.identity.application.common.model.RoleMapping)24 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)23 HashSet (java.util.HashSet)20 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)20 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)19 IdentityRoleManagementClientException (org.wso2.carbon.identity.role.mgt.core.IdentityRoleManagementClientException)19 Matchers.anyString (org.mockito.Matchers.anyString)18