Java Code Examples for org.wso2.carbon.utils.multitenancy.MultitenantUtils#getTenantDomainFromRequestURL()

The following examples show how to use org.wso2.carbon.utils.multitenancy.MultitenantUtils#getTenantDomainFromRequestURL() . 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: 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 2
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 3
Source File: EmailSender.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private String getRequestMessage() {
    String msg;
    String targetEpr = config.getTargetEpr();
    String tenantDomain = this.tenantDomain;
    if (tenantDomain == null) {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
    }
    if (tenantDomain != null && targetEpr.indexOf("/carbon") > 0 &&
        MultitenantUtils.getTenantDomainFromRequestURL(targetEpr) == null &&
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)!= MultitenantConstants.SUPER_TENANT_ID) {
        targetEpr = targetEpr.replace("/carbon", "/" +
                                                 MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain + "/carbon");
    }
    if (config.getEmailBody().length() == 0) {
        msg = EmailVerifierConfig.DEFAULT_VALUE_MESSAGE + "\n" + targetEpr + "?"
              + CONF_STRING + "=" + secretKey + "\n";
    } else {
        msg = config.getEmailBody() + "\n" + targetEpr + "?" + CONF_STRING + "="
              + secretKey + "\n";
    }
    if (config.getEmailFooter() != null) {
        msg = msg + "\n" + config.getEmailFooter();
    }
    return msg;
}
 
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: APIMgtFaultHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
protected String getTenantDomainFromRequestURL(String fullRequestPath) {
    return MultitenantUtils.getTenantDomainFromRequestURL(fullRequestPath);
}
 
Example 6
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 7
Source File: RequestIntercepterValve.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {

    Long startTime = System.currentTimeMillis();

    getNext().invoke(request, response);

    if(CarbonUtils.isWorkerNode()){
        return;
    }

    Long responseTime = System.currentTimeMillis() - startTime;

    String requestURI = request.getRequestURI().trim();

    //Extracting the tenant domain using the requested url.
    String tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(requestURI);


    StatisticData statisticData = new StatisticData();

    int firstDigit = Integer.parseInt(Integer.toString(response.getStatus()).substring(0, 1));

    statisticData.setRequstCount(1);
    if (firstDigit == 2 || firstDigit == 3) {
        statisticData.setResponseCount(1);
        statisticData.setFaultCount(0);
    } else if (firstDigit == 4 || firstDigit == 5) {
        statisticData.setResponseCount(0);
        statisticData.setFaultCount(1);
    }

    String[] requestedUriParts = requestURI.split("/");
    if(requestedUriParts == null){
        return;
    }
    if (requestedUriParts.length >= 5 && requestURI.startsWith("/t/")) {
        statisticData.setWebappName(requestedUriParts[4]);
        statisticData.setTenantName(requestedUriParts[2]);
    } else if (requestedUriParts.length >= 2 && !requestURI.startsWith("/t/")){
        statisticData.setWebappName(requestedUriParts[1]);
        statisticData.setTenantName(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    } else{
        return;
    }

    //Extracting the configuration context. if tenant domain is null then main carbon server configuration is loaded
   /* ConfigurationContext currentCtx;
    if (tenantDomain != null) {
        currentCtx = getTenantConfigurationContext(tenantDomain);
    } else {
        currentCtx = CarbonDataHolder.getServerConfigContext();
    }*/

    //Requesting the tenant id, if this main carbon context id will be -1234
    int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    statisticData.setTenantId(tenantID);
    statisticData.setResponseTime(responseTime);

    ComputeData cd = new ComputeData();
    cd.setRequestData(statisticData);

}