Search in sources :

Example 6 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class APIPublisherImpl method searchAPIs.

/**
 * @param limit  Limit
 * @param offset Offset
 * @param query  Search query
 * @return List of APIS.
 * @throws APIManagementException If failed to formatApiSearch APIs.
 */
@Override
public List<API> searchAPIs(Integer limit, Integer offset, String query) throws APIManagementException {
    List<API> apiResults;
    String user = getUsername();
    Set<String> roles = new HashSet<>();
    try {
        // TODO: Need to validate users roles against results returned
        if (!"admin".equals(user)) {
            // Whenever call identity provider should convert pseudo name to actual name
            String userId = getIdentityProvider().getIdOfUser(user);
            roles = new HashSet<>(getIdentityProvider().getRoleIdsOfUser(userId));
        }
        if (query != null && !query.isEmpty()) {
            String[] attributes = query.split(ATTRIBUTE_DELIMITER);
            Map<String, String> attributeMap = new HashMap<>();
            boolean isFullTextSearch = false;
            String searchAttribute, searchValue;
            if (!query.contains(KEY_VALUE_DELIMITER)) {
                isFullTextSearch = true;
            } else {
                log.debug("Search query: " + query);
                for (String attribute : attributes) {
                    searchAttribute = attribute.split(KEY_VALUE_DELIMITER)[0];
                    searchValue = attribute.split(KEY_VALUE_DELIMITER)[1];
                    log.debug(searchAttribute + KEY_VALUE_DELIMITER + searchValue);
                    attributeMap.put(searchAttribute, searchValue);
                }
            }
            if (isFullTextSearch) {
                apiResults = getApiDAO().searchAPIs(roles, user, query, offset, limit);
            } else {
                log.debug("Attributes:", attributeMap.toString());
                apiResults = getApiDAO().attributeSearchAPIs(roles, user, attributeMap, offset, limit);
            }
        } else {
            apiResults = getApiDAO().getAPIs(roles, user);
        }
        return apiResults;
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while Searching the API with query " + query;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (IdentityProviderException e) {
        String errorMsg = "Error occurred while calling SCIM endpoint to retrieve user " + user + "'s information";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) HashMap(java.util.HashMap) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) HashSet(java.util.HashSet)

Example 7 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class APIPublisherImpl method addAPI.

/**
 * Adds a new API to the system
 *
 * @param apiBuilder API model object
 * @return UUID of the added API.
 * @throws APIManagementException if failed to add API
 */
