Search in sources :

Example 56 with Permission

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

the class ApplicationsApiServiceImplTestCase method testApplicationsApplicationIdPut.

@Test
public void testApplicationsApplicationIdPut() throws APIManagementException, NotFoundException {
    TestUtil.printTestMethodName();
    String applicationId = UUID.randomUUID().toString();
    String accessToken = UUID.randomUUID().toString();
    String clientID = UUID.randomUUID().toString();
    String clientSecret = UUID.randomUUID().toString();
    ApplicationsApiServiceImpl applicationsApiService = new ApplicationsApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStoreImpl.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    ApplicationTokenDTO applicationTokenDTO = new ApplicationTokenDTO();
    applicationTokenDTO.setAccessToken(accessToken);
    applicationTokenDTO.setTokenScopes("SCOPE1");
    applicationTokenDTO.setValidityTime((long) 100000);
    List<String> grantTypes = new ArrayList<>();
    grantTypes.add("password");
    grantTypes.add("jwt");
    ApplicationKeysDTO applicationKeysDTO = new ApplicationKeysDTO();
    applicationKeysDTO.setConsumerKey(clientID);
    applicationKeysDTO.setConsumerSecret(clientSecret);
    applicationKeysDTO.setKeyType(ApplicationKeysDTO.KeyTypeEnum.PRODUCTION);
    applicationKeysDTO.setCallbackUrl(null);
    applicationKeysDTO.setSupportedGrantTypes(grantTypes);
    List<ApplicationKeysDTO> applicationKeysDTOList = new ArrayList<>();
    applicationKeysDTOList.add(applicationKeysDTO);
    ApplicationDTO applicationDTO = new ApplicationDTO();
    applicationDTO.setApplicationId(applicationId);
    applicationDTO.setDescription("sample application");
    applicationDTO.setName("app1");
    applicationDTO.setSubscriber("subscriber");
    applicationDTO.setPermission("permission");
    applicationDTO.setLifeCycleStatus("APPROVED");
    applicationDTO.setThrottlingTier("UNLIMITED");
    applicationDTO.setToken(applicationTokenDTO);
    applicationDTO.setKeys(applicationKeysDTOList);
    WorkflowResponse workflowResponse = new GeneralWorkflowResponse();
    workflowResponse.setWorkflowStatus(WorkflowStatus.APPROVED);
    Mockito.when(apiStore.getApplication(applicationId, USER)).thenReturn(getSampleApplication(applicationId));
    Mockito.when(apiStore.updateApplication(applicationId, getSampleApplication(applicationId))).thenReturn(workflowResponse);
    Mockito.when(apiStore.getApplication(applicationId, USER)).thenReturn(getSampleApplication(applicationId));
    Response response = applicationsApiService.applicationsApplicationIdPut(applicationId, applicationDTO, null, null, request);
    Assert.assertEquals(200, response.getStatus());
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationDTO) ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenDTO) Request(org.wso2.msf4j.Request) ArrayList(java.util.ArrayList) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) Response(javax.ws.rs.core.Response) ApplicationKeysDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationKeysDTO) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 57 with Permission

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

the class ApiDAOImpl method getAPIs.

