Search in sources :

Example 6 with AuthorizationManager

use of org.wso2.carbon.user.api.AuthorizationManager in project carbon-apimgt by wso2.

the class AbstractAPIManager method registerCustomQueries.

/**
 * method to register custom registry queries
 *
 * @param registry Registry instance to use
 * @throws RegistryException n error
 */
protected void registerCustomQueries(UserRegistry registry, String username) throws RegistryException, APIManagementException {
    String tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
    String latestAPIsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/latest-apis";
    String resourcesByTag = RegistryConstants.QUERIES_COLLECTION_PATH + "/resource-by-tag";
    String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION);
    if (username == null) {
        try {
            UserRealm realm = ServiceReferenceHolder.getUserRealm();
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(realm);
            authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
        } catch (UserStoreException e) {
            String msg = "Error while setting the permissions";
            throw new APIManagementException(msg, e);
        }
    } else if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        int tenantId;
        try {
            tenantId = getTenantManager().getTenantId(tenantDomain);
            AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            String msg = "Error while setting the permissions";
            throw new APIManagementException(msg, e);
        }
    }
    if (!registry.resourceExists(tagsQueryPath)) {
        Resource resource = registry.newResource();
        // Tag Search Query
        // 'MOCK_PATH' used to bypass ChrootWrapper -> filterSearchResult. A valid registry path is
        // a must for executeQuery results to be passed to client side
        String sql1 = "SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " + "   RT.REG_TAG_NAME AS TAG_NAME, " + "   COUNT(RT.REG_TAG_NAME) AS USED_COUNT " + "FROM " + "   REG_RESOURCE_TAG RRT, " + "   REG_TAG RT, " + "   REG_RESOURCE R, " + "   REG_RESOURCE_PROPERTY RRP, " + "   REG_PROPERTY RP " + "WHERE " + "   RT.REG_ID = RRT.REG_TAG_ID  " + "   AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + "   AND RRT.REG_VERSION = R.REG_VERSION " + "   AND RRP.REG_VERSION = R.REG_VERSION " + "   AND RP.REG_NAME = 'STATUS' " + "   AND RRP.REG_PROPERTY_ID = RP.REG_ID " + "   AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED' AND RP.REG_VALUE !='BLOCKED' AND RP.REG_VALUE !='RETIRED') " + "GROUP BY " + "   RT.REG_TAG_NAME";
        resource.setContent(sql1);
        resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
        resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
        registry.put(tagsQueryPath, resource);
    }
    if (!registry.resourceExists(latestAPIsQueryPath)) {
        // Recently added APIs
        Resource resource = registry.newResource();
        String sql = "SELECT " + "   RR.REG_PATH_ID AS REG_PATH_ID, " + "   RR.REG_NAME AS REG_NAME " + "FROM " + "   REG_RESOURCE RR, " + "   REG_RESOURCE_PROPERTY RRP, " + "   REG_PROPERTY RP " + "WHERE " + "   RR.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + "   AND RRP.REG_VERSION = RR.REG_VERSION " + "   AND RP.REG_NAME = 'STATUS' " + "   AND RRP.REG_PROPERTY_ID = RP.REG_ID " + "   AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED') " + "ORDER BY " + "   RR.REG_LAST_UPDATED_TIME " + "DESC ";
        resource.setContent(sql);
        resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
        resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);
        registry.put(latestAPIsQueryPath, resource);
    }
    if (!registry.resourceExists(resourcesByTag)) {
        Resource resource = registry.newResource();
        String sql = "SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " + "   R.REG_UUID AS REG_UUID " + "FROM " + "   REG_RESOURCE_TAG RRT, " + "   REG_TAG RT, " + "   REG_RESOURCE R, " + "   REG_PATH RP " + "WHERE " + "   RT.REG_TAG_NAME = ? " + "   AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + "   AND RP.REG_PATH_ID = R.REG_PATH_ID " + "   AND RT.REG_ID = RRT.REG_TAG_ID " + "   AND RRT.REG_VERSION = R.REG_VERSION ";
        resource.setContent(sql);
        resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
        resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCE_UUID_RESULT_TYPE);
        registry.put(resourcesByTag, resource);
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.core.UserStoreException) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager)

Example 7 with AuthorizationManager

use of org.wso2.carbon.user.api.AuthorizationManager in project carbon-apimgt by wso2.

the class APIProviderImpl method getAuthorizedRoles.

private String[] getAuthorizedRoles(String artifactPath) throws UserStoreException {
    String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
        return authManager.getAllowedRolesForResource(resourcePath, ActionConstants.GET);
    } else {
        RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
        return authorizationManager.getAllowedRolesForResource(resourcePath, ActionConstants.GET);
    }
}
Also used : RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager)

Example 8 with AuthorizationManager

use of org.wso2.carbon.user.api.AuthorizationManager in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method loadloadTenantAPIRXT.

