Java Code Examples for org.wso2.carbon.apimgt.impl.utils.APIUtil#getTenantIdFromTenantDomain()

The following examples show how to use org.wso2.carbon.apimgt.impl.utils.APIUtil#getTenantIdFromTenantDomain() . 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: CertificateRestApiUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * To pre validate client certificate given for an alias
 *
 * @param alias Alias of the certificate.
 * @return Client certificate
 * @throws APIManagementException API Management Exception.
 */
public static ClientCertificateDTO preValidateClientCertificate(String alias, APIIdentifier apiIdentifier)
        throws APIManagementException {
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    if (StringUtils.isEmpty(alias)) {
        RestApiUtil.handleBadRequest("The alias cannot be empty", log);
    }
    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    if (!apiProvider.isClientCertificateBasedAuthenticationConfigured()) {
        RestApiUtil.handleBadRequest(
                "The client certificate based authentication is not configured for this server", log);
    }
    ClientCertificateDTO clientCertificate = apiProvider.getClientCertificate(tenantId, alias, apiIdentifier);
    if (clientCertificate == null) {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Could not find a client certificate in truststore which belongs to "
                    + "tenant : %d and with alias : %s. Hence the operation is terminated.", tenantId, alias));
        }
        String message = "Certificate for alias '" + alias + "' is not found.";
        RestApiUtil.handleResourceNotFoundError(message, log);
    }
    return clientCertificate;
}
 
Example 2
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Set API categories to API or APIProduct based on the instance type of the DTO object passes
 * @param dto APIDTO or APIProductDTO
 * @param model API or APIProduct
 */
private static void setAPICategoriesToModel(Object dto, Object model, String provider) {
    List<String> apiCategoryNames = new ArrayList<>();
    if (dto instanceof APIDTO) {
        APIDTO apiDTO = (APIDTO)dto;
        apiCategoryNames = apiDTO.getCategories();
    } else {
        APIProductDTO apiProductDTO = (APIProductDTO)dto;
        apiCategoryNames = apiProductDTO.getCategories();
    }
    provider = APIUtil.replaceEmailDomainBack(provider);
    String tenantDomain = MultitenantUtils.getTenantDomain(provider);
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    List<APICategory> apiCategories = new ArrayList<>();
    for (String categoryName : apiCategoryNames) {
        APICategory category = new APICategory();
        category.setName(categoryName);
        category.setTenantID(tenantId);
        apiCategories.add(category);
    }
    if (model instanceof API) {
        ((API)model).setApiCategories(apiCategories);
    } else {
        ((APIProduct)model).setApiCategories(apiCategories);
    }
}
 
Example 3
Source File: APIMOAuthEventInterceptor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private void persistRevokedJWTSignature(String token, Long expiryTime) {

        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        try {
            String tokenSignature = APIUtil.getSignatureIfJWT(token);
            String tenantDomain = APIUtil.getTenantDomainIfJWT(token);
            int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
            apiMgtDAO.addRevokedJWTSignature(tokenSignature, APIConstants.DEFAULT, expiryTime, tenantId);

            // Cleanup expired revoked tokens from db.
            Runnable expiredJWTCleaner = new ExpiredJWTCleaner();
            Thread cleanupThread = new Thread(expiredJWTCleaner);
            cleanupThread.start();
        } catch (APIManagementException e) {
            log.error("Unable to add revoked JWT signature to the database");
        }
    }
 
Example 4
Source File: APIGatewayManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * To deploy client certificate in given API environment.
 *
 * @param api          Relevant API.
 * @param tenantDomain Tenant domain.
 * @throws CertificateManagementException Certificate Management Exception.
 */