@Override
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public List<API> getAPIs(Set<String> roles, String user) throws APIMgtDAOException {
    int roleCount = roles.size();
    final String query;
    if (roleCount > 0) {
        query = API_SUMMARY_SELECT + " LEFT JOIN AM_API_GROUP_PERMISSION PERMISSION ON UUID = API_ID WHERE" + " API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = '" + ApiType.STANDARD.toString() + "') AND (((PERMISSION.GROUP_ID IN (" + DAOUtil.getParameterString(roles.size()) + "))" + " AND PERMISSION.PERMISSION >= " + APIMgtConstants.Permission.READ_PERMISSION + ") OR " + "(PROVIDER = ?) OR (PERMISSION.GROUP_ID IS NULL))";
    } else {
        query = API_SUMMARY_SELECT + " LEFT JOIN AM_API_GROUP_PERMISSION PERMISSION ON UUID = API_ID WHERE" + " API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = '" + ApiType.STANDARD.toString() + "') AND ((PROVIDER = ?) OR (PERMISSION.GROUP_ID IS NULL))";
    }
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        int index = 0;
        if (roleCount > 0) {
            for (String role : roles) {
                statement.setString(++index, role);
            }
        }
        statement.setString(++index, user);
        return constructAPISummaryList(connection, statement);
    } catch (SQLException e) {
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + "getting APIs", e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 58 with Permission

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

the class APIPublisherImpl method getAPIbyUUID.

@Override
public API getAPIbyUUID(String uuid) throws APIManagementException {
    API api = null;
    try {
        api = super.getAPIbyUUID(uuid);
        if (api != null) {
            api.setUserSpecificApiPermissions(getAPIPermissionsOfLoggedInUser(getUsername(), api));
            String permissionString = api.getApiPermission();
            if (!StringUtils.isEmpty(permissionString)) {
                api.setApiPermission(replaceGroupIdWithName(permissionString));
            }
            if (!getScopesForApi(uuid).isEmpty()) {
                String swagger = getApiSwaggerDefinition(uuid);
                List<String> globalScopes = new APIDefinitionFromSwagger20().getGlobalAssignedScopes(swagger);
                List<APIResource> apiResourceList = new APIDefinitionFromSwagger20().parseSwaggerAPIResources(new StringBuilder(swagger));
                api.setScopes(globalScopes);
                for (APIResource apiResource : apiResourceList) {
                    if (apiResource.getUriTemplate().getScopes().isEmpty()) {
                        UriTemplate retrievedUriTemplateFromApi = api.getUriTemplates().get(apiResource.getUriTemplate().getTemplateId());
                        if (retrievedUriTemplateFromApi != null) {
                            UriTemplate.UriTemplateBuilder uriTemplate = new UriTemplate.UriTemplateBuilder(retrievedUriTemplateFromApi);
                            uriTemplate.scopes(apiResource.getScope());
                            api.getUriTemplates().replace(apiResource.getUriTemplate().getTemplateId(), uriTemplate.build());
                        }
                    }
                }
            }
        }
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json string for API " + api.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.JSON_PARSE_ERROR);
    }
    return api;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIResource(org.wso2.carbon.apimgt.core.models.APIResource) API(org.wso2.carbon.apimgt.core.models.API) ParseException(org.json.simple.parser.ParseException) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate)

Example 59 with Permission

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

the class ApiDAOImplIT method testGetAPIsWhenUserRolesInAPIPermissions.

@Test(description = "Tests getting the APIs when the user roles are contained in the API permission list")
public void testGetAPIsWhenUserRolesInAPIPermissions() throws Exception {
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    Set<String> rolesOfUser = new HashSet<>();
    rolesOfUser.add(SampleTestObjectCreator.DEVELOPER_ROLE_ID);
    // This user is not the provider of the API
    List<API> apiList = apiDAO.getAPIs(rolesOfUser, ALTERNATIVE_USER);
    Assert.assertTrue(apiList.isEmpty());
    API.APIBuilder builder = SampleTestObjectCreator.createDefaultAPI();
    API api1 = builder.build();
    testAddGetEndpoint();
    apiDAO.addAPI(api1);
    apiList = apiDAO.getAPIs(rolesOfUser, ALTERNATIVE_USER);
    List<API> expectedAPIs = new ArrayList<>();
    expectedAPIs.add(SampleTestObjectCreator.copyAPISummary(api1));
    // Since the API has the role ID of the user with READ permissions, it is visible to this user
    Assert.assertTrue(apiList.size() == 1);
    Assert.assertTrue(APIUtils.isListsEqualIgnoreOrder(apiList, expectedAPIs, new APIComparator()), TestUtil.printDiff(apiList, expectedAPIs));
}
Also used : ArrayList(java.util.ArrayList) APIComparator(org.wso2.carbon.apimgt.core.util.APIComparator) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 60 with Permission

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

the class APIStoreImplTestCase method testAddApplicationPermissionStringInvalid.

@Test(description = "Add an application with invalid permission String")
public void testAddApplicationPermissionStringInvalid() throws APIManagementException {
    ApplicationDAO applicationDAO = Mockito.mock(ApplicationDAO.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Policy policy = Mockito.mock(Policy.class);
    WorkflowDAO workflowDAO = Mockito.mock(WorkflowDAO.class);
    APIGateway apiGateway = Mockito.mock(APIGateway.class);
    APIStore apiStore = getApiStoreImpl(applicationDAO, policyDAO, workflowDAO, apiGateway);
    Application application = new Application(APP_NAME, USER_NAME);
    application.setPolicy(new ApplicationPolicy(TIER));
    application.setPermissionString("[{\"groupId\": \"testGroup\",\"permission\":[\"TESTREAD\",\"TESTUPDATE\"]}]");
    Mockito.when(applicationDAO.isApplicationNameExists(APP_NAME)).thenReturn(false);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application, TIER)).thenReturn(policy);
    ApplicationCreationResponse applicationResponse = apiStore.addApplication(application);
    String applicationUuid = applicationResponse.getApplicationUUID();
    Assert.assertNotNull(applicationUuid);
    Mockito.verify(applicationDAO, Mockito.times(1)).addApplication(application);
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) WorkflowDAO(org.wso2.carbon.apimgt.core.dao.WorkflowDAO) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ApplicationDAO(org.wso2.carbon.apimgt.core.dao.ApplicationDAO) Application(org.wso2.carbon.apimgt.core.models.Application) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)29 HashSet (java.util.HashSet)18 HashMap (java.util.HashMap)17 ArrayList (java.util.ArrayList)16 Test (org.testng.annotations.Test)16 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)16 Test (org.junit.Test)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 API (org.wso2.carbon.apimgt.core.models.API)15 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)15 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)15 UserStoreException (org.wso2.carbon.user.api.UserStoreException)13 Map (java.util.Map)12 Resource (org.wso2.carbon.registry.core.Resource)12 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)12 API (org.wso2.carbon.apimgt.api.model.API)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)9 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)9 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)8