Search in sources :

Example 26 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-business-process by wso2.

the class AuthenticationHandler method authenticate.

/**
 * Checks whether a given userName:password combination authenticates correctly against carbon userStore
 * Upon successful authentication returns true, false otherwise
 *
 * @param userName
 * @param password
 * @return
 * @throws RestApiBasicAuthenticationException wraps and throws exceptions occur when trying to authenticate
 *                                             the user
 */
private boolean authenticate(String userName, String password) throws RestApiBasicAuthenticationException {
    boolean authStatus;
    try {
        IdentityService identityService = BPMNOSGIService.getIdentityService();
        authStatus = identityService.checkPassword(userName, password);
        if (!authStatus) {
            return false;
        }
    } catch (BPMNAuthenticationException e) {
        throw new RestApiBasicAuthenticationException(e.getMessage(), e);
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(userName);
    String userNameWithTenantDomain = tenantAwareUserName + "@" + tenantDomain;
    RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
    TenantManager mgr = realmService.getTenantManager();
    int tenantId = 0;
    try {
        tenantId = mgr.getTenantId(tenantDomain);
        // tenantId == -1, means an invalid tenant.
        if (tenantId == -1) {
            if (log.isDebugEnabled()) {
                log.debug("Basic authentication request with an invalid tenant : " + userNameWithTenantDomain);
            }
            return false;
        }
    } catch (UserStoreException e) {
        throw new RestApiBasicAuthenticationException("Identity exception thrown while getting tenant ID for user : " + userNameWithTenantDomain, e);
    }
    /* Upon successful authentication existing thread local carbon context
             * is updated to mimic the authenticated user */
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    carbonContext.setUsername(tenantAwareUserName);
    carbonContext.setTenantId(tenantId);
    carbonContext.setTenantDomain(tenantDomain);
    return true;
}
Also used : IdentityService(org.activiti.engine.IdentityService) RestApiBasicAuthenticationException(org.wso2.carbon.bpmn.rest.common.exception.RestApiBasicAuthenticationException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) BPMNAuthenticationException(org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager)

Example 27 with Tenant

use of org.wso2.carbon.user.api.Tenant in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPUtils method getMobileNumberForUsername.

/**
 * Get the mobile number for Username.
 *
 * @param username the username
 * @return mobile number
 * @throws SMSOTPException
 */
public static String getMobileNumberForUsername(String username) throws SMSOTPException, AuthenticationFailedException {
    UserRealm userRealm;
    String mobile;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        userRealm = getUserRealm(tenantDomain);
        if (userRealm != null) {
            mobile = userRealm.getUserStoreManager().getUserClaimValue(tenantAwareUsername, SMSOTPConstants.MOBILE_CLAIM, null);
        } else {
            throw new SMSOTPException("Cannot find the user realm for the given tenant domain : " + tenantDomain);
        }
    } catch (UserStoreException e) {
        throw new SMSOTPException("Cannot find the user " + username + " to get the mobile number ", e);
    }
    return mobile;
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SMSOTPException(org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException)

Example 28 with Tenant

use of org.wso2.carbon.user.api.Tenant in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPUtils method verifyUserExists.

/**
 * Verify whether user Exist in the user store or not.
 *
 * @param username the Username
 * @throws SMSOTPException
 */
public static void verifyUserExists(String username, String tenantDomain) throws SMSOTPException, AuthenticationFailedException {
    UserRealm userRealm;
    boolean isUserExist = false;
    try {
        userRealm = SMSOTPUtils.getUserRealm(tenantDomain);
        if (userRealm == null) {
            throw new SMSOTPException("Super tenant realm not loaded.");
        }
        UserStoreManager userStoreManager = userRealm.getUserStoreManager();
        if (userStoreManager.isExistingUser(username)) {
            isUserExist = true;
        }
    } catch (UserStoreException e) {
        throw new SMSOTPException("Error while validating the user.", e);
    }
    if (!isUserExist) {
        if (log.isDebugEnabled()) {
            log.debug("User does not exist in the User Store");
        }
        throw new SMSOTPException("User does not exist in the User Store.");
    }
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SMSOTPException(org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 29 with Tenant

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

the class AbstractAPIManager method getSwaggerDefinitionTimeStamps.

/**
 * gets the swagger definition timestamps as a map
 *
 * @param apiIdentifier
 * @return
 * @throws APIManagementException
 */
public Map<String, String> getSwaggerDefinitionTimeStamps(APIIdentifier apiIdentifier) throws APIManagementException {
    String apiTenantDomain = getTenantDomain(apiIdentifier);
    try {
        Registry registryType;
        // Tenant store anonymous mode if current tenant and the required tenant is not matching
        if (this.tenantDomain == null || isTenantDomainNotMatching(apiTenantDomain)) {
            int tenantId = getTenantManager().getTenantId(apiTenantDomain);
            registryType = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
        } else {
            registryType = registry;
        }
        return OASParserUtil.getAPIOpenAPIDefinitionTimeStamps(apiIdentifier, registryType);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("Error while getting the lastUpdated time due to " + e.getMessage(), e);
    } catch (RegistryException e) {
        log.debug("Error while getting the lastUpdated time due to " + e.getMessage(), e);
    }
    return null;
}
Also used : UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 30 with Tenant

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

the class AbstractAPIManager method searchPaginatedAPIs.

@Override
public Map<String, Object> searchPaginatedAPIs(String searchQuery, String requestedTenantDomain, int start, int end, boolean isLazyLoad, boolean isPublisherListing) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    boolean isTenantFlowStarted = false;
    String[] searchQueries = searchQuery.split("&");
    StringBuilder filteredQuery = new StringBuilder();
    String subQuery = null;
    if (log.isDebugEnabled()) {
        log.debug("Original search query received : " + searchQuery);
    }
    // Filtering the queries related with custom properties
    for (String query : searchQueries) {
        if (searchQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
            subQuery = query;
            break;
        }
        // If the query does not contains "=" then it is an errornous scenario.
        if (query.contains("=")) {
            String[] searchKeys = query.split("=");
            if (searchKeys.length >= 2) {
                if (!Arrays.asList(APIConstants.API_SEARCH_PREFIXES).contains(searchKeys[0].toLowerCase())) {
                    if (log.isDebugEnabled()) {
                        log.debug(searchKeys[0] + " does not match with any of the reserved key words. Hence" + " appending " + APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + " as prefix");
                    }
                    searchKeys[0] = (APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + searchKeys[0]);
                }
                // category search should only return results that exactly match.
                if (searchKeys[0].equals(APIConstants.LABEL_SEARCH_TYPE_PREFIX)) {
                    searchKeys[0] = APIConstants.API_LABELS_GATEWAY_LABELS;
                    searchKeys[1] = searchKeys[1].replace("*", "");
                } else if (searchKeys[0].equals(APIConstants.CATEGORY_SEARCH_TYPE_PREFIX)) {
                    searchKeys[0] = APIConstants.API_CATEGORIES_CATEGORY_NAME;
                    searchKeys[1] = searchKeys[1].replace("*", "");
                }
                if (filteredQuery.length() == 0) {
                    filteredQuery.append(searchKeys[0]).append("=").append(searchKeys[1]);
                } else {
                    filteredQuery.append("&").append(searchKeys[0]).append("=").append(searchKeys[1]);
                }
            }
        } else {
            filteredQuery.append(query);
        }
    }
    searchQuery = filteredQuery.toString();
    if (log.isDebugEnabled()) {
        log.debug("Final search query after the post processing for the custom properties : " + searchQuery);
    }
    try {
        boolean isTenantMode = (requestedTenantDomain != null);
        if (isTenantMode && !org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(requestedTenantDomain)) {
            isTenantFlowStarted = true;
            startTenantFlow(requestedTenantDomain);
        } else {
            requestedTenantDomain = org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            isTenantFlowStarted = true;
            startTenantFlow(requestedTenantDomain);
        }
        Registry userRegistry;
        int tenantIDLocal = 0;
        String userNameLocal = this.username;
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(requestedTenantDomain))) {
            // Tenant store anonymous mode
            tenantIDLocal = getTenantManager().getTenantId(requestedTenantDomain);
            APIUtil.loadTenantRegistry(tenantIDLocal);
            userRegistry = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantIDLocal);
            userNameLocal = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
            if (!requestedTenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                APIUtil.loadTenantConfigBlockingMode(requestedTenantDomain);
            }
        } else {
            userRegistry = this.registry;
            tenantIDLocal = tenantId;
        }
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
        if (subQuery != null && subQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
            Map<Documentation, API> apiDocMap = searchAPIDoc(userRegistry, tenantIDLocal, userNameLocal, subQuery.split("=")[1]);
            result.put("apis", apiDocMap);
            /*Pagination for Document search results is not supported yet, hence length is sent as end-start*/
            if (apiDocMap.isEmpty()) {
                result.put("length", 0);
            } else {
                result.put("length", end - start);
            }
        } else if (searchQuery != null && searchQuery.startsWith(APIConstants.CONTENT_SEARCH_TYPE_PREFIX)) {
            result = searchPaginatedAPIsByContent(userRegistry, tenantIDLocal, searchQuery, start, end, isLazyLoad);
        } else {
            result = searchPaginatedAPIs(userRegistry, tenantIDLocal, searchQuery, start, end, isLazyLoad, isPublisherListing);
        }
    } catch (Exception e) {
        String msg = "Failed to Search APIs";
        throw new APIManagementException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
    return result;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) BlockConditionNotFoundException(org.wso2.carbon.apimgt.api.BlockConditionNotFoundException) PolicyNotFoundException(org.wso2.carbon.apimgt.api.PolicyNotFoundException) IOException(java.io.IOException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationNameWhiteSpaceValidationException(org.wso2.carbon.apimgt.api.ApplicationNameWhiteSpaceValidationException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) ParseException(org.json.simple.parser.ParseException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) ApplicationNameWithInvalidCharactersException(org.wso2.carbon.apimgt.api.ApplicationNameWithInvalidCharactersException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)180 UserStoreException (org.wso2.carbon.user.api.UserStoreException)88 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)83 ArrayList (java.util.ArrayList)79 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)70 PreparedStatement (java.sql.PreparedStatement)51 SQLException (java.sql.SQLException)50 IOException (java.io.IOException)49 Connection (java.sql.Connection)49 HashMap (java.util.HashMap)44 ResultSet (java.sql.ResultSet)43 JSONObject (org.json.simple.JSONObject)41 Resource (org.wso2.carbon.registry.core.Resource)40 Registry (org.wso2.carbon.registry.core.Registry)38 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)34 API (org.wso2.carbon.apimgt.api.model.API)34 Test (org.junit.Test)33 File (java.io.File)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)32 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)30