Search in sources :

Example 41 with APIConsumer

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

the class ApplicationsApiServiceImpl method applicationsExportGet.

/**
 * Export an existing Application
 *
 * @param appName        Search query
 * @param appOwner       Owner of the Application
 * @param withKeys       Export keys with application
 * @param format         Export format
 * @param messageContext Message Context
 * @return Zip file containing exported Application
 */
@Override
public Response applicationsExportGet(String appName, String appOwner, Boolean withKeys, String format, MessageContext messageContext) throws APIManagementException {
    APIConsumer apiConsumer;
    Application application = null;
    if (StringUtils.isBlank(appName) || StringUtils.isBlank(appOwner)) {
        RestApiUtil.handleBadRequest("Application name or owner should not be empty or null.", log);
    }
    // Default export format is YAML
    ExportFormat exportFormat = StringUtils.isNotEmpty(format) ? ExportFormat.valueOf(format.toUpperCase()) : ExportFormat.YAML;
    String username = RestApiCommonUtil.getLoggedInUsername();
    apiConsumer = RestApiCommonUtil.getConsumer(username);
    if (appOwner != null && apiConsumer.getSubscriber(appOwner) != null) {
        application = ExportUtils.getApplicationDetails(appName, appOwner, apiConsumer);
    }
    if (application == null) {
        throw new APIManagementException("No application found with name " + appName + " owned by " + appOwner, ExceptionCodes.APPLICATION_NOT_FOUND);
    } else if (!MultitenantUtils.getTenantDomain(application.getSubscriber().getName()).equals(MultitenantUtils.getTenantDomain(username))) {
        throw new APIManagementException("Cross Tenant Exports are not allowed", ExceptionCodes.TENANT_MISMATCH);
    }
    File file = ExportUtils.exportApplication(application, apiConsumer, exportFormat, withKeys);
    return Response.ok(file).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"").build();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportFormat(org.wso2.carbon.apimgt.impl.importexport.ExportFormat) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) File(java.io.File)

Example 42 with APIConsumer

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

the class ApplicationsApiServiceImpl method applicationsApplicationIdApiKeysKeyTypeRevokePost.

@Override
public Response applicationsApplicationIdApiKeysKeyTypeRevokePost(String applicationId, String keyType, String ifMatch, APIKeyRevokeRequestDTO body, MessageContext messageContext) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    String apiKey = body.getApikey();
    if (!StringUtils.isEmpty(apiKey) && APIUtil.isValidJWT(apiKey)) {
        try {
            String[] splitToken = apiKey.split("\\.");
            String signatureAlgorithm = APIUtil.getSignatureAlgorithm(splitToken);
            String certAlias = APIUtil.getSigningAlias(splitToken);
            Certificate certificate = APIUtil.getCertificateFromParentTrustStore(certAlias);
            if (APIUtil.verifyTokenSignature(splitToken, certificate, signatureAlgorithm)) {
                APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
                Application application = apiConsumer.getApplicationByUUID(applicationId);
                org.json.JSONObject decodedBody = new org.json.JSONObject(new String(Base64.getUrlDecoder().decode(splitToken[1])));
                org.json.JSONObject appInfo = decodedBody.getJSONObject(APIConstants.JwtTokenConstants.APPLICATION);
                if (appInfo != null && application != null) {
                    if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
                        String appUuid = appInfo.getString(APIConstants.JwtTokenConstants.APPLICATION_UUID);
                        if (applicationId.equals(appUuid)) {
                            long expiryTime = Long.MAX_VALUE;
                            org.json.JSONObject payload = new org.json.JSONObject(new String(Base64.getUrlDecoder().decode(splitToken[1])));
                            if (payload.has(APIConstants.JwtTokenConstants.EXPIRY_TIME)) {
                                expiryTime = APIUtil.getExpiryifJWT(apiKey);
                            }
                            String tokenIdentifier = payload.getString(APIConstants.JwtTokenConstants.JWT_ID);
                            String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
                            apiConsumer.revokeAPIKey(tokenIdentifier, expiryTime, tenantDomain);
                            return Response.ok().build();
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug("Application uuid " + applicationId + " isn't matched with the " + "application in the token " + appUuid + " of API Key " + APIUtil.getMaskedToken(apiKey));
                            }
                            RestApiUtil.handleBadRequest("Validation failed for the given token ", log);
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Logged in user " + username + " isn't the owner of the application " + applicationId);
                        }
                        RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        if (application == null) {
                            log.debug("Application with given id " + applicationId + " doesn't not exist ");
                        }
                        if (appInfo == null) {
                            log.debug("Application information doesn't exist in the token " + APIUtil.getMaskedToken(apiKey));
                        }
                    }
                    RestApiUtil.handleBadRequest("Validation failed for the given token ", log);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Signature verification of given token " + APIUtil.getMaskedToken(apiKey) + " is failed");
                }
                RestApiUtil.handleInternalServerError("Validation failed for the given token", log);
            }
        } catch (APIManagementException e) {
            String msg = "Error while revoking API Key of application " + applicationId;
            if (log.isDebugEnabled()) {
                log.debug("Error while revoking API Key of application " + applicationId + " and token " + APIUtil.getMaskedToken(apiKey));
            }
            log.error(msg, e);
            RestApiUtil.handleInternalServerError(msg, e, log);
        }
    } else {
        log.debug("Provided API Key " + APIUtil.getMaskedToken(apiKey) + " is not valid");
        RestApiUtil.handleBadRequest("Provided API Key isn't valid ", log);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) Certificate(java.security.cert.Certificate)

Example 43 with APIConsumer

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

