Search in sources :

Example 26 with Permission

use of org.wso2.carbon.user.api.Permission in project product-iots by wso2.

the class RoleManagement method testUpdateRolePermission.

@Test(description = "Test update permission role.", dependsOnMethods = { "testAddRole" })
public void testUpdateRolePermission() throws FileNotFoundException {
    IOTResponse response = client.put(Constants.RoleManagement.ROLE_MANAGEMENT_END_POINT + "/" + ROLE_NAME, PayloadGenerator.getJsonPayload(Constants.RoleManagement.ROLE_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_PUT).toString());
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
}
Also used : IOTResponse(org.wso2.iot.integration.common.IOTResponse) Test(org.testng.annotations.Test)

Example 27 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class AbstractAPIManager method getAllDocumentation.

public List<Documentation> getAllDocumentation(APIIdentifier apiId, String loggedUsername) throws APIManagementException {
    List<Documentation> documentationList = new ArrayList<Documentation>();
    try {
        String tenantDomain = getTenantDomain(apiId);
        Registry registryType;
        /* If the API provider is a tenant, load tenant registry*/
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            // Tenant store anonymous mode
            int tenantId = getTenantManager().getTenantId(tenantDomain);
            registryType = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
        } else {
            registryType = registry;
        }
        String apiOrAPIProductDocPath = APIUtil.getAPIOrAPIProductDocPath(apiId);
        String pathToContent = apiOrAPIProductDocPath + APIConstants.INLINE_DOCUMENT_CONTENT_DIR;
        String pathToDocFile = apiOrAPIProductDocPath + APIConstants.DOCUMENT_FILE_DIR;
        if (registry.resourceExists(apiOrAPIProductDocPath)) {
            Resource resource = registry.get(apiOrAPIProductDocPath);
            if (resource instanceof org.wso2.carbon.registry.core.Collection) {
                String[] docsPaths = ((org.wso2.carbon.registry.core.Collection) resource).getChildren();
                for (String docPath : docsPaths) {
                    if (!(docPath.equalsIgnoreCase(pathToContent) || docPath.equalsIgnoreCase(pathToDocFile))) {
                        Resource docResource = registry.get(docPath);
                        GenericArtifactManager artifactManager = getAPIGenericArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
                        GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
                        Documentation doc = APIUtil.getDocumentation(docArtifact, apiId.getProviderName());
                        Date contentLastModifiedDate;
                        Date docLastModifiedDate = docResource.getLastModified();
                        if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(apiId, doc.getName());
                            try {
                                contentLastModifiedDate = registryType.get(contentPath).getLastModified();
                                doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ? contentLastModifiedDate : docLastModifiedDate));
                            } catch (org.wso2.carbon.registry.core.secure.AuthorizationFailedException e) {
                            // do nothing. Permission not allowed to access the doc.
                            }
                        } else if (Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(apiId, doc.getName());
                            try {
                                contentLastModifiedDate = registryType.get(contentPath).getLastModified();
                                doc.setLastUpdated((contentLastModifiedDate.after(docLastModifiedDate) ? contentLastModifiedDate : docLastModifiedDate));
                            } catch (org.wso2.carbon.registry.core.secure.AuthorizationFailedException e) {
                            // do nothing. Permission not allowed to access the doc.
                            }
                        } else {
                            doc.setLastUpdated(docLastModifiedDate);
                        }
                        documentationList.add(doc);
                    }
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Failed to get documentations for api " + apiId.getApiName();
        throw new APIManagementException(msg, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "Failed to get documentations for api " + apiId.getApiName();
        throw new APIManagementException(msg, e);
    }
    return documentationList;
}
Also used : ArrayList(java.util.ArrayList) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Date(java.util.Date) Collection(org.wso2.carbon.registry.core.Collection)

Example 28 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class AbstractAPIManager method getAPIorAPIProductByUUID.

/**
 * Get API or APIProduct by registry artifact id
 *
 * @param uuid                  Registry artifact id
 * @param requestedTenantDomain tenantDomain for the registry
 * @return ApiTypeWrapper wrapping the API or APIProduct of the provided artifact id
 * @throws APIManagementException
 */