private void setClientCertificatesToBeAdded(API api, String tenantDomain, GatewayAPIDTO gatewayAPIDTO)
        throws CertificateManagementException {

    if (!CertificateManagerImpl.getInstance().isClientCertificateBasedAuthenticationConfigured()) {
        return;
    }
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    List<ClientCertificateDTO> clientCertificateDTOList = CertificateMgtDAO.getInstance()
            .getClientCertificates(tenantId, null, api.getId());
    if (clientCertificateDTOList != null) {
        for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOList) {
            GatewayContentDTO clientCertificate = new GatewayContentDTO();
            clientCertificate.setName(clientCertificateDTO.getAlias() + "_" + tenantId);
            clientCertificate.setContent(clientCertificateDTO.getCertificate());
            gatewayAPIDTO.setClientCertificatesToBeAdd(addGatewayContentToList(clientCertificate,
                    gatewayAPIDTO.getClientCertificatesToBeAdd()));
        }
    }
}
 
Example 5
Source File: APIGatewayManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * To undeploy the client certificates from the gateway environment.
 *
 * @param api          Relevant API particular certificate is related with.
 * @param tenantDomain Tenant domain of the API.
 * @throws CertificateManagementException Certificate Management Exception.
 */
private void setClientCertificatesToBeRemoved(API api, String tenantDomain, GatewayAPIDTO gatewayAPIDTO)
        throws CertificateManagementException {

    if (!CertificateManagerImpl.getInstance().isClientCertificateBasedAuthenticationConfigured()) {
        return;
    }
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    List<ClientCertificateDTO> clientCertificateDTOList = CertificateMgtDAO.getInstance()
            .getClientCertificates(tenantId, null, api.getId());
    if (clientCertificateDTOList != null) {
        for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOList) {
            gatewayAPIDTO.setClientCertificatesToBeRemove(addStringToList(clientCertificateDTO.getAlias() + "_" +
                    tenantId, gatewayAPIDTO.getLocalEntriesToBeRemove()));
        }
    }
    List<String> aliasList = CertificateMgtDAO.getInstance()
            .getDeletedClientCertificateAlias(api.getId(), tenantId);
    for (String alias : aliasList) {
        gatewayAPIDTO.setClientCertificatesToBeRemove(addStringToList(alias + "_" + tenantId,
                gatewayAPIDTO.getClientCertificatesToBeRemove()));
    }
}
 
Example 6
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 7
Source File: ApiCategoriesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public Response apiCategoriesGet(MessageContext messageContext) {
    try {
        APIAdmin apiAdmin = new APIAdminImpl();
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        int tenantID = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
        List<APICategory> categoryList = apiAdmin.getAPICategoriesOfTenant(tenantID);
        APICategoryListDTO categoryListDTO = APICategoryMappingUtil.fromCategoryListToCategoryListDTO(categoryList);
        return Response.ok().entity(categoryListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API categories";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 8
Source File: EndpointCertificatesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public Response endpointCertificatesAliasContentGet(String alias, MessageContext messageContext) {
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    String certFileName = alias + ".crt";

    if (!StringUtils.isNotEmpty(alias)) {
        RestApiUtil.handleBadRequest("The alias cannot be empty", log);
    }

    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        if (!apiProvider.isCertificatePresent(tenantId, alias)) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Could not find a certificate in truststore which belongs to tenant : %d " +
                        "and with alias : %s. Hence the operation is terminated.", tenantId, alias));
            }
            String message = "Certificate for Alias '" + alias + "' is not found.";
            RestApiUtil.handleResourceNotFoundError(message, log);
        }

        Object certificate = apiProvider.getCertificateContent(alias);
        if (certificate != null) {
            Response.ResponseBuilder responseBuilder = Response.ok().entity(certificate);
            responseBuilder.header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\""
                    + certFileName + "\"");
            responseBuilder.header(RestApiConstants.HEADER_CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);
            return responseBuilder.build();
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving the certificate status.", e, log);
    }
    return null;
}
 