the class ApplicationsApiServiceImpl method applicationsApplicationIdApiKeysKeyTypeGeneratePost.

@Override
public Response applicationsApplicationIdApiKeysKeyTypeGeneratePost(String applicationId, String keyType, String ifMatch, APIKeyGenerateRequestDTO body, MessageContext messageContext) {
    String userName = RestApiCommonUtil.getLoggedInUsername();
    Application application;
    int validityPeriod;
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(userName);
        if ((application = apiConsumer.getApplicationByUUID(applicationId)) == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        } else {
            if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            } else {
                if (APIConstants.API_KEY_TYPE_PRODUCTION.equalsIgnoreCase(keyType)) {
                    application.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
                } else if (APIConstants.API_KEY_TYPE_SANDBOX.equalsIgnoreCase(keyType)) {
                    application.setKeyType(APIConstants.API_KEY_TYPE_SANDBOX);
                } else {
                    RestApiUtil.handleBadRequest("Invalid keyType. KeyType should be either PRODUCTION or SANDBOX", log);
                }
                if (body != null && body.getValidityPeriod() != null && body.getValidityPeriod() > 0) {
                    validityPeriod = body.getValidityPeriod();
                } else {
                    validityPeriod = -1;
                }
                String restrictedIP = null;
                String restrictedReferer = null;
                if (body.getAdditionalProperties() != null) {
                    Map additionalProperties = (HashMap) body.getAdditionalProperties();
                    if (additionalProperties.get(APIConstants.JwtTokenConstants.PERMITTED_IP) != null) {
                        restrictedIP = (String) additionalProperties.get(APIConstants.JwtTokenConstants.PERMITTED_IP);
                    }
                    if (additionalProperties.get(APIConstants.JwtTokenConstants.PERMITTED_REFERER) != null) {
                        restrictedReferer = (String) additionalProperties.get(APIConstants.JwtTokenConstants.PERMITTED_REFERER);
                    }
                }
                String apiKey = apiConsumer.generateApiKey(application, userName, validityPeriod, restrictedIP, restrictedReferer);
                APIKeyDTO apiKeyDto = ApplicationKeyMappingUtil.formApiKeyToDTO(apiKey, validityPeriod);
                return Response.ok().entity(apiKeyDto).build();
            }
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while generatig API Keys for application " + applicationId, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) Map(java.util.Map) HashMap(java.util.HashMap) APIKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIKeyDTO)

Example 44 with APIConsumer

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

the class ApplicationsApiServiceImpl method applicationsApplicationIdMapKeysPost.

/**
 * Generate keys using existing consumer key and consumer secret
 *
 * @param applicationId Application id
 * @param body          Contains consumer key, secret and key type information
 * @return A response object containing application keys
 */
@Override
public Response applicationsApplicationIdMapKeysPost(String applicationId, ApplicationKeyMappingRequestDTO body, String xWSO2Tenant, MessageContext messageContext) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    JSONObject jsonParamObj = new JSONObject();
    APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
    Application application = apiConsumer.getApplicationByUUID(applicationId);
    String keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
    if (StringUtils.isNotEmpty(body.getKeyManager())) {
        keyManagerName = body.getKeyManager();
    }
    if (application != null) {
        if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
            String clientId = body.getConsumerKey();
            String keyType = body.getKeyType().toString();
            String tokenType = APIConstants.DEFAULT_TOKEN_TYPE;
            jsonParamObj.put(APIConstants.SUBSCRIPTION_KEY_TYPE, body.getKeyType().toString());
            jsonParamObj.put(APIConstants.JSON_CLIENT_SECRET, body.getConsumerSecret());
            String organization = RestApiUtil.getValidatedOrganization(messageContext);
            Map<String, Object> keyDetails = apiConsumer.mapExistingOAuthClient(jsonParamObj.toJSONString(), username, clientId, application.getName(), keyType, tokenType, keyManagerName, organization);
            ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil.fromApplicationKeyToDTO(keyDetails, body.getKeyType().toString());
            applicationKeyDTO.setKeyManager(keyManagerName);
            return Response.ok().entity(applicationKeyDTO).build();
        } else {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } else {
        RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 45 with APIConsumer

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

the class ExportUtils method getApplicationDetails.

/**
 * Retrieve all the details of an Application by name for a given user.
 *
 * @param appName     name of the application
 * @param username    User name
 * @param apiConsumer API Consumer
 * @return {@link Application} instance
 * @throws APIManagementException if an error occurs while retrieving Application details
 */
public static Application getApplicationDetails(String appName, String username, APIConsumer apiConsumer) throws APIManagementException {
    Application application;
    int appId = APIUtil.getApplicationId(appName, username);
    String groupId = apiConsumer.getGroupId(appId);
    application = apiConsumer.getApplicationById(appId);
    if (application != null) {
        application.setGroupId(groupId);
        application.setOwner(application.getSubscriber().getName());
    }
    return application;
}
Also used : ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application)

Aggregations

APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)91 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)79 Application (org.wso2.carbon.apimgt.api.model.Application)50 Test (org.junit.Test)46 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)46 HashMap (java.util.HashMap)32 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)29 ArrayList (java.util.ArrayList)28 API (org.wso2.carbon.apimgt.api.model.API)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)28 JSONObject (org.json.simple.JSONObject)23 ExportedApplication (org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication)23 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)20 Map (java.util.Map)19 Matchers.anyString (org.mockito.Matchers.anyString)19 ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)18 Tier (org.wso2.carbon.apimgt.api.model.Tier)18 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)15 URI (java.net.URI)13 URISyntaxException (java.net.URISyntaxException)13