org.wso2.carbon.utils.multitenancy.MultitenantConstants Java Examples

The following examples show how to use org.wso2.carbon.utils.multitenancy.MultitenantConstants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IdentityMgtEventListener.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void sendEmail(String userName, int tenantId, String notification) {
    UserRecoveryDTO dto;
    String tenantDomain = IdentityTenantUtil.getTenantDomain(tenantId);

    if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        dto = new UserRecoveryDTO(userName);
    } else {
        UserDTO userDTO = new UserDTO(UserCoreUtil.addTenantDomainToEntry(userName, tenantDomain));
        userDTO.setTenantId(tenantId);
        dto = new UserRecoveryDTO(userDTO);
    }
    dto.setNotification(notification);
    dto.setNotificationType(EMAIL_NOTIFICATION_TYPE);
    try {
        IdentityMgtServiceComponent.getRecoveryProcessor().recoverWithNotification(dto);
    } catch (IdentityException e) {
        //proceed with the rest of the flow even if the email is not sent
        log.error("Email notification sending failed for user:" + userName + " for " + notification);
    }
}
 
Example #2
Source File: IdentityTenantUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Get the tenant id of the given user.
 *
 * @param username Username
 * @return Tenant Id of domain user belongs to.
 * @throws IdentityRuntimeException Error when getting the tenant Id from tenant domain
 */
public static int getTenantIdOfUser(String username) throws IdentityRuntimeException {

    int tenantId = MultitenantConstants.INVALID_TENANT_ID;
    String domainName = MultitenantUtils.getTenantDomain(username);
    if (domainName != null) {
        try {
            TenantManager tenantManager = IdentityTenantUtil.getRealmService().getTenantManager();
            tenantId = tenantManager.getTenantId(domainName);
        } catch (UserStoreException e) {
            String errorMsg = "Error when getting the tenant id from the tenant domain : " + domainName;
            throw IdentityRuntimeException.error(errorMsg, e);
        }
    }
    if(tenantId == MultitenantConstants.INVALID_TENANT_ID){
        throw IdentityRuntimeException.error("Invalid tenant domain of user " + username);
    } else {
        return tenantId;
    }
}
 
Example #3
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Set<Tier> getAllTiers() throws APIManagementException {
    Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
    Map<String, Tier> tierMap;

    if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
        tierMap = APIUtil.getAllTiers();
    } else {
        boolean isTenantFlowStarted = false;
        try {
            if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                startTenantFlow(tenantDomain);
                isTenantFlowStarted = true;
            }
            tierMap = APIUtil.getAllTiers(tenantId);
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
    }

    tiers.addAll(tierMap.values());
    return tiers;
}
 
Example #4
Source File: CacheBackedApplicationDAO.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void addAppBasicInfoToCache(ApplicationBasicInfo appBasicInfo, String tenantDomain) throws
        IdentityApplicationManagementException {

    if (log.isDebugEnabled()) {
        log.debug("Add cache for the application " + appBasicInfo.getApplicationName() + "@" + tenantDomain);
    }
    try {
        ApplicationMgtUtil.startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

        ApplicationBasicInfoResourceIdCacheKey key =
                new ApplicationBasicInfoResourceIdCacheKey(appBasicInfo.getApplicationResourceId());
        ApplicationBasicInfoResourceIdCacheEntry entry = new ApplicationBasicInfoResourceIdCacheEntry(appBasicInfo);
        appBasicInfoCacheByResourceId.addToCache(key, entry);
    } finally {
        ApplicationMgtUtil.endTenantFlow();
    }
}
 
Example #5
Source File: ManagementPermissionsAdder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public void bundleChanged(BundleEvent event) {
    Bundle bundle = event.getBundle();
    try {
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);

        if (event.getType() == BundleEvent.STARTED) {
            addUIPermissionFromBundle(bundle);
        }
    } catch (Exception e) {
        log.error("Error occured when processing component xml in bundle " +
                bundle.getSymbolicName(), e);
    }
}
 
