Search in sources :

Example 66 with Permission

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

the class PublisherCommonUtils method addAPIProductWithGeneratedSwaggerDefinition.

/**
 * Add API Product with the generated swagger from the DTO.
 *
 * @param apiProductDTO API Product DTO
 * @param username      Username
 * @param organization Identifier of the organization
 * @return Created API Product object
 * @throws APIManagementException Error while creating the API Product
 * @throws FaultGatewaysException Error while adding the API Product to gateway
 */
public static APIProduct addAPIProductWithGeneratedSwaggerDefinition(APIProductDTO apiProductDTO, String username, String organization) throws APIManagementException, FaultGatewaysException {
    username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
    APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
    // if not add product
    String provider = apiProductDTO.getProvider();
    String context = apiProductDTO.getContext();
    if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
        if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
            }
            provider = username;
        }
    } else {
        // Set username in case provider is null or empty
        provider = username;
    }
    List<String> tiersFromDTO = apiProductDTO.getPolicies();
    Set<Tier> definedTiers = apiProvider.getTiers();
    List<String> invalidTiers = PublisherCommonUtils.getInvalidTierNames(definedTiers, tiersFromDTO);
    if (!invalidTiers.isEmpty()) {
        throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
    }
    if (apiProductDTO.getAdditionalProperties() != null) {
        String errorMessage = PublisherCommonUtils.validateAdditionalProperties(apiProductDTO.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiProductDTO.getName()));
        }
    }
    if (apiProductDTO.getVisibility() == null) {
        // set the default visibility to PUBLIC
        apiProductDTO.setVisibility(APIProductDTO.VisibilityEnum.PUBLIC);
    }
    if (apiProductDTO.getAuthorizationHeader() == null) {
        apiProductDTO.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
    }
    if (apiProductDTO.getAuthorizationHeader() == null) {
        apiProductDTO.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
    }
    // Remove the /{version} from the context.
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    // Make sure context starts with "/". ex: /pizzaProduct
    context = context.startsWith("/") ? context : ("/" + context);
    // Check whether the context already exists
    if (apiProvider.isContextExist(context)) {
        throw new APIManagementException("Error occurred while adding API Product. API Product with the context " + context + " already " + "exists.", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_CONTEXT_ALREADY_EXISTS, context));
    }
    // Set default gatewayVendor
    if (apiProductDTO.getGatewayVendor() == null) {
        apiProductDTO.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
    }
    APIProduct productToBeAdded = APIMappingUtil.fromDTOtoAPIProduct(apiProductDTO, provider);
    productToBeAdded.setOrganization(organization);
    if (!APIConstants.PROTOTYPED.equals(productToBeAdded.getState())) {
        productToBeAdded.setState(APIConstants.CREATED);
    }
    APIProductIdentifier createdAPIProductIdentifier = productToBeAdded.getId();
    Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider.addAPIProductWithoutPublishingToGateway(productToBeAdded);
    APIProduct createdProduct = apiProvider.getAPIProduct(createdAPIProductIdentifier);
    apiProvider.addAPIProductSwagger(createdProduct.getUuid(), apiToProductResourceMapping, createdProduct, organization);
    createdProduct = apiProvider.getAPIProduct(createdAPIProductIdentifier);
    return createdProduct;
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 67 with Permission

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

the class APIManagerComponent method addApplicationsPermissionsToRegistry.

/**
 * This method will create new permission name  "applications" in registry permission.
 */
private void addApplicationsPermissionsToRegistry() throws APIManagementException {
    Registry tenantGovReg = getRegistry();
    String permissionResourcePath = CarbonConstants.UI_PERMISSION_NAME + RegistryConstants.PATH_SEPARATOR + APPLICATION_ROOT_PERMISSION;
    try {
        if (!tenantGovReg.resourceExists(permissionResourcePath)) {
            String loggedInUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
            UserRealm realm = (UserRealm) CarbonContext.getThreadLocalCarbonContext().getUserRealm();
            // Logged in user is not authorized to create the permission.
            // Temporarily change the user to the admin for creating the permission
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(realm.getRealmConfiguration().getAdminUserName());
            tenantGovReg = CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.USER_GOVERNANCE);
            Collection appRootNode = tenantGovReg.newCollection();
            appRootNode.setProperty("name", "Applications");
            tenantGovReg.put(permissionResourcePath, appRootNode);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(loggedInUser);
        }
    } catch (org.wso2.carbon.user.core.UserStoreException e) {
        throw new APIManagementException("Error while reading user store information.", e);
    } catch (org.wso2.carbon.registry.api.RegistryException e) {
        throw new APIManagementException("Error while creating new permission in registry", e);
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Collection(org.wso2.carbon.registry.api.Collection) Registry(org.wso2.carbon.registry.api.Registry) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry)

