Java Code Examples for org.wso2.carbon.utils.multitenancy.MultitenantConstants#SUPER_TENANT_DOMAIN_NAME

The following examples show how to use org.wso2.carbon.utils.multitenancy.MultitenantConstants#SUPER_TENANT_DOMAIN_NAME . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractKeyValidationHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private boolean validateSubscriptionDetails(String context, String version, String consumerKey, String keyManager,
        APIKeyValidationInfoDTO infoDTO) throws APIManagementException {
    boolean defaultVersionInvoked = false;
    String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (apiTenantDomain == null) {
        apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    int apiOwnerTenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
    // Check if the api version has been prefixed with _default_
    if (version != null && version.startsWith(APIConstants.DEFAULT_VERSION_PREFIX)) {
        defaultVersionInvoked = true;
        // Remove the prefix from the version.
        version = version.split(APIConstants.DEFAULT_VERSION_PREFIX)[1];
    }

    validateSubscriptionDetails(infoDTO, context, version, consumerKey, keyManager, defaultVersionInvoked);
    return infoDTO.isAuthorized();
}
 
Example 2
Source File: RegularExpressionProtector.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Using Regex Threat Protector mediator will be restricted to the tenants defined by the system property
 * 'regexThreatProtectorEnabledTenants' as a list of comma separated values and super tenant. If this system
 * property is not defined, then this restriction will not be applied at all. If invoked API is existing within a
 * tenant, which was defined in this list, this method returns true. If this system property is not defined, this
 * check won't be done and so will return true, hence all the tenants will be allowed to use this mediator
 *
 * @param messageContext contains the message properties of the relevant API request which was
 *                       enabled the regexValidator message mediation in flow.
 * @return true if the tenant is allowed to use this Mediator
 */
private boolean isTenantAllowed(MessageContext messageContext) {
    String allowedTenants = System.getProperty(APIMgtGatewayConstants.REGEX_THREAT_PROTECTOR_ENABLED_TENANTS);
    if (allowedTenants == null) {
        return true;
    }
    List<String> allowedTenantsList = Arrays.asList(allowedTenants.split(","));
    String tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(RESTUtils.getFullRequestPath
            (messageContext));
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    if (!allowedTenantsList.contains(tenantDomain) &&
            !(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME).equals(tenantDomain)) {
        GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE,
                "This tenant is not allowed to use Regular Expression Threat Protector mediator");
        return false;
    }
    return true;
}
 
Example 3
Source File: IdPMgtValidationListener.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreDeleteIdP(String idPName, String tenantDomain) throws IdentityProviderManagementException {

    if (StringUtils.isEmpty(idPName)) {
        throw new IllegalArgumentException("Invalid argument: Identity Provider Name value is empty");
    }

    String loggedInTenant = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();

    if (IdentityApplicationConstants.RESIDENT_IDP_RESERVED_NAME.equals(idPName)) {
        if (StringUtils.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, tenantDomain)) {
            throw new IdentityProviderManagementException("Cannot delete Resident Identity Provider of Super " +
                    "Tenant");
        } else if(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME != loggedInTenant){
            throw new IdentityProviderManagementException("Tenant user of " + loggedInTenant + " cannot delete " +
                    "Resident Identity Provider of tenant " + tenantDomain);
        } else {
            log.warn("Deleting Resident Identity Provider for tenant " + tenantDomain);
        }
    }

    return true;
}
 
Example 4
Source File: HostUtil.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * adding domain for service in registry
 * 
 * @param hostName
 * @param url
 * @throws UrlMapperException
 */
public static void addDomainToServiceEpr(String hostName, String url, String appType) throws UrlMapperException {

	// if the request if from tenant
	String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
	if (url.contains("/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/")) {
		tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(url);
	}

	if (isServiceURLPattern(url)) {
		url = getServiceEndpoint(url);
	}
	try {
		// add entry to registry with the tenant domain if exist in the uri
		registryManager.addEprToRegistry(hostName, url, tenantDomain, appType);
		URLMappingHolder.getInstance().putUrlMappingForApplication(hostName,
				url);
           log.info("mapping added to service:***********: " + hostName + "******: " + url );
           //adding mapping to cluster message
           VirtualHostClusterUtil.addServiceMappingToCluster(hostName, url);
           addServiceParameter(url);
	} catch (Exception e) {
		log.error("error in adding the domain to the resitry", e);
		throw new UrlMapperException("error in adding the domain to the resitry");
	}
}
 
