Search in sources :

Example 11 with Roles

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

the class ApiDAOImplIT method testGetAPIsByStatusStore.

@Test
public void testGetAPIsByStatusStore() throws Exception {
    // Add few APIs with different attributes.
    List<String> apiIDList = createAPIsAndGetIDsOfAddedAPIs();
    Set<String> userRoles = new HashSet<>();
    List<String> statuses = new ArrayList<>();
    statuses.add(APIStatus.PUBLISHED.getStatus());
    statuses.add(APIStatus.PROTOTYPED.getStatus());
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    String[] expectedAPINames;
    List<API> apiResults;
    // Asserting results for different search queries
    // Role based API retrieval for a user with "admin" role
    userRoles.add(ADMIN);
    apiResults = apiDAO.getAPIsByStatus(userRoles, statuses, new ArrayList<>());
    List<String> resultAPINameList = new ArrayList<>();
    for (API api : apiResults) {
        resultAPINameList.add(api.getName());
    }
    expectedAPINames = new String[] { "PublicAPI", "AdminManagerAPI" };
    Assert.assertTrue(resultAPINameList.containsAll(Arrays.asList(expectedAPINames)) && Arrays.asList(expectedAPINames).containsAll(resultAPINameList));
    userRoles.clear();
    apiResults.clear();
    resultAPINameList.clear();
    // Role based API retrieval for a user with "manager" role
    userRoles.add(MANAGER_ROLE);
    apiResults = apiDAO.getAPIsByStatus(userRoles, statuses, new ArrayList<>());
    for (API api : apiResults) {
        resultAPINameList.add(api.getName());
    }
    expectedAPINames = new String[] { "PublicAPI", "ManagerOnlyAPI", "AdminManagerAPI", "NonAdminAPI" };
    Assert.assertTrue(resultAPINameList.containsAll(Arrays.asList(expectedAPINames)) && Arrays.asList(expectedAPINames).containsAll(resultAPINameList));
    userRoles.clear();
    apiResults.clear();
    resultAPINameList.clear();
    // Role based API retrieval for a user with "manager", "employee" and "customer" roles
    userRoles.add(MANAGER_ROLE);
    userRoles.add(EMPLOYEE_ROLE);
    userRoles.add(CUSTOMER_ROLE);
    apiResults = apiDAO.getAPIsByStatus(userRoles, statuses, new ArrayList<>());
    for (API api : apiResults) {
        resultAPINameList.add(api.getName());
    }
    expectedAPINames = new String[] { "PublicAPI", "ManagerOnlyAPI", "AdminManagerAPI", "EmployeeAPI", "NonAdminAPI" };
    Assert.assertTrue(resultAPINameList.containsAll(Arrays.asList(expectedAPINames)) && Arrays.asList(expectedAPINames).containsAll(resultAPINameList));
    userRoles.clear();
    apiResults.clear();
    resultAPINameList.clear();
}
Also used : ArrayList(java.util.ArrayList) 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 12 with Roles

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

the class ApiDAOImplIT method testAttributeSearchAPIs.

@Test(description = "Retrieve summary of paginated data of all available APIs that match the given search criteria")
public void testAttributeSearchAPIs() throws Exception {
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    testAddGetEndpoint();
    API api = SampleTestObjectCreator.createDefaultAPI().build();
    apiDAO.addAPI(api);
    Set<String> roles = new HashSet<>();
    Map<String, String> attributeMap = new HashMap<>();
    attributeMap.put("name", api.getName());
    List<API> apiList = apiDAO.attributeSearchAPIs(roles, api.getProvider(), attributeMap, 0, 2);
    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) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 13 with Roles

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

the class APIPublisherImpl method replaceGroupNamesWithId.

/**
 * This method replaces the groupId field's value to the role id instead of the name passed by the user
 *
 * @param permissionString - the permission json string which contains role names in groupId field
 * @return permission string with replaced groupId
 * @throws ParseException         - if there is an error parsing the json string
 * @throws APIManagementException - if there is an error getting the IdentityProvider instance
 */
private String replaceGroupNamesWithId(String permissionString) throws ParseException, APIManagementException {
    JSONArray updatedPermissionArray = new JSONArray();
    JSONParser jsonParser = new JSONParser();
    JSONArray originalPermissionArray = (JSONArray) jsonParser.parse(permissionString);
    try {
        for (Object permissionObj : originalPermissionArray) {
            JSONObject jsonObject = (JSONObject) permissionObj;
            String groupName = (String) jsonObject.get(APIMgtConstants.Permission.GROUP_ID);
            String groupId = getIdentityProvider().getRoleId(groupName);
            JSONObject updatedPermissionJsonObj = new JSONObject();
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.GROUP_ID, groupId);
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.PERMISSION, jsonObject.get(APIMgtConstants.Permission.PERMISSION));
            updatedPermissionArray.add(updatedPermissionJsonObj);
        }
    } catch (IdentityProviderException e) {
        String errorMessage = "There are invalid roles in the permission string";
        log.error(errorMessage, e);
        throw new APIManagementException(errorMessage, e, ExceptionCodes.UNSUPPORTED_ROLE);
    }
    return updatedPermissionArray.toJSONString();
}
Also used : JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException)