@Override
public String addAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    API createdAPI;
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    if (StringUtils.isEmpty(apiBuilder.getId())) {
        apiBuilder.id(UUID.randomUUID().toString());
    }
    LocalDateTime localDateTime = LocalDateTime.now();
    apiBuilder.createdTime(localDateTime);
    apiBuilder.lastUpdatedTime(localDateTime);
    apiBuilder.createdBy(getUsername());
    apiBuilder.updatedBy(getUsername());
    if (apiBuilder.getLabels().isEmpty()) {
        List<String> labelSet = new ArrayList<>();
        labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_GATEWAY));
        labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_STORE));
        apiBuilder.labels(labelSet);
    }
    Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
    validateEndpoints(apiEndpointMap, false);
    try {
        if (!isApiNameExist(apiBuilder.getName()) && !isContextExist(apiBuilder.getContext())) {
            LifecycleState lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
            apiBuilder.associateLifecycle(lifecycleState);
            createUriTemplateList(apiBuilder, false);
            List<UriTemplate> list = new ArrayList<>(apiBuilder.getUriTemplates().values());
            List<TemplateBuilderDTO> resourceList = new ArrayList<>();
            validateApiPolicy(apiBuilder.getApiPolicy());
            validateSubscriptionPolicies(apiBuilder);
            for (UriTemplate uriTemplate : list) {
                TemplateBuilderDTO dto = new TemplateBuilderDTO();
                dto.setTemplateId(uriTemplate.getTemplateId());
                dto.setUriTemplate(uriTemplate.getUriTemplate());
                dto.setHttpVerb(uriTemplate.getHttpVerb());
                Map<String, Endpoint> map = uriTemplate.getEndpoint();
                if (map.containsKey(APIMgtConstants.PRODUCTION_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.PRODUCTION_ENDPOINT);
                    dto.setProductionEndpoint(endpoint);
                }
                if (map.containsKey(APIMgtConstants.SANDBOX_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.SANDBOX_ENDPOINT);
                    dto.setSandboxEndpoint(endpoint);
                }
                resourceList.add(dto);
            }
            GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
            APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
            gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
            String gatewayConfig = gatewaySourceGenerator.getConfigStringFromTemplate(resourceList);
            if (log.isDebugEnabled()) {
                log.debug("API " + apiBuilder.getName() + "gateway config: " + gatewayConfig);
            }
            apiBuilder.gatewayConfig(gatewayConfig);
            if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
                apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
            }
            if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                Map<String, Integer> roleNamePermissionList;
                roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                apiBuilder.permissionMap(roleNamePermissionList);
            }
            createdAPI = apiBuilder.build();
            APIUtils.validate(createdAPI);
            // Add API to gateway
            gateway.addAPI(createdAPI);
            if (log.isDebugEnabled()) {
                log.debug("API : " + apiBuilder.getName() + " has been identifier published to gateway");
            }
            Set<String> apiRoleList;
            // if the API has role based visibility, add the API with role checking
            if (API.Visibility.PUBLIC == createdAPI.getVisibility()) {
                getApiDAO().addAPI(createdAPI);
            } else if (API.Visibility.RESTRICTED == createdAPI.getVisibility()) {
                // get all the roles in the system
                Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                // get the roles needed to be associated with the API
                apiRoleList = createdAPI.getVisibleRoles();
                if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                    getApiDAO().addAPI(createdAPI);
                }
            }
            APIUtils.logDebug("API " + createdAPI.getName() + "-" + createdAPI.getVersion() + " was created " + "successfully.", log);
            // 'API_M Functions' related code
            // Create a payload with event specific details
            Map<String, String> eventPayload = new HashMap<>();
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, createdAPI.getId());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, createdAPI.getName());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, createdAPI.getVersion());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, createdAPI.getDescription());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, createdAPI.getContext());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, createdAPI.getLifeCycleStatus());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_PERMISSION, createdAPI.getApiPermission());
            // This will notify all the EventObservers(Asynchronous)
            ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_CREATION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
            ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
        } else {
            String message = "Duplicate API already Exist with name/Context " + apiBuilder.getName();
            log.error(message);
            throw new APIManagementException(message, ExceptionCodes.API_ALREADY_EXISTS);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while creating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException | ParseException e) {
        String errorMsg = "Error occurred while Associating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (APITemplateException e) {
        String message = "Error generating API configuration for API " + apiBuilder.getName();
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.TEMPLATE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while adding API - " + apiBuilder.getName() + " to gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
    return apiBuilder.getId();
}
Also used : LocalDateTime(java.time.LocalDateTime) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) TemplateBuilderDTO(org.wso2.carbon.apimgt.core.template.dto.TemplateBuilderDTO) API(org.wso2.carbon.apimgt.core.models.API) ParseException(org.json.simple.parser.ParseException) APITemplateException(org.wso2.carbon.apimgt.core.template.APITemplateException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 8 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class ApiDAOImplIT method testGetAPIsWhenUserRolesInAPIPermissionsWithoutREAD.

@Test(description = "Tests getting the APIs when the user roles are contained in the API permission list " + "but without READ permissions")
public void testGetAPIsWhenUserRolesInAPIPermissionsWithoutREAD() 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());
    Map map = new HashMap();
    map.put(SampleTestObjectCreator.DEVELOPER_ROLE_ID, 0);
    API.APIBuilder builder = SampleTestObjectCreator.createDefaultAPI().permissionMap(map);
    API api1 = builder.build();
    testAddGetEndpoint();
    apiDAO.addAPI(api1);
    apiList = apiDAO.getAPIs(rolesOfUser, ALTERNATIVE_USER);
    // Since the API has the role ID of the user but without READ permissions, it is not visible to this user
    Assert.assertTrue(apiList.size() == 0);
}
Also used : HashMap(java.util.HashMap) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 9 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class ApiDAOImplIT method testAttributeSearchAPIsStore.