Example #6
Source File: APIManagerCacheExtensionHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Put the access token that was cached in the tenant's cache space into invalid token cache
 *
 * @param accessToken        - Token to be removed from the cache.
 * @param cachedTenantDomain - Tenant domain from which the token should be removed.
 */
private void putInvalidTokenIntoTenantInvalidTokenCache(String accessToken, String cachedTenantDomain) {
    //If the token was cached in the tenant cache
    if (cachedTenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(cachedTenantDomain)) {

        if (log.isDebugEnabled()) {
            log.debug("Going to put cache entry " + accessToken + " from " + cachedTenantDomain + " domain");
        }
        try {
            startTenantFlow(cachedTenantDomain);
            //Remove the tenant cache entry.
            putInvalidTokenEntryIntoInvalidTokenCache(accessToken, cachedTenantDomain);
            if (log.isDebugEnabled()) {
                log.debug(" Put invalid cached entry " + accessToken + " from " + cachedTenantDomain + " domain");
            }
        } finally {
            endTenantFlow();
        }
    }
}
 
Example #7
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Starts the tenant flow for the given tenant domain
 *
 * @param tenantDomain tenant domain
 */
public static void startTenantFlow(String tenantDomain) {
    String tenantDomainParam = tenantDomain;
    int tenantId = MultitenantConstants.SUPER_TENANT_ID;

    if (tenantDomainParam != null && !tenantDomainParam.trim().isEmpty()) {
        try {
            tenantId = FrameworkServiceComponent.getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            log.error("Error while getting tenantId from tenantDomain query param", e);
        }
    } else {
        tenantDomainParam = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
            .getThreadLocalCarbonContext();
    carbonContext.setTenantId(tenantId);
    carbonContext.setTenantDomain(tenantDomainParam);
}
 
Example #8
Source File: CarbonUILoginUtil.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param requestedURI
 * @param request
 * @return
 */
protected static String getForcedSignOutRequestedURI(String requestedURI,
        HttpServletRequest request) {
    if (requestedURI.endsWith(".jsp")
            && !requestedURI.endsWith("ajaxprocessor.jsp")
            && !requestedURI.endsWith("session_validate.jsp")
            && (request.getSession().getAttribute("authenticated")) != null
            && ((Boolean) (request.getSession().getAttribute("authenticated"))).booleanValue()
            && ((request.getSession().getAttribute(MultitenantConstants.TENANT_DOMAIN) == null && request
                    .getAttribute(MultitenantConstants.TENANT_DOMAIN) != null) || ((request
                    .getSession().getAttribute(MultitenantConstants.TENANT_DOMAIN) != null && request
                    .getAttribute(MultitenantConstants.TENANT_DOMAIN) != null) && !request
                    .getSession().getAttribute(MultitenantConstants.TENANT_DOMAIN)
                    .equals(request.getAttribute(MultitenantConstants.TENANT_DOMAIN))))) {
        // If someone signed in from a tenant, try to access a different tenant domain, he
        // should be forced to sign out without any prompt Cloud requirement
        requestedURI = "../admin/logout_action.jsp";
    }

    return requestedURI;
}
 
Example #9
Source File: CacheBackedApplicationDAO.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private ServiceProvider getApplicationFromCache(int appId) throws IdentityApplicationManagementException {

        ServiceProvider serviceProvider = null;
        try {
            ApplicationMgtUtil.startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
            ServiceProviderIDCacheKey cacheKey = new ServiceProviderIDCacheKey(appId);
            ServiceProviderIDCacheEntry entry = appCacheByID.getValueFromCache(cacheKey);

            if (entry != null) {
                serviceProvider = entry.getServiceProvider();
            }
        } finally {
            ApplicationMgtUtil.endTenantFlow();
        }
        if (serviceProvider == null) {
            if (log.isDebugEnabled()) {
                log.debug("Cache missing for the application with id " + appId);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Cache present for the application with id " + appId);
            }
        }
        return serviceProvider;
    }
 
Example #10
Source File: BaseCache.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Clears a cache entry.
 *
 * @param key Key to clear cache.
 */
public void clearCacheEntry(K key) {
    if (!isEnabled()) {
        return;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Cache<K, V> cache = getBaseCache();
        if (cache != null) {
            cache.remove(key);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #11
Source File: SignKeyDataHolder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public SignKeyDataHolder() throws Exception {
    try {
        String keyAlias = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.KeyAlias");
        KeyStoreManager keyMan = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
        Certificate[] certificates = keyMan.getPrimaryKeyStore().getCertificateChain(keyAlias);
        issuerPK = keyMan.getDefaultPrivateKey();
        issuerCerts = new X509Certificate[certificates.length];
        int i = 0;
        for (Certificate certificate : certificates) {
            issuerCerts[i++] = (X509Certificate) certificate;
        }
        signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA;
        String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
        }

    } catch (Exception e) {
        throw new Exception("Error while reading the key", e);
    }

}
 
Example #12
Source File: BaseCache.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Add a cache entry.
 *
 * @param key   Key which cache entry is indexed.
 * @param entry Actual object where cache entry is placed.
 */
public void addToCache(K key, V entry) {

    if (!isEnabled()) {
        return;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        // Element already in the cache. Remove it first
        Cache<K, V> cache = getBaseCache();
        if (cache != null) {
            cache.put(key, entry);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #13
Source File: BaseCache.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Remove everything in the cache.
 */
public void clear() {

    if (!isEnabled()) {
        return;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Cache<K, V> cache = getBaseCache();
        if (cache != null) {
            cache.removeAll();
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #14
Source File: APISynchronizer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Method to load the configurations of a tenant
 */
private void loadTenant(String username) {
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        ConfigurationContext context = ServiceDataHolder.getInstance().getConfigurationContextService()
                .getServerConfigContext();
        TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, context);
        if (log.isDebugEnabled()) {
            log.debug("Tenant was loaded into Carbon Context. Tenant : " + tenantDomain
                    + ", Username : " + username);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Skipping loading super tenant space since execution is currently in super tenant flow.");
        }
    }
}
 
Example #15
Source File: APIMRegistryServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public String getGovernanceRegistryResourceContent(String tenantDomain, String registryLocation)
                                    throws UserStoreException, RegistryException {
    String content = null;
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);

        if (registry.resourceExists(registryLocation)) {
            Resource resource = registry.get(registryLocation);
            content = getString(resource);
        }
    }
    finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return content;
}
 
Example #16
Source File: IdentityTenantUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static int getTenantId(String tenantDomain) throws IdentityRuntimeException {

        int tenantId = MultitenantConstants.INVALID_TENANT_ID;
        try {
            if (realmService != null) {
                tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
            }
        } catch (UserStoreException e) {
            // Ideally user.core should be throwing an unchecked exception, in which case no need to wrap at this
            // level once more without adding any valuable contextual information. Because we don't have exception
            // enrichment properly implemented, we are appending the error message from the UserStoreException to the
            // new message
            throw IdentityRuntimeException.error("Error occurred while retrieving tenantId for tenantDomain: " +
                    tenantDomain + e.getMessage(), e);
        }
        if(tenantId == MultitenantConstants.INVALID_TENANT_ID){
            throw IdentityRuntimeException.error("Invalid tenant domain " + tenantDomain);
        } else {
            return tenantId;
        }

    }
 
Example #17
Source File: ClaimsMgtUtil.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Method to get the name of the admin user given the tenant id
 * 
 * @param tenantId
 *            tenant id
 * @return admin user name
 * @throws Exception
 *             UserStoreException
 */
public static String getAdminUserNameFromTenantId(RealmService realmService, int tenantId)
                                                                                          throws Exception {
    if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
        return realmService.getBootstrapRealmConfiguration().getAdminUserName();
    }
    String tenantAdminName ="";
    try {
        if (realmService.getTenantManager().getTenant(tenantId) != null) {
            tenantAdminName = realmService.getTenantManager().getTenant(tenantId).getAdminName();
        }
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "Unable to retrieve the admin name for the tenant with the tenant Id: " +
                     tenantId;
        log.error(msg, e);
        throw new Exception(msg, e);
    }
    return tenantAdminName;
}
 
Example #18
Source File: ForumRegistryComponent.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Activate
protected void activate(ComponentContext componentContext) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Forum Registry Component Activated");
    }
    try {
        TenantServiceCreator tenantServiceCreator = new TenantServiceCreator();
        BundleContext bundleContext = componentContext.getBundleContext();
        bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), tenantServiceCreator, null);
        createTopicsRootCollection(MultitenantConstants.SUPER_TENANT_ID);
        addRxtConfigs(MultitenantConstants.SUPER_TENANT_ID);
    } catch (ForumException e) {
        log.error("Could not activate Forum Registry Component " + e.getMessage());
        throw e;
    }
}
 