Example 9
Source File: EndpointCertificatesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public Response endpointCertificatesAliasDelete(String alias, MessageContext messageContext) {
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    String userName = RestApiUtil.getLoggedInUsername();

    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        if (!apiProvider.isCertificatePresent(tenantId, alias)) {
            String message = "Certificate for alias '" + alias + "' is not found.";
            RestApiUtil.handleResourceNotFoundError(message, log);
        }

        int responseCode = apiProvider.deleteCertificate(userName, alias, null);

        if (responseCode == ResponseCode.SUCCESS.getResponseCode()) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("The certificate which belongs to tenant : %d represented by the alias : " +
                        "%s is deleted successfully", tenantId, alias));
            }
            return Response.ok().build();
        } else {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Failed to delete the certificate which belongs to tenant : %d " +
                        "represented by the alias : %s.", tenantId, alias));
            }
            RestApiUtil.handleInternalServerError("Error while deleting the certificate for alias '" +
                    alias + "'.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while deleting the certificate for alias '" +
                alias + "'.", e, log);
    }
    return null;
}
 
Example 10
Source File: ScopesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public Response getSharedScopeUsages(String scopeId, MessageContext messageContext)
        throws APIManagementException {
    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    if (StringUtils.isEmpty(scopeId)) {
        throw new APIManagementException("Scope Id cannot be null or empty",
                ExceptionCodes.SHARED_SCOPE_ID_NOT_SPECIFIED);
    }
    SharedScopeUsage sharedScopeUsage = apiProvider.getSharedScopeUsage(scopeId, tenantId);
    SharedScopeUsageDTO sharedScopeUsageDTO = SharedScopeMappingUtil.fromSharedScopeUsageToDTO(sharedScopeUsage);
    return Response.ok().entity(sharedScopeUsageDTO).build();
}
 
Example 11
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether the given scope key is already assigned to any API under given tenant.
 *
 * @param scopeKey     Scope Key
 * @param tenantDomain Tenant Domain
 * @return whether scope is assigned or not
 * @throws APIManagementException if failed to check the scope assignment
 */
@Override
public boolean isScopeKeyAssignedToAPI(String scopeKey, String tenantDomain) throws APIManagementException {

    if (log.isDebugEnabled()) {
        log.debug("Checking whether the scope:" + scopeKey + " is attached to any API in tenant: " + tenantDomain);
    }
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    return apiMgtDAO.isScopeKeyAssigned(scopeKey, tenantId);
}
 
Example 12
Source File: ApiCategoriesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public Response apiCategoriesGet() {
    try {
        APIAdmin apiAdmin = new APIAdminImpl();
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        int tenantID = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
        List<APICategory> categoryList = apiAdmin.getAllAPICategoriesOfTenant(tenantID);
        APICategoryListDTO categoryListDTO =
                APICategoryMappingUtil.fromCategoryListToCategoryListDTO(categoryList);
        return Response.ok().entity(categoryListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API categories";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 13
Source File: EndpointCertificatesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public Response endpointCertificatesAliasGet(String alias, MessageContext messageContext) {
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);

    if (!StringUtils.isNotEmpty(alias)) {
        RestApiUtil.handleBadRequest("The alias cannot be empty", log);
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Retrieving the common information of the certificate which is represented by the" +
                " alias : %s", alias));
    }

    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        if (!apiProvider.isCertificatePresent(tenantId, alias)) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Could not find a certificate in truststore which belongs to tenant %d " +
                        "and with alias %s. Hence the operation is terminated.", tenantId, alias));
            }
            String message = "Certificate for Alias '" + alias + "' is not found.";
            RestApiUtil.handleResourceNotFoundError(message, log);
        }

        CertificateInformationDTO certificateInformationDTO = apiProvider.getCertificateStatus(alias);

        CertificateValidityDTO certificateValidityDTO = new CertificateValidityDTO();
        certificateValidityDTO.setFrom(certificateInformationDTO.getFrom());
        certificateValidityDTO.setTo(certificateInformationDTO.getTo());

        CertificateInfoDTO certificateInfoDTO = new CertificateInfoDTO();
        certificateInfoDTO.setValidity(certificateValidityDTO);
        certificateInfoDTO.setStatus(certificateInformationDTO.getStatus());
        certificateInfoDTO.setSubject(certificateInformationDTO.getSubject());
        certificateInfoDTO.setVersion(certificateInformationDTO.getVersion());

        return Response.ok().entity(certificateInfoDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving the certificate status.", e, log);
    }
    return null;
}
 
Example 14
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;
}