Example 5
Source File: IdentityTenantUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private static UserRealm getRealmForAnonymousSession(String domainName, String username)
        throws IdentityException {
    try {
        if (domainName == null && username == null) {
            domainName = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }

        if (username == null) {
            return AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService,
                    domainName);
        } else if (username != null) {
            return AnonymousSessionUtil.getRealmByUserName(registryService, realmService,
                    username);
        }
    } catch (CarbonException e) {
        log.error("Error obtaining the realm", e);
        throw IdentityException.error("Error Obtaining a realm", e);
    }
    return null;
}
 
Example 6
Source File: FrameworkUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Starts the tenant flow for the given tenant domain
 *
 * @param tenantDomain tenant domain
 */
public static void startTenantFlow(String tenantDomain) {
    String tenantDomainParam = tenantDomain;
    int tenantId = MultitenantConstants.SUPER_TENANT_ID;

    if (tenantDomainParam != null && !tenantDomainParam.trim().isEmpty()) {
        try {
            tenantId = FrameworkServiceComponent.getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            log.error("Error while getting tenantId from tenantDomain query param", e);
        }
    } else {
        tenantDomainParam = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
            .getThreadLocalCarbonContext();
    carbonContext.setTenantId(tenantId);
    carbonContext.setTenantDomain(tenantDomainParam);
}
 
Example 7
Source File: DeviceAccessAuthorizationServiceTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private RegistryService getRegistryService() throws RegistryException, UserStoreException {
    RealmService realmService = new InMemoryRealmService();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
    BasicDataSource dataSource = new BasicDataSource();
    String connectionUrl = "jdbc:h2:./target/databasetest/CARBON_TEST";
    dataSource.setUrl(connectionUrl);
    dataSource.setDriverClassName(DRIVER_CLASS_NAME);
    JDBCTenantManager jdbcTenantManager = new JDBCTenantManager(dataSource,
            MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    realmService.setTenantManager(jdbcTenantManager);
    RegistryDataHolder.getInstance().setRealmService(realmService);
    DeviceManagementDataHolder.getInstance().setRealmService(realmService);
    InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml");
    RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
    context.setSetup(true);
    return context.getEmbeddedRegistryService();
}
 
Example 8
Source File: APIMRegistryServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public String getGovernanceRegistryResourceContent(String tenantDomain, String registryLocation)
                                    throws UserStoreException, RegistryException {
    String content = null;
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);

        if (registry.resourceExists(registryLocation)) {
            Resource resource = registry.get(registryLocation);
            content = getString(resource);
        }
    }
    finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return content;
}
 