Example #19
Source File: IdentityTenantUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private static Registry getRegistryForAnonymousSession(String domainName, String username)
        throws IdentityException {
    try {
        if (domainName == null && username == null) {
            domainName = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        if (username == null) {
            return AnonymousSessionUtil.getSystemRegistryByDomainName(registryService,
                    realmService, domainName);
        } else {
            return AnonymousSessionUtil.getSystemRegistryByUserName(registryService,
                    realmService, username);
        }
    } catch (CarbonException e) {
        log.error("Error obtaining a registry instance", e);
        throw IdentityException.error("Error obtaining a registry instance", e);
    }
}
 
Example #20
Source File: AbstractAdmin.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
protected ConfigurationContext getConfigContext() {

        // If a tenant has been set, then try to get the ConfigurationContext of that tenant
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ConfigurationContextService configurationContextService = (ConfigurationContextService) carbonContext
                .getOSGiService(ConfigurationContextService.class);
        ConfigurationContext mainConfigContext = configurationContextService.getServerConfigContext();
        String domain = carbonContext.getTenantDomain();
        if (domain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(domain)) {
            return TenantAxisUtils.getTenantConfigurationContext(domain, mainConfigContext);
        } else if (carbonContext.getTenantId() == MultitenantConstants.SUPER_TENANT_ID) {
            return mainConfigContext;
        } else {
            throw new UnsupportedOperationException("Tenant domain unidentified. " +
                    "Upstream code needs to identify & set the tenant domain & tenant ID. " +
                    " The TenantDomain SOAP header could be set by the clients or " +
                    "tenant authentication should be carried out.");
        }
    }
 
Example #21
Source File: APIGatewayAdminClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get API from the gateway
 *
 * @param tenantDomain - The Tenant Domain
 * @return - An APIData instance
 * @throws AxisFault
 */
public APIData getApi(String tenantDomain, APIIdentifier apiId) throws AxisFault {

    try {
        APIData apiData;
        if (tenantDomain != null && !("").equals(tenantDomain)
                && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            apiData = apiGatewayAdminStub.getApiForTenant(apiId.getProviderName(), apiId.getApiName(),
                    apiId.getVersion(), tenantDomain);
        } else {
            apiData = apiGatewayAdminStub.getApi(apiId.getProviderName(), apiId.getApiName(), apiId.getVersion());
        }
        return apiData;
    } catch (Exception e) {
        throw new AxisFault("Error while obtaining API information from gateway. " + e.getMessage(), e);
    }
}
 
Example #22
Source File: Utils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Put the access token that was cached in the tenant's cache space into invalid token cache
 *
 * @param accessToken        - Invalid token that should be added to the invalid token cache
 * @param cachedTenantDomain - Tenant domain of the cached token
 */
public static void putInvalidTokenIntoTenantInvalidTokenCache(String accessToken, String cachedTenantDomain) {
    //If the token was cached in the tenant cache
    if (cachedTenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(cachedTenantDomain)) {

        if (log.isDebugEnabled()) {
            log.debug("Putting the cache entry " + accessToken + " of " + cachedTenantDomain + " domain " +
                    "to the invalid token cache...");
        }
        try {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(cachedTenantDomain, true);
            putInvalidTokenEntryIntoInvalidTokenCache(accessToken, cachedTenantDomain);
            if (log.isDebugEnabled()) {
                log.debug(" Token " + accessToken + " of " + cachedTenantDomain + " domain was put to the " +
                        "invalid token cache.");
            }
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
 
Example #23
Source File: IdPMgtValidationListener.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doPreDeleteIdP(String idPName, String tenantDomain) throws IdentityProviderManagementException {

    if (StringUtils.isEmpty(idPName)) {
        throw new IllegalArgumentException("Invalid argument: Identity Provider Name value is empty");
    }

    String loggedInTenant = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();

    if (IdentityApplicationConstants.RESIDENT_IDP_RESERVED_NAME.equals(idPName)) {
        if (StringUtils.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, tenantDomain)) {
            throw new IdentityProviderManagementException("Cannot delete Resident Identity Provider of Super " +
                    "Tenant");
        } else if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME != loggedInTenant) {
            throw new IdentityProviderManagementException("Tenant user of " + loggedInTenant + " cannot delete " +
                    "Resident Identity Provider of tenant " + tenantDomain);
        } else {
            log.warn("Deleting Resident Identity Provider for tenant " + tenantDomain);
        }
    }

    return true;
}
 
Example #24
Source File: ServerStartupListener.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public void completedServerStartup() {

    copyToExtensions();

    APIManagerConfiguration apiManagerConfiguration =
            ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    if (apiManagerConfiguration != null) {
        String defaultKeyManagerRegistration =
                apiManagerConfiguration.getFirstProperty(APIConstants.ENABLE_DEFAULT_KEY_MANAGER_REGISTRATION);
        if (StringUtils.isNotEmpty(defaultKeyManagerRegistration) &&
                JavaUtils.isTrueExplicitly(defaultKeyManagerRegistration)) {
            try {
                KeyMgtRegistrationService.registerDefaultKeyManager(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
            } catch (APIManagementException e) {
                log.error("Error while registering Default Key Manager for SuperTenant", e);
            }
        }
        String enableKeyManagerRetrieval =
                apiManagerConfiguration.getFirstProperty(APIConstants.ENABLE_KEY_MANAGER_RETRIVAL);
        if (JavaUtils.isTrueExplicitly(enableKeyManagerRetrieval)) {
            startConfigureKeyManagerConfigurations();
        }
    }
}
 
Example #25
Source File: BasicAuthAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This method tests the behaviour of the authenticate method in BasicAuthenticator with valid "
        + "credentials", dependsOnMethods = "testCanHandleWithRequireParameters")
public void testAuthenticateWithValidCredentials() throws EncoderException, IllegalAccessException {
    String encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER).getBytes()));
    request = new Request();
    context = new StandardContext();
    context.addParameter("basicAuth", "true");
    request.setContext(context);
    mimeHeaders = new MimeHeaders();
    bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
    bytes.setString(BASIC_HEADER + encodedString);
    coyoteRequest = new org.apache.coyote.Request();
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    AuthenticationInfo authenticationInfo = basicAuthAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
            "For a valid user authentication failed.");
    Assert.assertEquals(authenticationInfo.getUsername(), ADMIN_USER,
            "Authenticated username for from BasicAuthenticator is not matching with the original user.");
    Assert.assertEquals(authenticationInfo.getTenantDomain(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME,
            "Authenticated user's tenant domain from BasicAuthenticator is not matching with the "
                    + "original user's tenant domain");
    Assert.assertEquals(authenticationInfo.getTenantId(), MultitenantConstants.SUPER_TENANT_ID,
            "Authenticated user's tenant ID from BasicAuthenticator is not matching with the "
                    + "original user's tenant ID");
}
 