Example 14 with Roles

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

the class APIPublisherImpl method updateAPI.

/**
 * Updates design and implementation of an existing API. This method must not be used to change API status.
 * Implementations should throw an exceptions when such attempts are made. All life cycle state changes
 * should be carried out using the changeAPIStatus method of this interface.
 *
 * @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
 * @throws APIManagementException if failed to update API
 */
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    apiBuilder.updatedBy(getUsername());
    try {
        API originalAPI = getAPIbyUUID(apiBuilder.getId());
        if (originalAPI != null) {
            // Checks whether the logged in user has the "UPDATE" permission for the API
            verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
            apiBuilder.createdTime(originalAPI.getCreatedTime());
            // workflow status is an internal property and shouldn't be allowed to update externally
            apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
            if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
                if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                    apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
                    Map<String, Integer> roleNamePermissionList;
                    roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                    apiBuilder.permissionMap(roleNamePermissionList);
                }
                Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
                validateEndpoints(apiEndpointMap, true);
                validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
                createUriTemplateList(apiBuilder, true);
                validateApiPolicy(apiBuilder.getApiPolicy());
                validateSubscriptionPolicies(apiBuilder);
                String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
                String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
                GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
                APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
                gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
                String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
                API api = apiBuilder.build();
                // Add API to gateway
                gateway.updateAPI(api);
                if (log.isDebugEnabled()) {
                    log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
                }
                if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
                    if (!checkIfAPIContextExists(api.getContext())) {
                        // if the API has public visibility, update the API without any role checking
                        if (API.Visibility.PUBLIC == api.getVisibility()) {
                            getApiDAO().updateAPI(api.getId(), api);
                        } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                            // get all the roles in the system
                            Set<String> availableRoles = APIUtils.getAllAvailableRoles();
                            // get the roles needed to be associated with the API
                            Set<String> apiRoleList = api.getVisibleRoles();
                            // if the API has role based visibility, update the API with role checking
                            if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
                                getApiDAO().updateAPI(api.getId(), api);
                            }
                        }
                        getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                        getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                    } else {
                        throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
                    }
                } else {
                    // if the API has public visibility, update the API without any role checking
                    if (API.Visibility.PUBLIC == api.getVisibility()) {
                        getApiDAO().updateAPI(api.getId(), api);
                    } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                        // get all the roles in the system
                        Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                        // get the roles needed to be associated with the API
                        Set<String> apiRoleList = api.getVisibleRoles();
                        // if the API has role based visibility, update the API with role checking
                        if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                            getApiDAO().updateAPI(api.getId(), api);
                        }
                    }
                    getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                    getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                }
                if (log.isDebugEnabled()) {
                    log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
                    // 'API_M Functions' related code
                    // Create a payload with event specific details
                    Map<String, String> eventPayload = new HashMap<>();
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
                    // This will notify all the EventObservers(Asynchronous)
                    ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
                    ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
                }
            } else {
                APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
            }
        } else {
            log.error("Couldn't found API with ID " + apiBuilder.getId());
            throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ParseException(org.json.simple.parser.ParseException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 15 with Roles

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

the class DefaultIdentityProviderImpl method getRoleNamesOfUser.

@Override
public List<String> getRoleNamesOfUser(String userId) throws IdentityProviderException {
    List<String> roleNames = new ArrayList<>();
    Response response = scimServiceStub.getUser(userId);
    if (response == null) {
        String errorMessage = "Error occurred while retrieving user with Id " + userId + ". Error : Response is null.";
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    try {
        if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
            SCIMUser scimUser = (SCIMUser) new GsonDecoder().decode(response, SCIMUser.class);
            if (scimUser != null) {
                List<SCIMUser.SCIMUserGroups> roles = scimUser.getGroups();
                if (roles != null) {
                    roles.forEach(role -> roleNames.add(role.getDisplay()));
                    String message = "Role names of user " + scimUser.getName() + " are successfully retrieved as " + StringUtils.join(roleNames, ", ") + ".";
                    if (log.isDebugEnabled()) {
                        log.debug(message);
                    }
                }
            } else {
                String errorMessage = "Error occurred while retrieving user with user Id " + userId + " from SCIM endpoint. " + "Response body is null or empty.";
                log.error(errorMessage);
                throw new IdentityProviderException("Error occurred while retrieving user with user Id " + userId + " from SCIM endpoint. " + "Response body is null or empty.", ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
            }
        } else {
            String errorMessage = "Error occurred while retrieving role names of user with Id " + userId + ". Error : " + getErrorMessage(response);
            log.error(errorMessage);
            throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
        }
    } catch (IOException e) {
        String errorMessage = "Error occurred while parsing response from SCIM endpoint.";
        log.error(errorMessage);
        throw new IdentityProviderException("Error occurred while parsing response from SCIM endpoint for ", e, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    return roleNames;
}
Also used : Response(feign.Response) SCIMUser(org.wso2.carbon.apimgt.core.auth.dto.SCIMUser) ArrayList(java.util.ArrayList) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException)

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