Search in sources :

Example 51 with Roles

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

the class PublisherCommonUtils method prepareToCreateAPIByDTO.

/**
 * Prepares the API Model object to be created using the DTO object.
 *
 * @param body        APIDTO of the API
 * @param apiProvider API Provider
 * @param username    Username
 * @param organization  Organization Identifier
 * @return API object to be created
 * @throws APIManagementException Error while creating the API
 */
public static API prepareToCreateAPIByDTO(APIDTO body, APIProvider apiProvider, String username, String organization) throws APIManagementException {
    String context = body.getContext();
    // Make sure context starts with "/". ex: /pizza
    context = context.startsWith("/") ? context : ("/" + context);
    if (body.getAccessControlRoles() != null) {
        String errorMessage = PublisherCommonUtils.validateUserRoles(body.getAccessControlRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    if (body.getAdditionalProperties() != null) {
        String errorMessage = PublisherCommonUtils.validateAdditionalProperties(body.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, body.getName(), body.getVersion()));
        }
    }
    if (body.getContext() == null) {
        throw new APIManagementException("Parameter: \"context\" cannot be null", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    } else if (body.getContext().endsWith("/")) {
        throw new APIManagementException("Context cannot end with '/' character", ExceptionCodes.INVALID_CONTEXT);
    }
    if (apiProvider.isApiNameWithDifferentCaseExist(body.getName())) {
        throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists.", ExceptionCodes.from(ExceptionCodes.API_NAME_ALREADY_EXISTS, body.getName()));
    }
    if (body.getAuthorizationHeader() == null) {
        body.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
    }
    if (body.getAuthorizationHeader() == null) {
        body.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
    }
    if (body.getVisibility() == APIDTO.VisibilityEnum.RESTRICTED && body.getVisibleRoles().isEmpty()) {
        throw new APIManagementException("Valid roles should be added under 'visibleRoles' to restrict " + "the visibility", ExceptionCodes.USER_ROLES_CANNOT_BE_NULL);
    }
    if (body.getVisibleRoles() != null) {
        String errorMessage = PublisherCommonUtils.validateRoles(body.getVisibleRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    // Get all existing versions of  api been adding
    List<String> apiVersions = apiProvider.getApiVersionsMatchingApiNameAndOrganization(body.getName(), username, organization);
    if (apiVersions.size() > 0) {
        // If any previous version exists
        for (String version : apiVersions) {
            if (version.equalsIgnoreCase(body.getVersion())) {
                // If version already exists
                if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
                    throw new APIManagementException("Error occurred while " + "adding the API. A duplicate API already exists for " + context + " in the organization : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
                } else {
                    throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists with different context" + context + " in the organization" + " : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
                }
            }
        }
    } else {
        // If no any previous version exists
        if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
            throw new APIManagementException("Error occurred while adding the API. A duplicate API context already exists for " + context + " in the organization" + " : " + organization, ExceptionCodes.from(ExceptionCodes.API_CONTEXT_ALREADY_EXISTS, context));
        }
    }
    // Check if the user has admin permission before applying a different provider than the current user
    String provider = body.getProvider();
    if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
        if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
            }
            provider = username;
        } else {
            if (!APIUtil.isUserExist(provider)) {
                throw new APIManagementException("Specified provider " + provider + " not exist.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
            }
        }
    } else {
        // Set username in case provider is null or empty
        provider = username;
    }
    List<String> tiersFromDTO = body.getPolicies();
    // check whether the added API's tiers are all valid
    Set<Tier> definedTiers = apiProvider.getTiers();
    List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
    if (invalidTiers.size() > 0) {
        throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
    }
    APIPolicy apiPolicy = apiProvider.getAPIPolicy(username, body.getApiThrottlingPolicy());
    if (apiPolicy == null && body.getApiThrottlingPolicy() != null) {
        throw new APIManagementException("Specified policy " + body.getApiThrottlingPolicy() + " is invalid", ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
    }
    API apiToAdd = APIMappingUtil.fromDTOtoAPI(body, provider);
    // only allow CREATED as the stating state for the new api if not status is PROTOTYPED
    if (!APIConstants.PROTOTYPED.equals(apiToAdd.getStatus())) {
        apiToAdd.setStatus(APIConstants.CREATED);
    }
    if (!apiToAdd.isAdvertiseOnly() || StringUtils.isBlank(apiToAdd.getApiOwner())) {
        // we are setting the api owner as the logged in user until we support checking admin privileges and
        // assigning the owner as a different user
        apiToAdd.setApiOwner(provider);
    }
    if (body.getKeyManagers() instanceof List) {
        apiToAdd.setKeyManagers((List<String>) body.getKeyManagers());
    } else if (body.getKeyManagers() == null) {
        apiToAdd.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    } else {
        throw new APIManagementException("KeyManagers value need to be an array");
    }
    // Set default gatewayVendor
    if (body.getGatewayVendor() == null) {
        apiToAdd.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
    }
    apiToAdd.setOrganization(organization);
    return apiToAdd;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy)

Example 52 with Roles

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

the class SystemScopesMappingUtil method fromRoleScopeMapToRoleScopeDTOList.

/**
 * Converts api scope-role mapping to RoleScopeDTO List.
 *
 * @param scopeRoleMapping Map of a Role Scope  Mapping
 * @return RoleScopeDTO list
 */
private static List<ScopeDTO> fromRoleScopeMapToRoleScopeDTOList(Map<String, String> scopeRoleMapping) throws APIManagementException {
    List<ScopeDTO> scopeDTOs = new ArrayList<>(scopeRoleMapping.size());
    if (portalScopeList.isEmpty()) {
        synchronized (lock) {
            if (portalScopeList.isEmpty()) {
                portalScopeList = RestApiUtil.getScopesInfoFromAPIYamlDefinitions();
            }
        }
    }
    for (Map.Entry<String, List<String>> mapping : portalScopeList.entrySet()) {
        // openid scope doesn't need a role mapping
        if (APIConstants.OPEN_ID_SCOPE_NAME.equals(mapping.getKey())) {
            continue;
        }
        if (scopeRoleMapping.containsKey(mapping.getKey())) {
            ScopeDTO roleScopeDTO = new ScopeDTO();
            roleScopeDTO.setName(mapping.getKey());
            String roles = scopeRoleMapping.get(mapping.getKey());
            List<String> roleList = new ArrayList<String>(Arrays.asList((roles.replaceAll("\\s+", "")).split(",")));
            roleScopeDTO.setRoles(roleList);
            roleScopeDTO.setDescription(mapping.getValue().get(0));
            roleScopeDTO.setTag(mapping.getValue().get(1));
            scopeDTOs.add(roleScopeDTO);
        } else {
            log.warn("The scope " + mapping.getKey() + " does not exist in tenant.conf");
        }
    }
    return scopeDTOs;
}
Also used : ScopeDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ScopeDTO) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 53 with Roles

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