Example 9
Source File: EndpointAdminServiceProxyTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckEndpointExistBeforeDelete() {
    EndpointAdminServiceProxy endpointAdminServiceProxy = null;
    String endpointName = "PizzaShackAPI--v1.0.0_APIproductionEndpoint";
    String[] endpointArray = { "PizzaShackAPI--v1.0.0_APIproductionEndpoint",
            "PizzaShackAPI--v1.0.0_APIsandboxEndpoint" };
    String tenantDomain = "wso2.com";
    try {
        endpointAdminServiceProxy = new EndpointAdminServiceProxy(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        EndpointAdmin endpointAdmin = Mockito.mock(EndpointAdmin.class);
        Mockito.when(endpointAdmin.deleteEndpoint(endpointName)).thenReturn(true);
        Mockito.when(endpointAdmin.deleteEndpointForTenant(endpointName, tenantDomain)).thenReturn(true);
        Mockito.when(endpointAdmin.getEndPointsNames()).thenReturn(endpointArray);
        Mockito.when(endpointAdmin.getEndPointsNamesForTenant(tenantDomain)).thenReturn(endpointArray);
        endpointAdminServiceProxy.setEndpointAdmin(endpointAdmin);
    } catch (Exception e) {
        Assert.fail("Exception while testing CheckEndpointExistBeforeDelete");
    }
}
 
Example 10
Source File: KeymanagersApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public Response keymanagersGet(String xWSO2Tenant, MessageContext messageContext) {

        String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        try {
            if (StringUtils.isNotEmpty(xWSO2Tenant)) {
                tenantDomain = xWSO2Tenant;
            }
            APIAdmin apiAdmin = new APIAdminImpl();
            List<KeyManagerConfigurationDTO> keyManagerConfigurations =
                    apiAdmin.getKeyManagerConfigurationsByTenant(tenantDomain);
            List<KeyManagerDTO> keyManagerDTOList = new ArrayList<>();
            for (KeyManagerConfigurationDTO keyManagerConfiguration : keyManagerConfigurations) {
                keyManagerDTOList.add(toKeyManagerDTO(tenantDomain, keyManagerConfiguration));
            }
            return Response.ok(keyManagerDTOList).build();
        } catch (APIManagementException e) {
            RestApiUtil.handleInternalServerError("Error while retrieving key manager configurations", e, log);
        }
        return null;
    }
 
Example 11
Source File: ConsentMgtPostAuthnHandler.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private String getSPTenantDomain(ServiceProvider serviceProvider) {

        String spTenantDomain;
        User owner = serviceProvider.getOwner();
        if (owner != null) {
            spTenantDomain = owner.getTenantDomain();
        } else {
            spTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        return spTenantDomain;
    }
 
Example 12
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public boolean isApiNameWithDifferentCaseExist(String apiName) throws APIManagementException {
    String tenantName = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        tenantName = tenantDomain;
    }
    return apiMgtDAO.isApiNameWithDifferentCaseExist(apiName, tenantName);
}
 
Example 13
Source File: AlertSubscriptionsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 *
 * Obtain the fully qualified username of the given user
 * @param username  tenant aware username
 * @return
 */
private String getFullyQualifiedUsername(String username) {
    if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(RestApiUtil.getLoggedInUserTenantDomain())) {
        return username + "@" + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    return username;
}
 
Example 14
Source File: APIMRegistryServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public String getConfigRegistryResourceContent(String tenantDomain, final String registryLocation)
                                    throws UserStoreException, RegistryException {
    String content = null;
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
        APIUtil.loadTenantRegistry(tenantId);
        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            APIUtil.loadTenantConf(tenantId);
        }

        if (registry.resourceExists(registryLocation)) {
            Resource resource = registry.get(registryLocation);
            content = getString(resource);
        }
    } catch (APIManagementException e) {
        log.error("Error occurred while loading tenant configuration for '" + tenantDomain + "'");

    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return content;
}
 
Example 15
Source File: RecommenderDetailsExtractor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public void run() {

        if (tenantDomain == null) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        startTenantFlow(tenantDomain);
        tenantFlowStarted = true;
        try {
            if (APIUtil.isRecommendationEnabled(tenantDomain)) {
                if (APIConstants.ADD_API.equals(publishingDetailType)) {
                    publishAPIDetails(api, tenantDomain);
                } else if (APIConstants.ADD_NEW_APPLICATION.equals(publishingDetailType)) {
                    publishApplicationDetails(application, userName, applicationId);
                } else if (APIConstants.UPDATED_APPLICATION.equals(publishingDetailType)) {
                    publishApplicationDetails(application, userName, applicationId);
                } else if (APIConstants.DELETE_APPLICATION.equals(publishingDetailType)) {
                    publishDeletedApplication(applicationId);
                } else if (APIConstants.ADD_USER_CLICKED_API.equals(publishingDetailType)) {
                    publishClickedApi(clickedApi, userName);
                } else if (APIConstants.ADD_USER_SEARCHED_QUERY.equals(publishingDetailType)) {
                    publishSearchQueries(searchQuery, userName);
                }

                if (!APIConstants.ADD_API.equals(publishingDetailType) && userName != null
                        && userName != APIConstants.WSO2_ANONYMOUS_USER && requestTenantDomain != null) {
                    updateRecommendationsCache(userName, requestTenantDomain);
                }
            }
        } catch (IOException e) {
            log.error("When extracting data for the recommendation system !", e);
        } finally {
            if (tenantFlowStarted) {
                endTenantFlow();
            }
        }
    }
 
