Search in sources :

Example 21 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class GraphQLSchemaDefinition method buildSchemaWithAdditionalInfo.

/**
 * build schema with additional info
 *
 * @param api                   api object
 * @param graphqlComplexityInfo
 * @return schemaDefinition
 */
public String buildSchemaWithAdditionalInfo(API api, GraphqlComplexityInfo graphqlComplexityInfo) {
    Swagger swagger = null;
    Map<String, String> scopeRoleMap = new HashMap<>();
    Map<String, String> operationScopeMap = new HashMap<>();
    Map<String, String> operationAuthSchemeMap = new HashMap<>();
    Map<String, String> operationThrottlingMap = new HashMap<>();
    String operationScopeType;
    StringBuilder schemaDefinitionBuilder = new StringBuilder(api.getGraphQLSchema());
    schemaDefinitionBuilder.append("\n");
    StringBuilder operationScopeMappingBuilder = new StringBuilder();
    StringBuilder scopeRoleMappingBuilder = new StringBuilder();
    StringBuilder operationAuthSchemeMappingBuilder = new StringBuilder();
    StringBuilder operationThrottlingMappingBuilder = new StringBuilder();
    StringBuilder policyBuilder = new StringBuilder();
    String swaggerDef = api.getSwaggerDefinition();
    OpenAPI openAPI = null;
    LinkedHashMap<String, Object> scopeBindings = null;
    if (swaggerDef != null) {
        OpenAPIParser parser = new OpenAPIParser();
        openAPI = parser.readContents(swaggerDef, null, null).getOpenAPI();
    }
    Map<String, Object> extensions = null;
    if (openAPI != null) {
        extensions = openAPI.getComponents().getSecuritySchemes().get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions();
    }
    if (extensions != null) {
        scopeBindings = (LinkedHashMap<String, Object>) openAPI.getComponents().getSecuritySchemes().get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    }
    if (swaggerDef != null) {
        for (URITemplate template : api.getUriTemplates()) {
            String scopeInURITemplate = template.getScope() != null ? template.getScope().getKey() : null;
            if (scopeInURITemplate != null) {
                operationScopeMap.put(template.getUriTemplate(), scopeInURITemplate);
                if (!scopeRoleMap.containsKey(scopeInURITemplate)) {
                    if (scopeBindings != null) {
                        scopeRoleMap.put(scopeInURITemplate, scopeBindings.get(scopeInURITemplate).toString());
                    }
                }
            }
        }
        for (URITemplate template : api.getUriTemplates()) {
            operationThrottlingMap.put(template.getUriTemplate(), template.getThrottlingTier());
            operationAuthSchemeMap.put(template.getUriTemplate(), template.getAuthType());
        }
        if (operationScopeMap.size() > 0) {
            String base64EncodedURLOperationKey;
            String base64EncodedURLScope;
            for (Map.Entry<String, String> entry : operationScopeMap.entrySet()) {
                base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
                base64EncodedURLScope = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getValue().getBytes(Charset.defaultCharset()));
                operationScopeType = "type " + APIConstants.SCOPE_OPERATION_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + base64EncodedURLScope + ": String\n}\n";
                operationScopeMappingBuilder.append(operationScopeType);
            }
            schemaDefinitionBuilder.append(operationScopeMappingBuilder.toString());
        }
        if (scopeRoleMap.size() > 0) {
            String[] roleList;
            String scopeType;
            String base64EncodedURLScopeKey;
            String scopeRoleMappingType;
            String base64EncodedURLRole;
            String roleField;
            for (Map.Entry<String, String> entry : scopeRoleMap.entrySet()) {
                List<String> scopeRoles = new ArrayList<>();
                base64EncodedURLScopeKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
                scopeType = "type " + APIConstants.SCOPE_ROLE_MAPPING + "_" + base64EncodedURLScopeKey + "{\n";
                StringBuilder scopeRoleBuilder = new StringBuilder(scopeType);
                roleList = entry.getValue().split(",");
                for (String role : roleList) {
                    if (!role.equals("") && !scopeRoles.contains(role)) {
                        base64EncodedURLRole = Base64.getUrlEncoder().withoutPadding().encodeToString(role.getBytes(Charset.defaultCharset()));
                        roleField = base64EncodedURLRole + ": String\n";
                        scopeRoleBuilder.append(roleField);
                        scopeRoles.add(role);
                    }
                }
                if (scopeRoles.size() > 0 && !StringUtils.isEmpty(scopeRoleBuilder.toString())) {
                    scopeRoleMappingType = scopeRoleBuilder.toString() + "}\n";
                    scopeRoleMappingBuilder.append(scopeRoleMappingType);
                }
            }
            schemaDefinitionBuilder.append(scopeRoleMappingBuilder.toString());
        }
        if (operationThrottlingMap.size() > 0) {
            String operationThrottlingType;
            for (Map.Entry<String, String> entry : operationThrottlingMap.entrySet()) {
                String base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
                String base64EncodedURLThrottilingTier = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getValue().getBytes(Charset.defaultCharset()));
                operationThrottlingType = "type " + APIConstants.OPERATION_THROTTLING_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + base64EncodedURLThrottilingTier + ": String\n}\n";
                operationThrottlingMappingBuilder.append(operationThrottlingType);
            }
            schemaDefinitionBuilder.append(operationThrottlingMappingBuilder.toString());
        }
        if (operationAuthSchemeMap.size() > 0) {
            String operationAuthSchemeType;
            String isSecurityEnabled;
            for (Map.Entry<String, String> entry : operationAuthSchemeMap.entrySet()) {
                String base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
                if (entry.getValue().equalsIgnoreCase(APIConstants.AUTH_NO_AUTHENTICATION)) {
                    isSecurityEnabled = APIConstants.OPERATION_SECURITY_DISABLED;
                } else {
                    isSecurityEnabled = APIConstants.OPERATION_SECURITY_ENABLED;
                }
                operationAuthSchemeType = "type " + APIConstants.OPERATION_AUTH_SCHEME_MAPPING + "_" + base64EncodedURLOperationKey + "{\n" + isSecurityEnabled + ": String\n}\n";
                operationAuthSchemeMappingBuilder.append(operationAuthSchemeType);
            }
            schemaDefinitionBuilder.append(operationAuthSchemeMappingBuilder.toString());
        }
        if (operationAuthSchemeMap.size() > 0) {
            // Constructing the policy definition
            JSONObject jsonPolicyDefinition = policyDefinitionToJson(graphqlComplexityInfo);
            String base64EncodedPolicyDefinition = Base64.getUrlEncoder().withoutPadding().encodeToString(jsonPolicyDefinition.toJSONString().getBytes(Charset.defaultCharset()));
            String policyDefinition = "type " + APIConstants.GRAPHQL_ACCESS_CONTROL_POLICY + " {\n" + base64EncodedPolicyDefinition + ": String\n}\n";
            policyBuilder.append(policyDefinition);
            schemaDefinitionBuilder.append(policyBuilder.toString());
        }
    }
    return schemaDefinitionBuilder.toString();
}
Also used : URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) OpenAPIParser(io.swagger.parser.OpenAPIParser) JSONObject(org.json.simple.JSONObject) Swagger(io.swagger.models.Swagger) JSONObject(org.json.simple.JSONObject) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Example 22 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class SystemScopesApiServiceImpl method systemScopesGet.