Example #26
Source File: BaseWebAppAuthenticatorFrameworkTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * To get the registry service.
 * @return RegistryService
 * @throws RegistryException Registry Exception
 */
private  RegistryService getRegistryService() throws RegistryException, UserStoreException {
    RealmService realmService = new InMemoryRealmService();
    AuthenticatorFrameworkDataHolder.getInstance().setRealmService(realmService);
    UserStoreManager userStoreManager = AuthenticatorFrameworkDataHolder.getInstance().getRealmService()
            .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager();
    Permission adminPermission = new Permission(PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH,
            CarbonConstants.UI_PERMISSION_ACTION);
    userStoreManager.addRole(ADMIN_ROLE + "t", new String[] { ADMIN_USER }, new Permission[] { adminPermission });
    RegistryDataHolder.getInstance().setRealmService(realmService);
    DeviceManagementDataHolder.getInstance().setRealmService(realmService);
    InputStream is = BaseWebAppAuthenticatorFrameworkTest.class.getClassLoader()
            .getResourceAsStream("carbon-home/repository/conf/registry.xml");
    RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
    context.setSetup(true);
    return context.getEmbeddedRegistryService();
}
 
Example #27
Source File: GeoLocationProviderServiceTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private Device enrollDevice() throws Exception {
    DeviceIdentifier deviceIdentifier = new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE);
    Device device = TestDataHolder.generateDummyDeviceData(deviceIdentifier);
    DeviceManagementProviderService deviceMgtService = DeviceManagementDataHolder.getInstance().
            getDeviceManagementProvider();
    deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE,
            MultitenantConstants.SUPER_TENANT_DOMAIN_NAME));
    deviceMgtService.enrollDevice(device);

    Device returnedDevice = deviceMgtService.getDevice(deviceIdentifier);

    if (!returnedDevice.getDeviceIdentifier().equals(deviceIdentifier.getId())) {
        throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!");
    }
    
    return returnedDevice;
}
 