public ApiTypeWrapper getAPIorAPIProductByUUID(String uuid, String requestedTenantDomain) throws APIManagementException {
    boolean tenantFlowStarted = false;
    try {
        Registry registry;
        if (requestedTenantDomain != null) {
            int id = getTenantManager().getTenantId(requestedTenantDomain);
            startTenantFlow(requestedTenantDomain);
            tenantFlowStarted = true;
            if (APIConstants.WSO2_ANONYMOUS_USER.equals(this.username)) {
                registry = getRegistryService().getGovernanceUserRegistry(this.username, id);
            } else if (this.tenantDomain != null && !this.tenantDomain.equals(requestedTenantDomain)) {
                registry = getRegistryService().getGovernanceSystemRegistry(id);
            } else {
                registry = this.registry;
            }
        } else {
            registry = this.registry;
        }
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(uuid);
        if (apiArtifact != null) {
            String type = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
            if (APIConstants.API_PRODUCT.equals(type)) {
                APIProduct apiProduct = getApiProduct(registry, apiArtifact);
                String productTenantDomain = getTenantDomain(apiProduct.getId());
                if (APIConstants.API_GLOBAL_VISIBILITY.equals(apiProduct.getVisibility())) {
                    return new ApiTypeWrapper(apiProduct);
                }
                if (this.tenantDomain == null || !this.tenantDomain.equals(productTenantDomain)) {
                    throw new APIManagementException("User " + username + " does not have permission to view API Product : " + apiProduct.getId().getName());
                }
                return new ApiTypeWrapper(apiProduct);
            } else {
                API api = getApiForPublishing(registry, apiArtifact);
                String apiTenantDomain = getTenantDomain(api.getId());
                if (APIConstants.API_GLOBAL_VISIBILITY.equals(api.getVisibility())) {
                    return new ApiTypeWrapper(api);
                }
                if (this.tenantDomain == null || !this.tenantDomain.equals(apiTenantDomain)) {
                    throw new APIManagementException("User " + username + " does not have permission to view API : " + api.getId().getApiName());
                }
                return new ApiTypeWrapper(api);
            }
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (RegistryException | org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "Failed to get API";
        throw new APIManagementException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 29 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method loadloadTenantAPIRXT.

public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    UserRegistry registry = null;
    try {
        registry = registryService.getGovernanceSystemRegistry(tenantID);
    } catch (RegistryException e) {
        throw new APIManagementException("Error when create registry instance ", e);
    }
    String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
    File file = new File(rxtDir);
    FilenameFilter filenameFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            // if the file extension is .rxt return true, else false
            return name.endsWith(".rxt");
        }
    };
    String[] rxtFilePaths = file.list(filenameFilter);
    if (rxtFilePaths == null) {
        throw new APIManagementException("rxt files not found in directory " + rxtDir);
    }
    for (String rxtPath : rxtFilePaths) {
        String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
        // This is  "registry" is a governance registry instance, therefore calculate the relative path to governance.
        String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
        try {
            // 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 (registry.resourceExists(govRelativePath)) {
                // set anonymous user permission to RXTs
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                continue;
            }
            String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
            Resource resource = registry.newResource();
            resource.setContent(rxt.getBytes(Charset.defaultCharset()));
            resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
            registry.put(govRelativePath, resource);
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
        } catch (UserStoreException e) {
            throw new APIManagementException("Error while adding role permissions to API", e);
        } catch (IOException e) {
            String msg = "Failed to read rxt files";
            throw new APIManagementException(msg, e);
        } catch (RegistryException e) {
            String msg = "Failed to add rxt to registry ";
            throw new APIManagementException(msg, e);
        }
    }
}
Also used : AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FilenameFilter(java.io.FilenameFilter) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File)

Example 30 with Permission

use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingPoliciesSubscriptionPolicyIdPut.

/**
 * Updates a given Subscription level policy specified by uuid
 *
 * @param policyId          u
 * @param body              DTO of policy to be updated
 * @param contentType       Content-Type header
 * @return Updated policy
 */
@Override
public Response throttlingPoliciesSubscriptionPolicyIdPut(String policyId, String contentType, SubscriptionThrottlePolicyDTO body, MessageContext messageContext) throws APIManagementException {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        // will give PolicyNotFoundException if there's no policy exists with UUID
        SubscriptionPolicy existingPolicy = apiProvider.getSubscriptionPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, existingPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_SUBSCRIPTION_POLICY, policyId, log);
        }
        // overridden properties
        body.setPolicyId(policyId);
        body.setPolicyName(existingPolicy.getPolicyName());
        // validate if permission info exists and halt the execution in case of an error
        validatePolicyPermissions(body);
        // update the policy
        SubscriptionPolicy subscriptionPolicy = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyDTOToModel(body);
        apiProvider.updatePolicy(subscriptionPolicy);
        // update policy permissions
        updatePolicyPermissions(body);
        // retrieve the new policy and send back as the response
        SubscriptionPolicy newSubscriptionPolicy = apiProvider.getSubscriptionPolicy(username, body.getPolicyName());
        SubscriptionThrottlePolicyDTO policyDTO = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyToDTO(newSubscriptionPolicy);
        // setting policy permissions
        setPolicyPermissionsToDTO(policyDTO);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException | ParseException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_SUBSCRIPTION_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while updating Subscription level policy: " + body.getPolicyName();
            throw new APIManagementException(errorMessage, e);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ParseException(org.json.simple.parser.ParseException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)29 HashSet (java.util.HashSet)18 HashMap (java.util.HashMap)17 ArrayList (java.util.ArrayList)16 Test (org.testng.annotations.Test)16 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)16 Test (org.junit.Test)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 API (org.wso2.carbon.apimgt.core.models.API)15 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)15 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)13 Map (java.util.Map)12 Resource (org.wso2.carbon.registry.core.Resource)12 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)12 API (org.wso2.carbon.apimgt.api.model.API)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)9 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)9 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)8