Example 16
Source File: SSOConsentServiceImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private String getSPTenantDomain(ServiceProvider serviceProvider) {

        String spTenantDomain;
        User owner = serviceProvider.getOwner();
        if (owner != null) {
            spTenantDomain = owner.getTenantDomain();
        } else {
            spTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        return spTenantDomain;
    }
 
Example 17
Source File: UserRecoveryDTO.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
public UserRecoveryDTO(String userId) {
    this.userId = userId;
    this.tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    this.tenantId = MultitenantConstants.SUPER_TENANT_ID;
}
 
Example 18
Source File: APIUtilRolesTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateDefaultRoles() throws Exception {
    System.setProperty("carbon.home", "");
    final int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    final String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;

    File siteConfFile = new File(Thread.currentThread().getContextClassLoader().
            getResource("tenant-conf.json").getFile());

    String tenantConfValue = FileUtils.readFileToString(siteConfFile);

    InputStream signUpConfStream = new FileInputStream(Thread.currentThread().getContextClassLoader().
            getResource("default-sign-up-config.xml").getFile());

    PrivilegedCarbonContext carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    TenantIndexingLoader indexingLoader = Mockito.mock(TenantIndexingLoader.class);
    TenantRegistryLoader tenantRegistryLoader = Mockito.mock(TenantRegistryLoader.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    Resource resource = Mockito.mock(Resource.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);

    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIManagerComponent.class);

    Mockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(serviceReferenceHolder.getIndexLoaderService()).thenReturn(indexingLoader);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(realmService.getBootstrapRealm()).thenReturn(userRealm);
    Mockito.when(realmService.getTenantUserRealm(tenantId)).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
    Mockito.when(realmConfiguration.getAdminUserName()).thenReturn("admin");
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
    Mockito.when(APIManagerComponent.getTenantRegistryLoader()).thenReturn(tenantRegistryLoader);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getConfigSystemRegistry(eq(tenantId))).thenReturn(registry);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(tenantId))).thenReturn(registry);
    Mockito.when(registry.resourceExists(eq(APIConstants.API_TENANT_CONF_LOCATION))).thenReturn(true);
    Mockito.when(registry.resourceExists(eq(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION))).thenReturn(true);
    Mockito.when(registry.get(eq(APIConstants.API_TENANT_CONF_LOCATION))).thenReturn(resource);
    Mockito.when(registry.get(eq(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION))).thenReturn(resource);
    Mockito.when(resource.getContent()).thenReturn(tenantConfValue.getBytes());
    Mockito.when(resource.getContentStream()).thenReturn(signUpConfStream);

    APIUtil.createDefaultRoles(tenantId);

    String[] adminName = {"admin"};
    Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/publisher"),
            eq(adminName), new Permission[]{Mockito.any(Permission.class)});
    Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/subscriber"),
            eq(adminName), new Permission[]{Mockito.any(Permission.class)});
    Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/creator"),
            eq(adminName), new Permission[]{Mockito.any(Permission.class)});
}
 