public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    UserRegistry registry = null;
    try {
        registry = registryService.getGovernanceSystemRegistry(tenantID);
    } catch (RegistryException e) {
        throw new APIManagementException("Error when create registry instance ", e);
    }
    String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
    File file = new File(rxtDir);
    FilenameFilter filenameFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            // if the file extension is .rxt return true, else false
            return name.endsWith(".rxt");
        }
    };
    String[] rxtFilePaths = file.list(filenameFilter);
    if (rxtFilePaths == null) {
        throw new APIManagementException("rxt files not found in directory " + rxtDir);
    }
    for (String rxtPath : rxtFilePaths) {
        String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
        // This is  "registry" is a governance registry instance, therefore calculate the relative path to governance.
        String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
        try {
            // 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 (registry.resourceExists(govRelativePath)) {
                // set anonymous user permission to RXTs
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                continue;
            }
            String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
            Resource resource = registry.newResource();
            resource.setContent(rxt.getBytes(Charset.defaultCharset()));
            resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
            registry.put(govRelativePath, resource);
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
        } catch (UserStoreException e) {
            throw new APIManagementException("Error while adding role permissions to API", e);
        } catch (IOException e) {
            String msg = "Failed to read rxt files";
            throw new APIManagementException(msg, e);
        } catch (RegistryException e) {
            String msg = "Failed to add rxt to registry ";
            throw new APIManagementException(msg, e);
        }
    }
}
Also used : AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FilenameFilter(java.io.FilenameFilter) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File)

Example 9 with AuthorizationManager

use of org.wso2.carbon.user.api.AuthorizationManager in project carbon-apimgt by wso2.

the class APIUtilTest method testHasPermission.

@Test
public void testHasPermission() throws Exception {
    int tenantId = 2;
    String userNameWithoutChange = "Drake";
    String permission = APIConstants.Permissions.API_PUBLISH;
    System.setProperty(CARBON_HOME, "");
    PowerMockito.spy(APIUtil.class);
    PowerMockito.doReturn(false).when(APIUtil.class, "isPermissionCheckDisabled");
    PowerMockito.doReturn(1).when(APIUtil.class, "getValueFromCache", APIConstants.API_PUBLISHER_ADMIN_PERMISSION_CACHE, userNameWithoutChange);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Mockito.when(MultitenantUtils.getTenantDomain(userNameWithoutChange)).thenReturn(tenantDomain);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    Mockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    Mockito.when(realmService.getTenantUserRealm(tenantId)).thenReturn(userRealm);
    org.wso2.carbon.user.api.AuthorizationManager authorizationManager = Mockito.mock(org.wso2.carbon.user.api.AuthorizationManager.class);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authorizationManager);
    Mockito.when(authorizationManager.isUserAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true);
    org.wso2.carbon.user.core.UserRealm userRealm2 = Mockito.mock(org.wso2.carbon.user.core.UserRealm.class);
    Mockito.when(ServiceReferenceHolder.getUserRealm()).thenReturn((userRealm2));
    PowerMockito.mockStatic(AuthorizationManager.class);
    AuthorizationManager authorizationManager1 = Mockito.mock(AuthorizationManager.class);
    Mockito.when(AuthorizationManager.getInstance()).thenReturn(authorizationManager1);
    Mockito.when(authorizationManager1.isUserAuthorized(Mockito.anyString(), Mockito.anyString())).thenReturn(true);
    Log logMock = Mockito.mock(Log.class);
    PowerMockito.mockStatic(LogFactory.class);
    Mockito.when(LogFactory.getLog(any(Class.class))).thenReturn(logMock);
    boolean expectedResult = APIUtil.hasPermission(userNameWithoutChange, permission);
    Assert.assertEquals(true, expectedResult);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Log(org.apache.commons.logging.Log) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 10 with AuthorizationManager

use of org.wso2.carbon.user.api.AuthorizationManager in project carbon-apimgt by wso2.

the class StandaloneAuthorizationManagerClientTestCase method setup.

@Before
public void setup() throws Exception {
    ServiceReferenceHolderMockCreator serviceReferenceHolderMockCreator = new ServiceReferenceHolderMockCreator(4444);
    serviceReferenceHolder = serviceReferenceHolderMockCreator.getMock();
    Mockito.when(serviceReferenceHolder.getUserRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authorizationManager);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
}
Also used : ServiceReferenceHolderMockCreator(org.wso2.carbon.apimgt.impl.ServiceReferenceHolderMockCreator) Before(org.junit.Before)

Aggregations

AuthorizationManager (org.wso2.carbon.user.api.AuthorizationManager)11 RegistryAuthorizationManager (org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager)10 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 Resource (org.wso2.carbon.registry.core.Resource)7 UserStoreException (org.wso2.carbon.user.api.UserStoreException)7 Test (org.junit.Test)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)4 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)4 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)4 RealmService (org.wso2.carbon.user.core.service.RealmService)4 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)3 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)3 UserRealm (org.wso2.carbon.user.api.UserRealm)3 File (java.io.File)2 FilenameFilter (java.io.FilenameFilter)2 IOException (java.io.IOException)2 APIResource (org.wso2.carbon.apimgt.api.doc.model.APIResource)2 API (org.wso2.carbon.apimgt.api.model.API)2 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)2