the class APIMappingUtil method getScopesFromSwagger.

/**
 * Extract scopes from the swagger.
 *
 * @param swagger swagger document
 * @return list of scopes
 * @throws APIManagementException throw if parsing exception occur
 */
private static List<ScopeDTO> getScopesFromSwagger(String swagger) throws APIManagementException {
    APIDefinition apiDefinition = OASParserUtil.getOASParser(swagger);
    Set<Scope> scopes = apiDefinition.getScopes(swagger);
    List<ScopeDTO> scopeDTOS = new ArrayList<>();
    for (Scope aScope : scopes) {
        ScopeDTO scopeDTO = new ScopeDTO();
        scopeDTO.setName(aScope.getKey());
        scopeDTO.setDisplayName(aScope.getName());
        scopeDTO.setDescription(aScope.getDescription());
        String roles = aScope.getRoles();
        if (roles == null || roles.isEmpty()) {
            scopeDTO.setBindings(Collections.emptyList());
        } else {
            scopeDTO.setBindings(Arrays.asList((roles).split(",")));
        }
        scopeDTOS.add(scopeDTO);
    }
    return scopeDTOS;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) ScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ScopeDTO) APIScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIScopeDTO) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) ArrayList(java.util.ArrayList)

Example 54 with Roles

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

the class SharedScopeMappingUtil method fromScopeToDTO.

/**
 * Converts Scope object into ScopeDTO object.
 *
 * @param scope Scope object
 * @return ScopeDTO object
 */
public static ScopeDTO fromScopeToDTO(Scope scope) {
    ScopeDTO scopeDTO = new ScopeDTO();
    scopeDTO.setName(scope.getKey());
    scopeDTO.setDisplayName(scope.getName());
    scopeDTO.setUsageCount(scope.getUsageCount());
    scopeDTO.setDescription(scope.getDescription());
    scopeDTO.setId(scope.getId());
    String roles = scope.getRoles();
    if (StringUtils.isEmpty(roles)) {
        scopeDTO.setBindings(Collections.emptyList());
    } else {
        scopeDTO.setBindings(Arrays.asList((roles).split(",")));
    }
    return scopeDTO;
}
Also used : ScopeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ScopeDTO)

Example 55 with Roles

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

the class ThrottlingPolicyMappingUtil method setTierPermissions.

/**
 * Fills the tier information on TierDTO
 *
 * @param throttlingPolicyDTO Object Containing throttling policy DTOs
 * @param throttlingPolicy    Throttling Policy object
 * @return ThrottlingPolicyDTO with permission info
 */
public static ThrottlingPolicyDTO setTierPermissions(ThrottlingPolicyDTO throttlingPolicyDTO, Tier throttlingPolicy) {
    ThrottlingPolicyPermissionInfoDTO tierPermission = new ThrottlingPolicyPermissionInfoDTO();
    // If no permission found for the tier, the default permission will be applied
    if (throttlingPolicy.getTierPermission() == null || throttlingPolicy.getTierPermission().getPermissionType() == null) {
        tierPermission.setType(ThrottlingPolicyPermissionInfoDTO.TypeEnum.valueOf("ALLOW"));
        List<String> roles = new ArrayList<>();
        roles.add("Internal/everyone");
        tierPermission.setRoles(roles);
    } else {
        String permissionType = throttlingPolicy.getTierPermission().getPermissionType();
        tierPermission.setType(ThrottlingPolicyPermissionInfoDTO.TypeEnum.valueOf(permissionType.toUpperCase()));
        tierPermission.setRoles(Arrays.asList(throttlingPolicy.getTierPermission().getRoles()));
    }
    throttlingPolicyDTO.setThrottlingPolicyPermissions(tierPermission);
    return throttlingPolicyDTO;
}
Also used : ArrayList(java.util.ArrayList) ThrottlingPolicyPermissionInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ThrottlingPolicyPermissionInfoDTO)

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