Search in sources :

Example 31 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIUtil method createSelfSignUpRoles.

/**
 * @param tenantId
 * @throws APIManagementException
 */
public static void createSelfSignUpRoles(int tenantId) throws APIManagementException {
    try {
        String selfSighupConfig = ServiceReferenceHolder.getInstance().getApimConfigService().getSelfSighupConfig(getTenantDomainFromTenantId(tenantId));
        DocumentBuilderFactory factory = getSecuredDocumentBuilder();
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        DocumentBuilder parser = factory.newDocumentBuilder();
        InputStream inputStream = new ByteArrayInputStream(selfSighupConfig.getBytes());
        Document dc = parser.parse(inputStream);
        boolean enableSubscriberRoleCreation = isSubscriberRoleCreationEnabled(tenantId);
        String signUpDomain = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_DOMAIN_ELEM).item(0).getFirstChild().getNodeValue();
        if (enableSubscriberRoleCreation) {
            int roleLength = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_NAME_ELEMENT).getLength();
            for (int i = 0; i < roleLength; i++) {
                String roleName = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_NAME_ELEMENT).item(i).getFirstChild().getNodeValue();
                boolean isExternalRole = Boolean.parseBoolean(dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_IS_EXTERNAL).item(i).getFirstChild().getNodeValue());
                if (roleName != null) {
                    // If isExternalRole==false ;create the subscriber role as an internal role
                    if (isExternalRole && signUpDomain != null) {
                        roleName = signUpDomain.toUpperCase() + CarbonConstants.DOMAIN_SEPARATOR + roleName;
                    } else {
                        roleName = UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + roleName;
                    }
                    createSubscriberRole(roleName, tenantId);
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Adding Self signup configuration to the tenant's registry");
        }
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new APIManagementException("Error while getting Self signup role information from the registry", e);
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) Document(org.w3c.dom.Document) SolrDocument(org.apache.solr.common.SolrDocument) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) SAXException(org.xml.sax.SAXException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 32 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIUtil method clearResourcePermissions.

/**
 * This function is to set resource permissions based on its visibility
 *
 * @param artifactPath API/Product resource path
 * @throws APIManagementException Throwing exception
 */
public static void clearResourcePermissions(String artifactPath, Identifier id, int tenantId) throws APIManagementException {
    try {
        String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(id.getProviderName()));
        if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
            authManager.clearResourceAuthorizations(resourcePath);
        } else {
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            authorizationManager.clearResourceAuthorizations(resourcePath);
        }
    } catch (UserStoreException e) {
        handleException("Error while adding role permissions to API", e);
    }
}
Also used : RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 33 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIUtil method copyResourcePermissions.

public static void copyResourcePermissions(String username, String sourceArtifactPath, String targetArtifactPath) throws APIManagementException {
    String sourceResourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + sourceArtifactPath);
    String targetResourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + targetArtifactPath);
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
    try {
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
        String[] allowedRoles = authManager.getAllowedRolesForResource(sourceResourcePath, ActionConstants.GET);
        if (allowedRoles != null) {
            for (String allowedRole : allowedRoles) {
                authManager.authorizeRole(allowedRole, targetResourcePath, ActionConstants.GET);
            }
        }
    } catch (UserStoreException e) {
        throw new APIManagementException("Error while adding role permissions to API", e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 34 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIUtil method isUserInRole.

/**
 * Check whether the user has the given role
 *
 * @throws UserStoreException
 * @throws APIManagementException
 */
public static boolean isUserInRole(String user, String role) throws UserStoreException, APIManagementException {
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(user));
    UserRegistrationConfigDTO signupConfig = SelfSignUpUtil.getSignupConfiguration(tenantDomain);
    user = SelfSignUpUtil.getDomainSpecificUserName(user, signupConfig);
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(user);
    RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
    int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
    UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
    org.wso2.carbon.user.core.UserStoreManager manager = realm.getUserStoreManager();
    AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager;
    return abstractManager.isUserInRole(tenantAwareUserName, role);
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) RealmService(org.wso2.carbon.user.core.service.RealmService) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 35 with Role

use of org.wso2.carbon.identity.role.mgt.core.Role in project carbon-apimgt by wso2.

the class APIUtil method setResourcePermissions.

/**
 * This function is to set resource permissions based on its visibility
 *
 * @param visibility   API/Product visibility
 * @param roles        Authorized roles
 * @param artifactPath API/Product resource path
 * @param registry     Registry
 * @throws APIManagementException Throwing exception
 */
public static void setResourcePermissions(String username, String visibility, String[] roles, String artifactPath, Registry registry) throws APIManagementException {
    try {
        String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
        Resource registryResource = null;
        if (registry != null && registry.resourceExists(artifactPath)) {
            registryResource = registry.get(artifactPath);
        }
        StringBuilder publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
        if (registryResource != null) {
            String publisherRole = registryResource.getProperty(APIConstants.PUBLISHER_ROLES);
            if (publisherRole != null) {
                publisherAccessRoles = new StringBuilder(publisherRole);
            }
            if (StringUtils.isEmpty(publisherAccessRoles.toString())) {
                publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
            }
            if (APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(visibility) || APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
                // set publisher
                publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
            // access roles null since store visibility is global. We do not need to add any roles to
            // store_view_role property.
            } else {
                registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
            }
        }
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            // calculate resource path
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            resourcePath = authorizationManager.computePathOnMount(resourcePath);
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
            if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
                boolean isRoleEveryOne = false;
                /*If no roles have defined, authorize for everyone role */
                if (roles != null) {
                    if (roles.length == 1 && "".equals(roles[0])) {
                        authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                        isRoleEveryOne = true;
                    } else {
                        for (String role : roles) {
                            if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role.trim())) {
                                isRoleEveryOne = true;
                            }
                            authManager.authorizeRole(role.trim(), resourcePath, ActionConstants.GET);
                            publisherAccessRoles.append(",").append(role.trim().toLowerCase());
                        }
                    }
                }
                if (!isRoleEveryOne) {
                    authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                }
                authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
                /*If no roles have defined, deny access for everyone & anonymous role */
                if (roles == null) {
                    authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                    authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                } else {
                    for (String role : roles) {
                        authManager.denyRole(role.trim(), resourcePath, ActionConstants.GET);
                    }
                }
            } else {
                authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            }
        } else {
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
                boolean isRoleEveryOne = false;
                if (roles != null) {
                    for (String role : roles) {
                        if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role.trim())) {
                            isRoleEveryOne = true;
                        }
                        authorizationManager.authorizeRole(role.trim(), resourcePath, ActionConstants.GET);
                        publisherAccessRoles.append(",").append(role.toLowerCase());
                    }
                }
                if (!isRoleEveryOne) {
                    authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                }
                authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
                authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            } else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
                /*If no roles have defined, deny access for everyone & anonymous role */
                if (roles == null) {
                    authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                    authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                } else {
                    for (String role : roles) {
                        authorizationManager.denyRole(role.trim(), resourcePath, ActionConstants.GET);
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Store view roles for " + artifactPath + " : " + publisherAccessRoles.toString());
                }
                authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
                authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
            }
        }
        if (registryResource != null) {
            registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
            registry.put(artifactPath, registryResource);
        }
    } catch (UserStoreException e) {
        throw new APIManagementException("Error while adding role permissions to API", e);
    } catch (RegistryException e) {
        throw new APIManagementException("Registry exception while adding role permissions to API", e);
    }
}
Also used : Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

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