use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class ThrottlingApiServiceImpl method setPolicyPermissionsToDTO.
/**
* Set subscription throttle policy permission info into the DTO
*
* @param policyDTO subscription throttle policy DTO
* @throws APIManagementException error while setting/retrieve the permissions to the DTO
*/
private void setPolicyPermissionsToDTO(SubscriptionThrottlePolicyDTO policyDTO) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
TierPermissionDTO addedPolicyPermission = (TierPermissionDTO) apiProvider.getThrottleTierPermission(policyDTO.getPolicyName());
if (addedPolicyPermission != null) {
SubscriptionThrottlePolicyPermissionDTO addedPolicyPermissionDTO = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyPermissionToDTO(addedPolicyPermission);
policyDTO.setPermissions(addedPolicyPermissionDTO);
}
}
use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class ThrottlingApiServiceImpl method throttlingPoliciesSubscriptionPost.
/**
* Add a Subscription Level Throttle Policy
*
* @param body DTO of new policy to be created
* @param contentType Content-Type header
* @return Created policy along with the location of it with Location header
*/
@Override
public Response throttlingPoliciesSubscriptionPost(String contentType, SubscriptionThrottlePolicyDTO body, MessageContext messageContext) throws APIManagementException {
RestApiAdminUtils.validateThrottlePolicyNameProperty(body.getPolicyName());
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String username = RestApiCommonUtil.getLoggedInUsername();
SubscriptionPolicy subscriptionPolicy = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyDTOToModel(body);
// Check if there's a policy exists before adding the new policy
try {
Policy policyIfExists = apiProvider.getSubscriptionPolicy(username, subscriptionPolicy.getPolicyName());
if (policyIfExists != null) {
RestApiUtil.handleResourceAlreadyExistsError("Subscription Policy with name " + subscriptionPolicy.getPolicyName() + " already exists", log);
}
} catch (PolicyNotFoundException ignore) {
}
// validate if permission info exists and halt the execution in case of an error
validatePolicyPermissions(body);
// Add the policy
apiProvider.addPolicy(subscriptionPolicy);
// update policy permissions
updatePolicyPermissions(body);
// retrieve the new policy and send back as the response
SubscriptionPolicy newSubscriptionPolicy = apiProvider.getSubscriptionPolicy(username, body.getPolicyName());
SubscriptionThrottlePolicyDTO policyDTO = SubscriptionThrottlePolicyMappingUtil.fromSubscriptionThrottlePolicyToDTO(newSubscriptionPolicy);
// setting policy permissions
setPolicyPermissionsToDTO(policyDTO);
return Response.created(new URI(RestApiConstants.RESOURCE_PATH_THROTTLING_POLICIES_SUBSCRIPTION + "/" + policyDTO.getPolicyId())).entity(policyDTO).build();
} catch (ParseException e) {
String errorMessage = "Error while adding a Subscription level policy: " + body.getPolicyName();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving Subscription Throttle policy location : " + body.getPolicyName();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class PoliciesApiServiceImpl method policiesMediationPost.
/**
* Add a global mediation policy
*
* @param body Mediation DTO as request body
* @param contentType Content-Type header
* @return created mediation DTO as response
*/
@Override
public Response policiesMediationPost(String contentType, MediationDTO body, MessageContext messageContext) {
InputStream contentStream = null;
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String content = body.getConfig();
contentStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
ResourceFile contentFile = new ResourceFile(contentStream, contentType);
// Extracting mediation policy name from the mediation config
String fileName = this.getMediationNameFromConfig(content);
// constructing the registry resource path
String mediationPolicyPath = APIConstants.API_CUSTOM_SEQUENCE_LOCATION + RegistryConstants.PATH_SEPARATOR + body.getType() + RegistryConstants.PATH_SEPARATOR + fileName;
if (apiProvider.checkIfResourceExists(mediationPolicyPath)) {
RestApiUtil.handleConflict("Mediation policy already exists", log);
}
// Adding new global mediation sequence
// No need to check API permission, hence null as api identifier
String mediationPolicyUrl = apiProvider.addResourceFile(null, mediationPolicyPath, contentFile);
if (StringUtils.isNotBlank(mediationPolicyUrl)) {
// Getting the uuid of the created global mediation policy
String uuid = apiProvider.getCreatedResourceUuid(mediationPolicyPath);
// Getting created mediation policy
Mediation createdMediation = apiProvider.getGlobalMediationPolicy(uuid);
MediationDTO createdPolicy = MediationMappingUtil.fromMediationToDTO(createdMediation);
URI uploadedMediationUri = new URI(mediationPolicyUrl);
return Response.created(uploadedMediationUri).entity(createdPolicy).build();
}
} catch (APIManagementException e) {
String errorMessage = "Error while adding the global mediation policy " + body.getName();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (URISyntaxException e) {
String errorMessage = "Error while getting location header for created " + "mediation policy " + body.getName();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} finally {
IOUtils.closeQuietly(contentStream);
}
return null;
}
use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class PoliciesApiServiceImpl method policiesMediationMediationPolicyIdPut.
/**
* Updates an existing global mediation policy
*
* @param mediationPolicyId uuid of mediation policy
* @param body updated MediationDTO
* @param contentType Content-Type header
* @return updated mediation DTO as response
*/
@Override
public Response policiesMediationMediationPolicyIdPut(String mediationPolicyId, String contentType, MediationDTO body, MessageContext messageContext) {
InputStream contentStream = null;
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// Get registry resource correspond to given uuid
Resource mediationResource = apiProvider.getCustomMediationResourceFromUuid(mediationPolicyId);
if (mediationResource != null) {
// extracting already existing name of the mediation policy
String contentString = IOUtils.toString(mediationResource.getContentStream(), RegistryConstants.DEFAULT_CHARSET_ENCODING);
// Get policy name from the mediation config
OMElement omElement = AXIOMUtil.stringToOM(contentString);
OMAttribute attribute = omElement.getAttribute(new QName(PolicyConstants.MEDIATION_NAME_ATTRIBUTE));
String existingMediationPolicyName = attribute.getAttributeValue();
// replacing the name of the body with existing name
body.setName(existingMediationPolicyName);
// Getting mediation config to be update from the body
contentStream = new ByteArrayInputStream(body.getConfig().getBytes(StandardCharsets.UTF_8));
// Creating new resource file
ResourceFile contentFile = new ResourceFile(contentStream, contentType);
// Getting registry path of the existing resource
String resourcePath = mediationResource.getPath();
// Updating the existing global mediation policy
// No need to check API permission, hence null as api identifier
String updatedPolicyUrl = apiProvider.addResourceFile(null, resourcePath, contentFile);
if (StringUtils.isNotBlank(updatedPolicyUrl)) {
// Getting uuid of updated global mediation policy
String uuid = apiProvider.getCreatedResourceUuid(resourcePath);
// Getting updated mediation
Mediation updatedMediation = apiProvider.getGlobalMediationPolicy(uuid);
MediationDTO updatedMediationDTO = MediationMappingUtil.fromMediationToDTO(updatedMediation);
URI uploadedMediationUri = new URI(updatedPolicyUrl);
return Response.ok(uploadedMediationUri).entity(updatedMediationDTO).build();
}
} else {
// If resource not exists
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_POLICY, mediationPolicyId, log);
}
} catch (APIManagementException e) {
String errorMessage = "Error while updating the global mediation policy " + body.getName();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (URISyntaxException e) {
String errorMessage = "Error while getting location header for uploaded " + "mediation policy " + body.getName();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (XMLStreamException e) {
String errorMessage = "Error occurred while converting the existing content stream of " + " mediation " + "policy to string";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (RegistryException e) {
String errorMessage = "Error occurred while getting the existing content stream ";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (IOException e) {
String errorMessage = "Error occurred while converting content stream in to string ";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} finally {
IOUtils.closeQuietly(contentStream);
}
return null;
}
use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class JWTUtil method validateScopes.
/**
* @param message CXF message to be validate
* @param tokenInfo Token information associated with incoming request
* @return return true if we found matching scope in resource and token information
* else false(means scope validation failed).
*/
public static boolean validateScopes(HashMap<String, Object> message, OAuthTokenInfo tokenInfo) {
String basePath = (String) message.get(RestApiConstants.BASE_PATH);
// path is obtained from Message.REQUEST_URI instead of Message.PATH_INFO, as Message.PATH_INFO contains
// decoded values of request parameters
String path = (String) message.get(RestApiConstants.REQUEST_URL);
String verb = (String) message.get(RestApiConstants.REQUEST_METHOD);
String resource = path.substring(basePath.length() - 1);
String[] scopes = tokenInfo.getScopes();
String version = (String) message.get(RestApiConstants.API_VERSION);
// get all the URI templates of the REST API from the base path
Set<URITemplate> uriTemplates = (Set<URITemplate>) message.get(RestApiConstants.URI_TEMPLATES);
if (uriTemplates.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("No matching scopes found for request with path: " + basePath + ". Skipping scope validation.");
}
return true;
}
for (Object template : uriTemplates.toArray()) {
org.wso2.uri.template.URITemplate templateToValidate = null;
Map<String, String> var = new HashMap<String, String>();
// check scopes with what we have
String templateString = ((URITemplate) template).getUriTemplate();
try {
templateToValidate = new org.wso2.uri.template.URITemplate(templateString);
} catch (URITemplateException e) {
log.error("Error while creating URI Template object to validate request. Template pattern: " + templateString, e);
}
if (templateToValidate != null && templateToValidate.matches(resource, var) && scopes != null && verb != null && verb.equalsIgnoreCase(((URITemplate) template).getHTTPVerb())) {
for (String scope : scopes) {
Scope scp = ((URITemplate) template).getScope();
if (scp != null) {
if (scope.equalsIgnoreCase(scp.getKey())) {
// we found scopes matches
if (log.isDebugEnabled()) {
log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scp.getKey() + " for resource path: " + path + " and verb " + verb);
}
return true;
}
} else if (!((URITemplate) template).retrieveAllScopes().isEmpty()) {
List<Scope> scopesList = ((URITemplate) template).retrieveAllScopes();
for (Scope scpObj : scopesList) {
if (scope.equalsIgnoreCase(scpObj.getKey())) {
// we found scopes matches
if (log.isDebugEnabled()) {
log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scpObj.getKey() + " for resource path: " + path + " and verb " + verb);
}
return true;
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Scope not defined in swagger for matching resource " + resource + " and verb " + verb + " . So consider as anonymous permission and let request to continue.");
}
return true;
}
}
}
}
return false;
}
Aggregations