use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationKeyMappingUtil method fromApplicationKeysToDTO.
public static ApplicationKeysDTO fromApplicationKeysToDTO(OAuthApplicationInfo applicationKeys) {
ApplicationKeysDTO applicationKeyDTO = new ApplicationKeysDTO();
applicationKeyDTO.setKeyType(ApplicationKeysDTO.KeyTypeEnum.fromValue(applicationKeys.getKeyType()));
applicationKeyDTO.setConsumerKey(applicationKeys.getClientId());
applicationKeyDTO.setConsumerSecret(applicationKeys.getClientSecret());
applicationKeyDTO.setSupportedGrantTypes(applicationKeys.getGrantTypes());
return applicationKeyDTO;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsImportPost.
/**
* Import an Application which has been exported to a zip file
*
* @param fileInputStream Content stream of the zip file which contains exported Application
* @param fileDetail Meta information of the zip file
* @param preserveOwner If true, preserve the original owner of the application
* @param skipSubscriptions If true, skip subscriptions of the application
* @param appOwner Target owner of the application
* @param skipApplicationKeys Skip application keys while importing
* @param update Update if existing application found or import
* @param messageContext Message Context
* @return imported Application
*/
@Override
public Response applicationsImportPost(InputStream fileInputStream, Attachment fileDetail, Boolean preserveOwner, Boolean skipSubscriptions, String appOwner, Boolean skipApplicationKeys, Boolean update, MessageContext messageContext) throws APIManagementException {
String ownerId;
Application application;
try {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
String extractedFolderPath = CommonUtil.getArchivePathOfExtractedDirectory(fileInputStream, ImportExportConstants.UPLOAD_APPLICATION_FILE_NAME);
String jsonContent = ImportUtils.getApplicationDefinitionAsJson(extractedFolderPath);
// Retrieving the field "data" in api.yaml/json and convert it to a JSON object for further processing
JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
ExportedApplication exportedApplication = new Gson().fromJson(configElement, ExportedApplication.class);
// Retrieve the application DTO object from the aggregated exported application
ApplicationDTO applicationDTO = exportedApplication.getApplicationInfo();
if (!StringUtils.isBlank(appOwner)) {
ownerId = appOwner;
} else if (preserveOwner != null && preserveOwner) {
ownerId = applicationDTO.getOwner();
} else {
ownerId = username;
}
if (!MultitenantUtils.getTenantDomain(ownerId).equals(MultitenantUtils.getTenantDomain(username))) {
throw new APIManagementException("Cross Tenant Imports are not allowed", ExceptionCodes.TENANT_MISMATCH);
}
String applicationGroupId = String.join(",", applicationDTO.getGroups());
if (applicationDTO.getGroups() != null && applicationDTO.getGroups().size() > 0) {
ImportUtils.validateOwner(username, applicationGroupId, apiConsumer);
}
String organization = RestApiUtil.getValidatedOrganization(messageContext);
if (APIUtil.isApplicationExist(ownerId, applicationDTO.getName(), applicationGroupId, organization) && update != null && update) {
int appId = APIUtil.getApplicationId(applicationDTO.getName(), ownerId);
Application oldApplication = apiConsumer.getApplicationById(appId);
application = preProcessAndUpdateApplication(ownerId, applicationDTO, oldApplication, oldApplication.getUUID());
} else {
application = preProcessAndAddApplication(ownerId, applicationDTO, organization);
update = Boolean.FALSE;
}
List<APIIdentifier> skippedAPIs = new ArrayList<>();
if (skipSubscriptions == null || !skipSubscriptions) {
skippedAPIs = ImportUtils.importSubscriptions(exportedApplication.getSubscribedAPIs(), ownerId, application, update, apiConsumer, organization);
}
Application importedApplication = apiConsumer.getApplicationById(application.getId());
importedApplication.setOwner(ownerId);
ApplicationInfoDTO importedApplicationDTO = ApplicationMappingUtil.fromApplicationToInfoDTO(importedApplication);
URI location = new URI(RestApiConstants.RESOURCE_PATH_APPLICATIONS + "/" + importedApplicationDTO.getApplicationId());
// check whether keys need to be skipped while import
if (skipApplicationKeys == null || !skipApplicationKeys) {
// if this is an update, old keys will be removed and the OAuth app will be overridden with new values
if (update) {
if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() > 0) {
importedApplication.getKeys().clear();
}
}
// Add application keys if present and keys does not exists in the current application
if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() == 0) {
for (ApplicationKeyDTO applicationKeyDTO : applicationDTO.getKeys()) {
ImportUtils.addApplicationKey(ownerId, importedApplication, applicationKeyDTO, apiConsumer, update);
}
}
}
if (skippedAPIs.isEmpty()) {
return Response.created(location).entity(importedApplicationDTO).build();
} else {
APIInfoListDTO skippedAPIListDTO = APIInfoMappingUtil.fromAPIInfoListToDTO(skippedAPIs);
return Response.created(location).status(207).entity(skippedAPIListDTO).build();
}
} catch (URISyntaxException | UserStoreException | APIImportExportException e) {
throw new APIManagementException("Error while importing Application", e);
} catch (UnsupportedEncodingException e) {
throw new APIManagementException("Error while Decoding apiId", e);
} catch (IOException e) {
throw new APIManagementException("Error while reading the application definition", e);
}
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsApplicationIdKeysKeyTypePut.
/**
* Update grant types/callback URL
*
* @param applicationId Application Id
* @param keyType Key Type (Production | Sandbox)
* @param body Grant type and callback URL information
* @return Updated Key Information
*/
@Override
public Response applicationsApplicationIdKeysKeyTypePut(String applicationId, String keyType, ApplicationKeyDTO body, MessageContext messageContext) {
String username = RestApiCommonUtil.getLoggedInUsername();
try {
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application != null) {
if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
String grantTypes = StringUtils.join(body.getSupportedGrantTypes(), ',');
JsonObject jsonParams = new JsonObject();
jsonParams.addProperty(APIConstants.JSON_GRANT_TYPES, grantTypes);
jsonParams.addProperty(APIConstants.JSON_USERNAME, username);
if (body.getAdditionalProperties() != null) {
if (body.getAdditionalProperties() instanceof String && StringUtils.isNotEmpty((String) body.getAdditionalProperties())) {
jsonParams.addProperty(APIConstants.JSON_ADDITIONAL_PROPERTIES, (String) body.getAdditionalProperties());
} else if (body.getAdditionalProperties() instanceof Map) {
String jsonContent = new Gson().toJson(body.getAdditionalProperties());
jsonParams.addProperty(APIConstants.JSON_ADDITIONAL_PROPERTIES, jsonContent);
}
}
String keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
OAuthApplicationInfo updatedData = apiConsumer.updateAuthClient(username, application, keyType, body.getCallbackUrl(), null, null, null, body.getGroupId(), new Gson().toJson(jsonParams), keyManagerName);
ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
applicationKeyDTO.setCallbackUrl(updatedData.getCallBackURL());
JsonObject json = new Gson().fromJson(updatedData.getJsonString(), JsonObject.class);
if (json.get(APIConstants.JSON_GRANT_TYPES) != null) {
String[] updatedGrantTypes = json.get(APIConstants.JSON_GRANT_TYPES).getAsString().split(" ");
applicationKeyDTO.setSupportedGrantTypes(Arrays.asList(updatedGrantTypes));
}
applicationKeyDTO.setConsumerKey(updatedData.getClientId());
applicationKeyDTO.setConsumerSecret(updatedData.getClientSecret());
applicationKeyDTO.setKeyType(ApplicationKeyDTO.KeyTypeEnum.valueOf(keyType));
Object additionalProperties = updatedData.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
if (additionalProperties != null) {
applicationKeyDTO.setAdditionalProperties(additionalProperties);
}
return Response.ok().entity(applicationKeyDTO).build();
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error while updating application " + applicationId, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsApplicationIdKeysKeyTypeRegenerateSecretPost.
/**
* Re generate consumer secret.
*
* @param applicationId Application Id
* @param keyType Key Type (Production | Sandbox)
* @return A response object containing application keys.
*/
@Override
public Response applicationsApplicationIdKeysKeyTypeRegenerateSecretPost(String applicationId, String keyType, MessageContext messageContext) {
String username = RestApiCommonUtil.getLoggedInUsername();
try {
Set<APIKey> applicationKeys = getApplicationKeys(applicationId);
if (applicationKeys == null) {
return null;
}
for (APIKey apiKey : applicationKeys) {
if (keyType != null && keyType.equals(apiKey.getType()) && APIConstants.KeyManager.DEFAULT_KEY_MANAGER.equals(apiKey.getKeyManager())) {
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
String clientId = apiKey.getConsumerKey();
String clientSecret = apiConsumer.renewConsumerSecret(clientId, APIConstants.KeyManager.DEFAULT_KEY_MANAGER);
ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
applicationKeyDTO.setConsumerKey(clientId);
applicationKeyDTO.setConsumerSecret(clientSecret);
return Response.ok().entity(applicationKeyDTO).build();
}
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error while re generating the consumer secret ", e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsApplicationIdOauthKeysKeyMappingIdGenerateTokenPost.
@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdGenerateTokenPost(String applicationId, String keyMappingId, ApplicationTokenGenerateRequestDTO body, String ifMatch, MessageContext messageContext) throws APIManagementException {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application != null) {
if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyMapping(applicationId, keyMappingId);
if (appKey != null) {
String jsonInput = null;
String grantType;
if (ApplicationTokenGenerateRequestDTO.GrantTypeEnum.TOKEN_EXCHANGE.equals(body.getGrantType())) {
grantType = APIConstants.OAuthConstants.TOKEN_EXCHANGE;
} else {
grantType = APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS;
}
try {
// verify that the provided jsonInput is a valid json
if (body.getAdditionalProperties() != null && !body.getAdditionalProperties().toString().isEmpty()) {
jsonInput = validateAdditionalParameters(grantType, body);
}
} catch (JsonProcessingException | ParseException | ClassCastException e) {
RestApiUtil.handleBadRequest("Error while generating " + appKey.getKeyType() + " token for " + "application " + applicationId + ". Invalid jsonInput '" + body.getAdditionalProperties() + "' provided.", log);
}
if (StringUtils.isNotEmpty(body.getConsumerSecret())) {
appKey.setConsumerSecret(body.getConsumerSecret());
}
String[] scopes = body.getScopes().toArray(new String[0]);
try {
AccessTokenInfo response = apiConsumer.renewAccessToken(body.getRevokeToken(), appKey.getConsumerKey(), appKey.getConsumerSecret(), body.getValidityPeriod().toString(), scopes, jsonInput, appKey.getKeyManager(), grantType);
ApplicationTokenDTO appToken = new ApplicationTokenDTO();
appToken.setAccessToken(response.getAccessToken());
if (response.getScopes() != null) {
appToken.setTokenScopes(Arrays.asList(response.getScopes()));
}
appToken.setValidityTime(response.getValidityPeriod());
return Response.ok().entity(appToken).build();
} catch (APIManagementException e) {
Long errorCode = e.getErrorHandler() != null ? e.getErrorHandler().getErrorCode() : ExceptionCodes.INTERNAL_ERROR.getErrorCode();
RestApiUtil.handleBadRequest(e.getMessage(), errorCode, log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_CONSUMER_KEY, keyMappingId, log);
}
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
return null;
}
Aggregations