Search in sources :

Example 31 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class APIUtil method getTenantBasedDevPortalContext.

public static String getTenantBasedDevPortalContext(String tenantDomain) throws APIManagementException {
    String context = null;
    try {
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry();
        String resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace(APIConstants.API_DOMAIN_MAPPING_TENANT_ID_IDENTIFIER, tenantDomain);
        if (registry.resourceExists(resourcePath)) {
            Resource resource = registry.get(resourcePath);
            String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
            JSONParser parser = new JSONParser();
            JSONObject mappings = (JSONObject) parser.parse(content);
            if (mappings.containsKey(APIConstants.API_DOMAIN_MAPPINGS_STORE)) {
                JSONObject storeMapping = (JSONObject) mappings.get(APIConstants.API_DOMAIN_MAPPINGS_STORE);
                if (storeMapping.containsKey(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT)) {
                    context = (String) storeMapping.get(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT);
                } else {
                    context = "";
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Error while retrieving gateway domain mappings from registry";
        throw new APIManagementException(msg, e);
    } catch (ClassCastException e) {
        String msg = "Invalid JSON found in the gateway tenant domain mappings";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Malformed JSON found in the gateway tenant domain mappings";
        throw new APIManagementException(msg, e);
    }
    return context;
}
Also used : JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) JSONParser(org.json.simple.parser.JSONParser) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) ParseException(org.json.simple.parser.ParseException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 32 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class APIUtil method clearResourcePermissions.

/**
 * This function is to set resource permissions based on its visibility
 *
 * @param artifactPath API/Product resource path
 * @throws APIManagementException Throwing exception
 */
public static void clearResourcePermissions(String artifactPath, Identifier id, int tenantId) throws APIManagementException {
    try {
        String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(id.getProviderName()));
        if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
            authManager.clearResourceAuthorizations(resourcePath);
        } else {
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            authorizationManager.clearResourceAuthorizations(resourcePath);
        }
    } catch (UserStoreException e) {
        handleException("Error while adding role permissions to API", e);
    }
}
Also used : RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 33 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class APIUtil method setResourcePermissions.

/**
 * This function is to set resource permissions based on its visibility
 *
 * @param visibility   API/Product visibility
 * @param roles        Authorized roles
 * @param artifactPath API/Product resource path
 * @param registry     Registry
 * @throws APIManagementException Throwing exception
 */
public static void setResourcePermissions(String username, String visibility, String[] roles, String artifactPath, Registry registry) throws APIManagementException {
    try {
        String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
        Resource registryResource = null;
        if (registry != null && registry.resourceExists(artifactPath)) {
            registryResource = registry.get(artifactPath);
        }
        StringBuilder publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
        if (registryResource != null) {
            String publisherRole = registryResource.getProperty(APIConstants.PUBLISHER_ROLES);
            if (publisherRole != null) {
                publisherAccessRoles = new StringBuilder(publisherRole);
            }
            if (StringUtils.isEmpty(publisherAccessRoles.toString())) {
                publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
            }
            if (APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(visibility) || APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
                // set publisher
                publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
            // access roles null since store visibility is global. We do not need to add any roles to
            // store_view_role property.
            } else {
                registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
            }
        }
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            // calculate resource path
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            resourcePath = authorizationManager.computePathOnMount(resourcePath);
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
            if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
                boolean isRoleEveryOne = false;
                /*If no roles have defined, authorize for everyone role */
                if (roles != null) {
                    if (roles.length == 1 && "".equals(roles[0])) {
                        authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                        isRoleEveryOne = true;
                    } else {
                        for (String role : roles) {
                            if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role.trim())) {
                                isRoleEveryOne = true;
                            }
                            authManager.authorizeRole(role.trim(), resourcePath, ActionConstants.GET);
                            publisherAccessRoles.append(",").append(role.trim().toLowerCase());
                        }
                    }
                }
                if (!isRoleEveryOne) {
                    authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                }
                authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
                /*If no roles have defined, deny access for everyone & anonymous role */
                if (roles == null) {
                    authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                    authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                } else {
                    for (String role : roles) {
                        authManager.denyRole(role.trim(), resourcePath, ActionConstants.GET);
                    }
                }
            } else {
                authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            }
        } else {
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
                boolean isRoleEveryOne = false;
                if (roles != null) {
                    for (String role : roles) {
                        if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role.trim())) {
                            isRoleEveryOne = true;
                        }
                        authorizationManager.authorizeRole(role.trim(), resourcePath, ActionConstants.GET);
                        publisherAccessRoles.append(",").append(role.toLowerCase());
                    }
                }
                if (!isRoleEveryOne) {
                    authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                }
                authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
                /*If no roles have defined, deny access for everyone & anonymous role */
                if (roles == null) {
                    authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                    authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                } else {
                    for (String role : roles) {
                        authorizationManager.denyRole(role.trim(), resourcePath, ActionConstants.GET);
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Store view roles for " + artifactPath + " : " + publisherAccessRoles.toString());
                }
                authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            }
        }
        if (registryResource != null) {
            registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
            registry.put(artifactPath, registryResource);
        }
    } catch (UserStoreException e) {
        throw new APIManagementException("Error while adding role permissions to API", e);
    } catch (RegistryException e) {
        throw new APIManagementException("Registry exception while adding role permissions to API", e);
    }
}
Also used : Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 34 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class APIUtil method getTenantBasedPublisherContext.