Example #28
Source File: OperationManagementTests.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = "getPendingOperations")
public void getPaginatedRequestAsAdmin() throws OperationManagementException {
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID, true);
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ADMIN_USER);
    PaginationRequest request = new PaginationRequest(1, 2);
    request.setDeviceType(DEVICE_TYPE);
    request.setOwner(ADMIN_USER);
    for (DeviceIdentifier deviceIdentifier : deviceIds) {
        PaginationResult result = this.operationMgtService.getOperations(deviceIdentifier, request);
        Assert.assertEquals(result.getRecordsFiltered(), 4);
        Assert.assertEquals(result.getData().size(), 2);
        Assert.assertEquals(result.getRecordsTotal(), 4);
    }
    PrivilegedCarbonContext.endTenantFlow();
}
 
Example #29
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public String addResourceFile(Identifier identifier, String resourcePath, ResourceFile resourceFile) throws APIManagementException {
    try {
        Resource thumb = registry.newResource();
        thumb.setContentStream(resourceFile.getContent());
        thumb.setMediaType(resourceFile.getContentType());
        registry.put(resourcePath, thumb);
        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
            return RegistryConstants.PATH_SEPARATOR + "registry"
                    + RegistryConstants.PATH_SEPARATOR + "resource"
                    + RegistryConstants.PATH_SEPARATOR + "_system"
                    + RegistryConstants.PATH_SEPARATOR + "governance"
                    + resourcePath;
        } else {
            return "/t/" + tenantDomain + RegistryConstants.PATH_SEPARATOR + "registry"
                    + RegistryConstants.PATH_SEPARATOR + "resource"
                    + RegistryConstants.PATH_SEPARATOR + "_system"
                    + RegistryConstants.PATH_SEPARATOR + "governance"
                    + resourcePath;
        }
    } catch (RegistryException e) {
        String msg = "Error while adding the resource to the registry";
        throw new APIManagementException(msg, e);
    }
}
 
Example #30
Source File: EntitlementEngineCache.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public EntitlementEngine get(int key) {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        EntitlementEngine entitlementEngine = getEntitlementCache().get(key);
        if (entitlementEngine != null) {
            if (log.isDebugEnabled()) {
                log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + "  is HIT " +
                        "for tenantId : " + key);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Cache : " + ENTITLEMENT_ENGINE_CACHE + "  is MISSED " +
                        "for tenantId : " + key);
            }
        }
        return entitlementEngine;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}