Example 68 with Permission

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

the class RegistryPersistenceImpl method addDocumentationContent.

@Override
public DocumentContent addDocumentationContent(Organization org, String apiId, String docId, DocumentContent content) throws DocumentationPersistenceException {
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        GenericArtifactManager apiArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiId);
        String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        apiProviderName = RegistryPersistenceUtil.replaceEmailDomain(apiProviderName);
        String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        GenericArtifactManager docArtifactManager = RegistryPersistenceDocUtil.getDocumentArtifactManager(registry);
        GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docId);
        Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
        if (DocumentContent.ContentSourceType.FILE.equals(content.getSourceType())) {
            ResourceFile resource = content.getResourceFile();
            String filePath = RegistryPersistenceDocUtil.getDocumentFilePath(apiProviderName, apiName, apiVersion, resource.getName());
            String visibility = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
            String visibleRolesList = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
            String[] visibleRoles = new String[0];
            if (visibleRolesList != null) {
                visibleRoles = visibleRolesList.split(",");
            }
            RegistryPersistenceUtil.setResourcePermissions(RegistryPersistenceUtil.replaceEmailDomain(apiProviderName), visibility, visibleRoles, filePath, registry);
            // documentation.setFilePath(addResourceFile(apiId, filePath, icon));
            String savedFilePath = addResourceFile(filePath, resource, registry, tenantDomain);
            // doc.setFilePath(savedFilePath);
            docArtifact.setAttribute(APIConstants.DOC_FILE_PATH, savedFilePath);
            docArtifactManager.updateGenericArtifact(docArtifact);
            RegistryPersistenceUtil.setFilePermission(filePath);
        } else {
            String contentPath = RegistryPersistenceDocUtil.getDocumentContentPath(apiProviderName, apiName, apiVersion, doc.getName());
            Resource docContent;
            if (!registry.resourceExists(contentPath)) {
                docContent = registry.newResource();
            } else {
                docContent = registry.get(contentPath);
            }
            String text = content.getTextContent();
            if (!APIConstants.NO_CONTENT_UPDATE.equals(text)) {
                docContent.setContent(text);
            }
            docContent.setMediaType(APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE);
            registry.put(contentPath, docContent);
            // Set resource permission
            String apiPath = RegistryPersistenceUtil.getAPIPath(apiName, apiVersion, apiProviderName);
            String docVisibility = doc.getVisibility().name();
            String[] authorizedRoles = RegistryPersistenceUtil.getAuthorizedRoles(apiPath, tenantDomain);
            String visibility = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
            if (docVisibility != null) {
                if (APIConstants.DOC_SHARED_VISIBILITY.equalsIgnoreCase(docVisibility)) {
                    authorizedRoles = null;
                    visibility = APIConstants.DOC_SHARED_VISIBILITY;
                } else if (APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(docVisibility)) {
                    authorizedRoles = null;
                    visibility = APIConstants.DOC_OWNER_VISIBILITY;
                }
            }
            RegistryPersistenceUtil.setResourcePermissions(apiProviderName, visibility, authorizedRoles, contentPath, registry);
            GenericArtifact updateDocArtifact = RegistryPersistenceDocUtil.createDocArtifactContent(docArtifact, apiProviderName, apiName, apiVersion, doc);
            Boolean toggle = Boolean.parseBoolean(updateDocArtifact.getAttribute("toggle"));
            updateDocArtifact.setAttribute("toggle", Boolean.toString(!toggle));
            docArtifactManager.updateGenericArtifact(updateDocArtifact);
        }
    } catch (APIPersistenceException | RegistryException | APIManagementException | PersistenceException | UserStoreException e) {
        throw new DocumentationPersistenceException("Error while adding document content", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return null;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) Documentation(org.wso2.carbon.apimgt.persistence.dto.Documentation) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) ResourceFile(org.wso2.carbon.apimgt.persistence.dto.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 69 with Permission

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

the class RegistryPersistenceImpl method getDevPortalAPI.

@Override
public DevPortalAPI getDevPortalAPI(Organization org, String apiId) throws APIPersistenceException {
    boolean tenantFlowStarted = false;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        Registry registry = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted();
        GenericArtifact apiArtifact = getAPIArtifact(apiId, registry);
        if (apiArtifact != null) {
            API api = RegistryPersistenceUtil.getApiForPublishing(registry, apiArtifact);
            String definitionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(api.getId().getProviderName()) + RegistryConstants.PATH_SEPARATOR + api.getId().getName() + RegistryConstants.PATH_SEPARATOR + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
            if (registry.resourceExists(definitionPath)) {
                Resource apiDocResource = registry.get(definitionPath);
                String apiDocContent = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
                api.setSwaggerDefinition(apiDocContent);
            }
            String apiTenantDomain = MultitenantUtils.getTenantDomain(RegistryPersistenceUtil.replaceEmailDomainBack(api.getId().getProviderName()));
            if (APIConstants.API_GLOBAL_VISIBILITY.equals(api.getVisibility())) {
                // return new ApiTypeWrapper(api);
                return APIMapper.INSTANCE.toDevPortalApi(api);
            }
            if (tenantDomain == null || !tenantDomain.equals(apiTenantDomain)) {
                throw new APIPersistenceException("User does not have permission to view API : " + api.getId().getApiName());
            }
            return APIMapper.INSTANCE.toDevPortalApi(api);
        } else {
            return null;
        }
    } catch (RegistryException | APIManagementException e) {
        String msg = "Failed to get API";
        throw new APIPersistenceException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 70 with Permission

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

the class APIUtilTest method testHasPermission.

@Test
public void testHasPermission() throws Exception {
    int tenantId = 2;
    String userNameWithoutChange = "Drake";
    String permission = APIConstants.Permissions.API_PUBLISH;
    System.setProperty(CARBON_HOME, "");
    PowerMockito.spy(APIUtil.class);
    PowerMockito.doReturn(false).when(APIUtil.class, "isPermissionCheckDisabled");
    PowerMockito.doReturn(1).when(APIUtil.class, "getValueFromCache", APIConstants.API_PUBLISHER_ADMIN_PERMISSION_CACHE, userNameWithoutChange);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Mockito.when(MultitenantUtils.getTenantDomain(userNameWithoutChange)).thenReturn(tenantDomain);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    Mockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    Mockito.when(realmService.getTenantUserRealm(tenantId)).thenReturn(userRealm);
    org.wso2.carbon.user.api.AuthorizationManager authorizationManager = Mockito.mock(org.wso2.carbon.user.api.AuthorizationManager.class);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authorizationManager);
    Mockito.when(authorizationManager.isUserAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true);
    org.wso2.carbon.user.core.UserRealm userRealm2 = Mockito.mock(org.wso2.carbon.user.core.UserRealm.class);
    Mockito.when(ServiceReferenceHolder.getUserRealm()).thenReturn((userRealm2));
    PowerMockito.mockStatic(AuthorizationManager.class);
    AuthorizationManager authorizationManager1 = Mockito.mock(AuthorizationManager.class);
    Mockito.when(AuthorizationManager.getInstance()).thenReturn(authorizationManager1);
    Mockito.when(authorizationManager1.isUserAuthorized(Mockito.anyString(), Mockito.anyString())).thenReturn(true);
    Log logMock = Mockito.mock(Log.class);
    PowerMockito.mockStatic(LogFactory.class);
    Mockito.when(LogFactory.getLog(any(Class.class))).thenReturn(logMock);
    boolean expectedResult = APIUtil.hasPermission(userNameWithoutChange, permission);
    Assert.assertEquals(true, expectedResult);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Log(org.apache.commons.logging.Log) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

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