public Response systemScopesGet(MessageContext messageContext) {
    try {
        Map<String, String> scopeRoleMapping = APIUtil.getRESTAPIScopesForTenantWithoutRoleMappings(MultitenantUtils.getTenantDomain(RestApiCommonUtil.getLoggedInUsername()));
        ScopeListDTO scopeListDTO = SystemScopesMappingUtil.fromScopeListToScopeListDTO(scopeRoleMapping);
        return Response.ok().entity(scopeListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error when getting the list of scopes-role mapping.";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : ScopeListDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ScopeListDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Example 23 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class UserSignUpWSWorkflowExecutor method complete.

@Override
public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowException {
    // workflowDTO.setStatus(workflowDTO.getStatus());
    workflowDTO.setUpdatedTime(System.currentTimeMillis());
    if (log.isDebugEnabled()) {
        log.debug("User Sign Up [Complete] Workflow Invoked. Workflow ID : " + workflowDTO.getExternalWorkflowReference() + "Workflow State : " + workflowDTO.getStatus());
    }
    super.complete(workflowDTO);
    String tenantDomain = workflowDTO.getTenantDomain();
    try {
        UserRegistrationConfigDTO signupConfig = SelfSignUpUtil.getSignupConfiguration(tenantDomain);
        String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(workflowDTO.getWorkflowReference());
        if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) {
            try {
                updateRolesOfUser(tenantAwareUserName, SelfSignUpUtil.getRoleNames(signupConfig), tenantDomain);
            } catch (Exception e) {
                // updateRolesOfUser throws generic Exception. Therefore generic Exception is caught
                throw new WorkflowException("Error while assigning role to user", e);
            }
        } else {
            try {
                /* Remove created user */
                deleteUser(tenantDomain, tenantAwareUserName);
            } catch (Exception e) {
                throw new WorkflowException("Error while deleting the user", e);
            }
        }
    } catch (APIManagementException e1) {
        throw new WorkflowException("Error while accessing signup configuration", e1);
    }
    return new GeneralWorkflowResponse();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) XMLStreamException(javax.xml.stream.XMLStreamException)

Example 24 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class UserSignUpWorkflowExecutor method updateRolesOfUser.

/**
 * Method updates Roles users with list of roles
 *
 * @param userName
 * @param tenantDomain
 * @param roleList
 * @throws Exception
 */
protected static void updateRolesOfUser(String userName, List<String> roleList, String tenantDomain) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Adding roles to " + userName + "in " + tenantDomain + " Domain");
    }
    RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
    int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
    UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
    UserStoreManager manager = realm.getUserStoreManager();
    if (manager.isExistingUser(userName)) {
        // check whether given roles exist
        for (String role : roleList) {
            if (!manager.isExistingRole(role)) {
                log.error("Could not find role " + role + " in the user store");
                throw new Exception("Could not find role " + role + " in the user store");
            }
        }
        manager.updateRoleListOfUser(userName, null, roleList.toArray(new String[0]));
    } else {
        log.error("User does not exist. Unable to approve user " + userName);
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 25 with Role

use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.

the class APIProviderImpl method updateRegistryResources.

/**
 * To add API/Product roles restrictions and add additional properties.
 *
 * @param artifactPath                Path of the API/Product artifact.
 * @param publisherAccessControlRoles Role specified for the publisher access control.
 * @param publisherAccessControl      Publisher Access Control restriction.
 * @param additionalProperties        Additional properties that is related with an API/Product.
 * @throws RegistryException Registry Exception.
 */
private void updateRegistryResources(String artifactPath, String publisherAccessControlRoles, String publisherAccessControl, Map<String, String> additionalProperties) throws RegistryException {
    publisherAccessControlRoles = (publisherAccessControlRoles == null || publisherAccessControlRoles.trim().isEmpty()) ? APIConstants.NULL_USER_ROLE_LIST : publisherAccessControlRoles;
    if (publisherAccessControlRoles.equalsIgnoreCase(APIConstants.NULL_USER_ROLE_LIST)) {
        publisherAccessControl = APIConstants.NO_ACCESS_CONTROL;
    }
    if (!registry.resourceExists(artifactPath)) {
        return;
    }
    Resource apiResource = registry.get(artifactPath);
    if (apiResource != null) {
        if (additionalProperties != null) {
            // Removing all the properties, before updating new properties.
            Properties properties = apiResource.getProperties();
            if (properties != null) {
                Enumeration propertyNames = properties.propertyNames();
                while (propertyNames.hasMoreElements()) {
                    String propertyName = (String) propertyNames.nextElement();
                    if (propertyName.startsWith(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX)) {
                        apiResource.removeProperty(propertyName);
                    }
                }
            }
        }
        // We are changing to lowercase, as registry search only supports lower-case characters.
        apiResource.setProperty(APIConstants.PUBLISHER_ROLES, publisherAccessControlRoles.toLowerCase());
        // This property will be only used for display proposes in the Publisher UI so that the original case of
        // the roles that were specified can be maintained.
        apiResource.setProperty(APIConstants.DISPLAY_PUBLISHER_ROLES, publisherAccessControlRoles);
        apiResource.setProperty(APIConstants.ACCESS_CONTROL, publisherAccessControl);
        apiResource.removeProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY);
        if (additionalProperties != null && additionalProperties.size() != 0) {
            for (Map.Entry<String, String> entry : additionalProperties.entrySet()) {
                apiResource.setProperty((APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + entry.getKey()), entry.getValue());
            }
        }
        registry.put(artifactPath, apiResource);
    }
}
Also used : Enumeration(java.util.Enumeration) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) Properties(java.util.Properties) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Aggregations

Test (org.testng.annotations.Test)85 ArrayList (java.util.ArrayList)74 UserStoreException (org.wso2.carbon.user.api.UserStoreException)56 HashMap (java.util.HashMap)52 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)42 Connection (java.sql.Connection)36 SQLException (java.sql.SQLException)34 Role (org.wso2.charon3.core.objects.Role)33 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)31 CharonException (org.wso2.charon3.core.exceptions.CharonException)29 RoleBasicInfo (org.wso2.carbon.identity.role.mgt.core.RoleBasicInfo)26 PreparedStatement (java.sql.PreparedStatement)25 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 RoleMapping (org.wso2.carbon.identity.application.common.model.RoleMapping)24 ISIntegrationTest (org.wso2.identity.integration.common.utils.ISIntegrationTest)23 HashSet (java.util.HashSet)20 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)20 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)19 IdentityRoleManagementClientException (org.wso2.carbon.identity.role.mgt.core.IdentityRoleManagementClientException)19 Matchers.anyString (org.mockito.Matchers.anyString)18