public static String getTenantBasedPublisherContext(String tenantDomain) throws APIManagementException {
    String context = null;
    try {
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry();
        String resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace(APIConstants.API_DOMAIN_MAPPING_TENANT_ID_IDENTIFIER, tenantDomain);
        if (registry.resourceExists(resourcePath)) {
            Resource resource = registry.get(resourcePath);
            String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
            JSONParser parser = new JSONParser();
            JSONObject mappings = (JSONObject) parser.parse(content);
            if (mappings.containsKey(APIConstants.API_DOMAIN_MAPPINGS_PUBLISHER)) {
                JSONObject publisherMapping = (JSONObject) mappings.get(APIConstants.API_DOMAIN_MAPPINGS_PUBLISHER);
                if (publisherMapping.containsKey(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT)) {
                    context = (String) publisherMapping.get(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT);
                } else {
                    context = "";
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Error while retrieving publisher domain mappings from registry";
        throw new APIManagementException(msg, e);
    } catch (ClassCastException e) {
        String msg = "Invalid JSON found in the publisher tenant domain mappings";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Malformed JSON found in the publisher tenant domain mappings";
        throw new APIManagementException(msg, e);
    }
    return context;
}
Also used : JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) JSONParser(org.json.simple.parser.JSONParser) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) ParseException(org.json.simple.parser.ParseException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 35 with ResourcePath

use of org.wso2.carbon.apimgt.api.model.ResourcePath in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getAPIResourcePaths.

@Override
public Response getAPIResourcePaths(String apiId, Integer limit, Integer offset, String ifNoneMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
        if (apiIdentifier == null) {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        List<ResourcePath> apiResourcePaths = apiProvider.getResourcePathsOfAPI(apiIdentifier);
        ResourcePathListDTO dto = APIMappingUtil.fromResourcePathListToDTO(apiResourcePaths, limit, offset);
        APIMappingUtil.setPaginationParamsForAPIResourcePathList(dto, offset, limit, apiResourcePaths.size());
        return Response.ok().entity(dto).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving resource paths of API : " + apiId, e, log);
        } else {
            String errorMessage = "Error while retrieving resource paths of API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : ResourcePath(org.wso2.carbon.apimgt.api.model.ResourcePath) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ResourcePathListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ResourcePathListDTO) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

Resource (org.wso2.carbon.registry.core.Resource)51 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)48 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)44 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)28 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)25 IOException (java.io.IOException)18 Registry (org.wso2.carbon.registry.core.Registry)16 Collection (org.wso2.carbon.registry.core.Collection)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 Test (org.junit.Test)13 Resource (org.wso2.carbon.registry.api.Resource)13 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 ArrayList (java.util.ArrayList)11 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)11 RegistryException (org.wso2.carbon.registry.api.RegistryException)11 ResourceImpl (org.wso2.carbon.registry.core.ResourceImpl)11 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)11 JSONParser (org.json.simple.parser.JSONParser)10 ParseException (org.json.simple.parser.ParseException)10 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)10