Example 19
Source File: AbstractKeyValidationHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
private APIKeyValidationInfoDTO validateSubscriptionDetails(APIKeyValidationInfoDTO infoDTO, String context,
        String version, String consumerKey, String keyManager, boolean defaultVersionInvoked) {
    String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (apiTenantDomain == null) {
        apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    int tenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
    API api = null;
    ApplicationKeyMapping key = null;
    Application app = null;
    Subscription sub = null;
    
    SubscriptionDataStore datastore = SubscriptionDataHolder.getInstance()
            .getTenantSubscriptionStore(apiTenantDomain);
    //TODO add a check to see whether datastore is initialized an load data using rest api if it is not loaded
    if (datastore != null) {
        api = datastore.getApiByContextAndVersion(context, version);
        if (api != null) {
            key = datastore.getKeyMappingByKeyAndKeyManager(consumerKey, keyManager);
            if (key != null) {
                app = datastore.getApplicationById(key.getApplicationId());
                if (app != null) {
                    sub = datastore.getSubscriptionById(app.getId(), api.getApiId());
                    if (sub != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("All information is retrieved from the inmemory data store.");
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Valid subscription not found for appId " + app.getId() + " and apiId "
                                    + api.getApiId());
                        }
                        loadInfoFromRestAPIAndValidate(api, app, key, sub, context, version, consumerKey,
                                keyManager, datastore, apiTenantDomain, infoDTO, tenantId);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Application not found in the datastore for id " + key.getApplicationId());
                    }
                    loadInfoFromRestAPIAndValidate(api, app, key, sub, context, version, consumerKey, keyManager,
                            datastore, apiTenantDomain, infoDTO, tenantId);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Application keymapping not found in the datastore for id consumerKey " + consumerKey);
                }
                loadInfoFromRestAPIAndValidate(api, app, key, sub, context, version, consumerKey, keyManager,
                        datastore, apiTenantDomain, infoDTO, tenantId);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("API not found in the datastore for " + context + ":" + version);
            }
            loadInfoFromRestAPIAndValidate(api, app, key, sub, context, version, consumerKey, keyManager, datastore,
                    apiTenantDomain, infoDTO, tenantId);
        }
    } else {
        log.error("Subscription datastore is null for tenant domain " + apiTenantDomain);
        loadInfoFromRestAPIAndValidate(api, app, key, sub, context, version, consumerKey, keyManager, datastore,
                apiTenantDomain, infoDTO, tenantId);
    }
    
    if (api != null && app != null && key != null && sub != null) {
        validate(infoDTO, apiTenantDomain, tenantId, datastore, api, key, app, sub, keyManager);
    } else if (!infoDTO.isAuthorized() && infoDTO.getValidationStatus() == 0) {
        //Scenario where validation failed and message is not set
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
    }

    return infoDTO;
}
 
Example 20
Source File: SingleLogoutMessageBuilder.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public LogoutResponse buildLogoutResponse(String id, String status, String statMsg, String destination, boolean
        isSignResponse, String tenantDomain, String responseSigningAlgorithmUri, String responseDigestAlgoUri)
        throws IdentityException {

    LogoutResponse logoutResp = new LogoutResponseBuilder().buildObject();
    logoutResp.setID(SAMLSSOUtil.createID());
    logoutResp.setInResponseTo(id);
    logoutResp.setIssuer(SAMLSSOUtil.getIssuer());
    logoutResp.setStatus(buildStatus(status, statMsg));
    logoutResp.setIssueInstant(new DateTime());
    logoutResp.setDestination(destination);

    // Currently, does not sign the error response since this message pass through a url to the error page
    if (isSignResponse && SAMLSSOConstants.StatusCodes.SUCCESS_CODE.equals(status)) {
        int tenantId;
        if (StringUtils.isEmpty(tenantDomain)) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        } else {
            try {
                tenantId = SAMLSSOUtil.getRealmService().getTenantManager().getTenantId(tenantDomain);
            } catch (UserStoreException e) {
                throw IdentityException.error("Error occurred while retrieving tenant id from tenant domain", e);
            }

            if(MultitenantConstants.INVALID_TENANT_ID == tenantId) {
                throw IdentityException.error("Invalid tenant domain - '" + tenantDomain + "'" );
            }
        }

        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
            SAMLSSOUtil.setSignature(logoutResp, responseSigningAlgorithmUri, responseDigestAlgoUri, new
                    SignKeyDataHolder(null));
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    return logoutResp;
}