use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class SubscriptionsApiServiceImpl method subscriptionsGet.
/**
* Get all subscriptions that are of user or shared subscriptions of the user's group.
* <p/>
* If apiId is specified this will return the subscribed applications of that api
* If application id is specified this will return the api subscriptions of that application
*
* @param apiId api identifier
* @param applicationId application identifier
* @param offset starting index of the subscription list
* @param limit max num of subscriptions returned
* @param ifNoneMatch If-None-Match header value
* @return matched subscriptions as a list of SubscriptionDTOs
*/
@Override
public Response subscriptionsGet(String apiId, String applicationId, String groupId, String xWSO2Tenant, Integer offset, Integer limit, String ifNoneMatch, MessageContext messageContext) {
String username = RestApiCommonUtil.getLoggedInUsername();
Subscriber subscriber = new Subscriber(username);
Set<SubscribedAPI> subscriptions;
List<SubscribedAPI> subscribedAPIList = new ArrayList<>();
// pre-processing
limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
// currently groupId is taken from the user so that groupId coming as a query parameter is not honored.
// As a improvement, we can check admin privileges of the user and honor groupId.
groupId = RestApiUtil.getLoggedInUserGroupId();
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
SubscriptionListDTO subscriptionListDTO;
if (!StringUtils.isEmpty(apiId)) {
// todo : FIX properly, need to done properly with backend side pagination.
// todo : getSubscribedIdentifiers() method should NOT be used. Appears to be too slow.
// This will fail with an authorization failed exception if user does not have permission to access the API
ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
if (apiTypeWrapper.isAPIProduct()) {
subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApiProduct().getId(), groupId, organization);
} else {
subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, apiTypeWrapper.getApi().getId(), groupId, organization);
}
// sort by application name
subscribedAPIList.addAll(subscriptions);
subscribedAPIList.sort(Comparator.comparing(o -> o.getApplication().getName()));
subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit, offset, organization);
SubscriptionMappingUtil.setPaginationParams(subscriptionListDTO, apiId, "", limit, offset, subscribedAPIList.size());
return Response.ok().entity(subscriptionListDTO).build();
} else if (!StringUtils.isEmpty(applicationId)) {
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application == null) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
return null;
}
if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
subscriptions = apiConsumer.getPaginatedSubscribedAPIsByApplication(application, offset, limit, organization);
subscribedAPIList.addAll(subscriptions);
subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit, offset, organization);
return Response.ok().entity(subscriptionListDTO).build();
} else {
// neither apiId nor applicationId is given
RestApiUtil.handleBadRequest("Either applicationId or apiId should be available", log);
return null;
}
} catch (APIManagementException e) {
if (RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, log);
} else if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else {
RestApiUtil.handleInternalServerError("Error while getting subscriptions of the user " + username, e, log);
}
}
return null;
}
use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class APIConsumerImpl method getAPIorAPIProductByUUIDWithoutPermissionCheck.
/**
* Used to retrieve API/API Products without performing the visibility permission checks
* @param uuid
* @param organization
* @return
* @throws APIManagementException
*/
private ApiTypeWrapper getAPIorAPIProductByUUIDWithoutPermissionCheck(String uuid, String organization) throws APIManagementException {
try {
Organization org = new Organization(organization);
DevPortalAPI devPortalApi = apiPersistenceInstance.getDevPortalAPI(org, uuid);
if (devPortalApi != null) {
if (APIConstants.API_PRODUCT.equalsIgnoreCase(devPortalApi.getType())) {
APIProduct apiProduct = APIMapper.INSTANCE.toApiProduct(devPortalApi);
apiProduct.setID(new APIProductIdentifier(devPortalApi.getProviderName(), devPortalApi.getApiName(), devPortalApi.getVersion()));
populateAPIProductInformation(uuid, organization, apiProduct);
return new ApiTypeWrapper(apiProduct);
} else {
API api = APIMapper.INSTANCE.toApi(devPortalApi);
populateDevPortalAPIInformation(uuid, organization, api);
populateDefaultVersion(api);
api = addTiersToAPI(api, organization);
return new ApiTypeWrapper(api);
}
} else {
String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
throw new APIMgtResourceNotFoundException(msg);
}
} catch (APIPersistenceException | OASPersistenceException | ParseException e) {
String msg = "Failed to get API";
throw new APIManagementException(msg, e);
}
}
use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class APIConsumerImpl method removeSubscription.
@Override
public void removeSubscription(Identifier identifier, String userId, int applicationId, String organization) throws APIManagementException {
APIIdentifier apiIdentifier = null;
APIProductIdentifier apiProdIdentifier = null;
if (identifier instanceof APIIdentifier) {
apiIdentifier = (APIIdentifier) identifier;
}
if (identifier instanceof APIProductIdentifier) {
apiProdIdentifier = (APIProductIdentifier) identifier;
}
String applicationName = apiMgtDAO.getApplicationNameFromId(applicationId);
try {
SubscriptionWorkflowDTO workflowDTO;
WorkflowExecutor createSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION);
WorkflowExecutor removeSubscriptionWFExecutor = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
String workflowExtRef = apiMgtDAO.getExternalWorkflowReferenceForSubscription(identifier, applicationId, organization);
// in a normal flow workflowExtRef is null when workflows are not enabled
if (workflowExtRef == null) {
workflowDTO = new SubscriptionWorkflowDTO();
} else {
workflowDTO = (SubscriptionWorkflowDTO) apiMgtDAO.retrieveWorkflow(workflowExtRef);
// set tiername to the workflowDTO only when workflows are enabled
SubscribedAPI subscription = apiMgtDAO.getSubscriptionById(Integer.parseInt(workflowDTO.getWorkflowReference()));
workflowDTO.setTierName(subscription.getTier().getName());
}
workflowDTO.setApiProvider(identifier.getProviderName());
API api = null;
APIProduct product = null;
String context = null;
ApiTypeWrapper wrapper;
if (apiIdentifier != null) {
// The API is retrieved without visibility permission check, since the subscribers should be allowed
// to delete already existing subscriptions made for restricted APIs
wrapper = getAPIorAPIProductByUUIDWithoutPermissionCheck(apiIdentifier.getUUID(), organization);
api = wrapper.getApi();
context = api.getContext();
} else if (apiProdIdentifier != null) {
// The API Product is retrieved without visibility permission check, since the subscribers should be
// allowe to delete already existing subscriptions made for restricted API Products
wrapper = getAPIorAPIProductByUUIDWithoutPermissionCheck(apiProdIdentifier.getUUID(), organization);
product = wrapper.getApiProduct();
context = product.getContext();
}
workflowDTO.setApiContext(context);
workflowDTO.setApiName(identifier.getName());
workflowDTO.setApiVersion(identifier.getVersion());
workflowDTO.setApplicationName(applicationName);
workflowDTO.setTenantDomain(tenantDomain);
workflowDTO.setTenantId(tenantId);
workflowDTO.setExternalWorkflowReference(workflowExtRef);
workflowDTO.setSubscriber(userId);
workflowDTO.setCallbackUrl(removeSubscriptionWFExecutor.getCallbackURL());
workflowDTO.setApplicationId(applicationId);
workflowDTO.setMetadata(WorkflowConstants.PayloadConstants.API_ID, String.valueOf(identifier.getId()));
String status = null;
if (apiIdentifier != null) {
status = apiMgtDAO.getSubscriptionStatus(apiIdentifier.getUUID(), applicationId);
} else if (apiProdIdentifier != null) {
status = apiMgtDAO.getSubscriptionStatus(apiProdIdentifier.getUUID(), applicationId);
}
if (APIConstants.SubscriptionStatus.ON_HOLD.equals(status)) {
try {
createSubscriptionWFExecutor.cleanUpPendingTask(workflowExtRef);
} catch (WorkflowException ex) {
// failed cleanup processes are ignored to prevent failing the deletion process
log.warn("Failed to clean pending subscription approval task");
}
}
// update attributes of the new remove workflow to be created
workflowDTO.setStatus(WorkflowStatus.CREATED);
workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
workflowDTO.setCreatedTime(System.currentTimeMillis());
workflowDTO.setExternalWorkflowReference(removeSubscriptionWFExecutor.generateUUID());
Tier tier = null;
if (api != null) {
Set<Tier> policies = api.getAvailableTiers();
Iterator<Tier> iterator = policies.iterator();
boolean isPolicyAllowed = false;
while (iterator.hasNext()) {
Tier policy = iterator.next();
if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
tier = policy;
}
}
} else if (product != null) {
Set<Tier> policies = product.getAvailableTiers();
Iterator<Tier> iterator = policies.iterator();
boolean isPolicyAllowed = false;
while (iterator.hasNext()) {
Tier policy = iterator.next();
if (policy.getName() != null && (policy.getName()).equals(workflowDTO.getTierName())) {
tier = policy;
}
}
}
if (api != null) {
// check whether monetization is enabled for API and tier plan is commercial
if (api.getMonetizationStatus() && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
removeSubscriptionWFExecutor.deleteMonetizedSubscription(workflowDTO, api);
} else {
removeSubscriptionWFExecutor.execute(workflowDTO);
}
} else if (product != null) {
// check whether monetization is enabled for API product and tier plan is commercial
if (product.getMonetizationStatus() && APIConstants.COMMERCIAL_TIER_PLAN.equals(tier.getTierPlan())) {
removeSubscriptionWFExecutor.deleteMonetizedSubscription(workflowDTO, product);
} else {
removeSubscriptionWFExecutor.execute(workflowDTO);
}
}
JSONObject subsLogObject = new JSONObject();
subsLogObject.put(APIConstants.AuditLogConstants.API_NAME, identifier.getName());
subsLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_ID, applicationId);
subsLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, applicationName);
APIUtil.logAuditMessage(APIConstants.AuditLogConstants.SUBSCRIPTION, subsLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
} catch (WorkflowException e) {
String errorMsg = "Could not execute Workflow, " + WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION + " for resource " + identifier.toString();
handleException(errorMsg, e);
}
if (log.isDebugEnabled()) {
String logMessage = "Subscription removed from app " + applicationName + " by " + userId + " For Id: " + identifier.toString();
log.debug(logMessage);
}
}
use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class APIUtil method checkPermission.
/**
* Checks whether the specified user has the specified permission.
*
* @param username A username
* @param permission A valid Carbon permission
* @throws APIManagementException If the user does not have the specified permission or if an error occurs
*/
public static void checkPermission(String username, String permission) throws APIManagementException {
if (username == null) {
throw new APIManagementException("Attempt to execute privileged operation as" + " the anonymous user");
}
if (isPermissionCheckDisabled()) {
log.debug("Permission verification is disabled by APIStore configuration");
return;
}
String tenantDomain = MultitenantUtils.getTenantDomain(username);
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
boolean authorized;
try {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
authorized = manager.isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission, CarbonConstants.UI_PERMISSION_ACTION);
} else {
// store), the user realm will be null.
if (ServiceReferenceHolder.getUserRealm() == null) {
ServiceReferenceHolder.setUserRealm((UserRealm) ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId));
}
authorized = AuthorizationManager.getInstance().isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission);
}
if (!authorized) {
throw new APIManagementException("User '" + username + "' does not have the " + "required permission: " + permission);
}
} catch (UserStoreException e) {
throw new APIManagementException("Error while checking the user:" + username + " authorized or not", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
use of org.wso2.carbon.user.api.Permission in project carbon-apimgt by wso2.
the class APIUtil method loadloadTenantAPIRXT.
/**
* Load the API RXT to the registry for tenants
*
* @param tenant
* @param tenantID
* @throws APIManagementException
*/
public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
UserRegistry registry = null;
try {
registry = registryService.getGovernanceSystemRegistry(tenantID);
} catch (RegistryException e) {
throw new APIManagementException("Error when create registry instance ", e);
}
String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
File file = new File(rxtDir);
FilenameFilter filenameFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// if the file extension is .rxt return true, else false
return name.endsWith(".rxt");
}
};
String[] rxtFilePaths = file.list(filenameFilter);
if (rxtFilePaths == null) {
throw new APIManagementException("rxt files not found in directory " + rxtDir);
}
for (String rxtPath : rxtFilePaths) {
String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
// This is "registry" is a governance registry instance, therefore calculate the relative path to governance.
String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
try {
// calculate resource path
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
resourcePath = authorizationManager.computePathOnMount(resourcePath);
org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
if (registry.resourceExists(govRelativePath)) {
// set anonymous user permission to RXTs
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
continue;
}
String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
Resource resource = registry.newResource();
resource.setContent(rxt.getBytes(Charset.defaultCharset()));
resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
registry.put(govRelativePath, resource);
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
} catch (UserStoreException e) {
throw new APIManagementException("Error while adding role permissions to API", e);
} catch (IOException e) {
String msg = "Failed to read rxt files";
throw new APIManagementException(msg, e);
} catch (RegistryException e) {
String msg = "Failed to add rxt to registry ";
throw new APIManagementException(msg, e);
}
}
}
Aggregations