@Test
public void testAttributeSearchAPIsStore() throws Exception {
    // Add few APIs with different attributes.
    List<String> apiIDList = createAPIsAndGetIDsOfAddedAPIs();
    List<String> userRoles = new ArrayList<>();
    Map<String, String> attributeMap = new HashMap<>();
    String[] expectedAPINames;
    // Asserting results for different search queries
    // Attribute search for "provider", for "admin" role
    userRoles.add(ADMIN);
    attributeMap.put("provider", "a");
    expectedAPINames = new String[] { "PublicAPI", "AdminManagerAPI" };
    Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
    userRoles.clear();
    attributeMap.clear();
    // Attribute search for "version", for "manager" role
    userRoles.add(MANAGER_ROLE);
    attributeMap.put("version", "2.3");
    expectedAPINames = new String[] { "PublicAPI", "ManagerOnlyAPI" };
    Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
    userRoles.clear();
    attributeMap.clear();
    // Attribute search for "context", for "manager", "employee" and "customer" roles
    userRoles.add(MANAGER_ROLE);
    userRoles.add(EMPLOYEE_ROLE);
    userRoles.add(CUSTOMER_ROLE);
    attributeMap.put("context", "Man");
    expectedAPINames = new String[] { "ManagerOnlyAPI", "AdminManagerAPI" };
    Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
    userRoles.clear();
    attributeMap.clear();
    // Attribute search for "description", for "admin" role
    userRoles.add(ADMIN);
    attributeMap.put("description", "Admin and manager");
    expectedAPINames = new String[] { "AdminManagerAPI" };
    Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
    userRoles.clear();
    attributeMap.clear();
    // Attribute search for "tags", for "manager", "employee" and "customer" roles
    userRoles.add(MANAGER_ROLE);
    userRoles.add(EMPLOYEE_ROLE);
    userRoles.add(CUSTOMER_ROLE);
    attributeMap.put("tags", "E");
    expectedAPINames = new String[] { "ManagerOnlyAPI", "NonAdminAPI" };
    Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
    userRoles.clear();
    attributeMap.clear();
    // Attribute search for "subcontext", for "manager", "employee" and "customer" roles
    userRoles.add(MANAGER_ROLE);
    userRoles.add(EMPLOYEE_ROLE);
    userRoles.add(CUSTOMER_ROLE);
    attributeMap.put("subcontext", "C");
    expectedAPINames = new String[] { "AdminManagerAPI", "EmployeeAPI", "NonAdminAPI" };
    Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
    userRoles.clear();
    attributeMap.clear();
    // cleanup added APIs
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    for (String apiID : apiIDList) {
        apiDAO.deleteAPI(apiID);
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Test(org.testng.annotations.Test)

Example 10 with Roles

use of org.wso2.carbon.identity.api.server.idp.v1.model.Roles in project carbon-apimgt by wso2.

the class ApiDAOImplIT method testGetAPIsWithUserRoles.

@Test(description = "Tests getting the APIs when the user has roles assigned")
public void testGetAPIsWithUserRoles() throws Exception {
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    Set<String> rolesOfUser = new HashSet<>();
    rolesOfUser.add(SampleTestObjectCreator.ADMIN_ROLE_ID);
    List<API> apiList = apiDAO.getAPIs(rolesOfUser, ADMIN);
    Assert.assertTrue(apiList.isEmpty());
    API.APIBuilder builder = SampleTestObjectCreator.createDefaultAPI();
    API api1 = builder.build();
    testAddGetEndpoint();
    apiDAO.addAPI(api1);
    builder = SampleTestObjectCreator.createAlternativeAPI();
    API api2 = builder.build();
    apiDAO.addAPI(api2);
    apiList = apiDAO.getAPIs(rolesOfUser, ADMIN);
    List<API> expectedAPIs = new ArrayList<>();
    expectedAPIs.add(SampleTestObjectCreator.copyAPISummary(api1));
    expectedAPIs.add(SampleTestObjectCreator.copyAPISummary(api2));
    Assert.assertTrue(apiList.size() == 2);
    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)

Aggregations

ArrayList (java.util.ArrayList)72 HashMap (java.util.HashMap)60 Test (org.testng.annotations.Test)36 UserStoreException (org.wso2.carbon.user.api.UserStoreException)36 SQLException (java.sql.SQLException)27 HashSet (java.util.HashSet)26 Map (java.util.Map)25 Connection (java.sql.Connection)23 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)23 PreparedStatement (java.sql.PreparedStatement)21 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)20 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)18 JSONObject (org.json.simple.JSONObject)17 UserStoreException (org.wso2.carbon.user.core.UserStoreException)17 RoleBasicInfo (org.wso2.carbon.identity.role.mgt.core.RoleBasicInfo)16 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)16 RealmService (org.wso2.carbon.user.core.service.RealmService)15 API (org.wso2.carbon.apimgt.core.models.API)14 RoleMapping (org.wso2.carbon.identity.application.common.model.RoleMapping)14 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)14