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

The following examples show how to use org.wso2.carbon.utils.multitenancy.MultitenantUtils. 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: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices when user is the device admin")
public void testGetDevicesWhenUserIsAdmin() throws DeviceAccessAuthorizationException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, null, false, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
    response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, null, false, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
 
Example #2
Source File: ApiPermissionFilter.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the client is authorized with the given permission and action.
 * @param permission           Carbon permission that requires for the use
 * @param action               Carbon permission action that requires for the given permission.
 * @return boolean - true if user is authorized else return false.
 */
private boolean isUserAuthorized(String permission, String action) {
    PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    String username = context.getUsername();
    try {
        UserRealm userRealm = APIUtil.getRealmService().getTenantUserRealm(PrivilegedCarbonContext
                            .getThreadLocalCarbonContext().getTenantId());
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        boolean status =  userRealm.getAuthorizationManager()
                .isUserAuthorized(tenantAwareUsername, permission, action);
        if (!status) {
            String[] roles = userRealm.getUserStoreManager().getRoleListOfUser(tenantAwareUsername);
            for (String role : roles) {
                if (role.equals(DEFAULT_ADMIN_ROLE)) {
                    return true;
                }
            }
        }
        return status;
    } catch (UserStoreException e) {
        String errorMsg = String.format("Unable to authorize the user : %s", username);
        log.error(errorMsg, e);
        return false;
    }
}
 
Example #3
Source File: UserSignUpApprovalWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Execute the User self sign up workflow approval process.
 *
 * @param workflowDTO
 */
@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {

    if (log.isDebugEnabled()) {
        log.debug("Executing User SignUp Webservice Workflow for " + workflowDTO.getWorkflowReference());
    }
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(workflowDTO.getWorkflowReference());
    String message = "Approve APIStore signup request done by " + tenantAwareUserName + " from the tenant domain " +
            workflowDTO.getTenantDomain();
    workflowDTO.setWorkflowDescription(message);
    workflowDTO.setProperties("tenantAwareUserName", tenantAwareUserName);
    workflowDTO.setProperties("tenantDomain", workflowDTO.getTenantDomain());
    super.execute(workflowDTO);
    return new GeneralWorkflowResponse();
}
 
Example #4
Source File: CarbonRepositoryUtils.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Create and initialize a new DeploymentSynchronizer for the Carbon repository of the
 * specified tenant. This method first attempts to load the synchronizer configuration
 * from the registry. If a configuration does not exist in the registry, it will get the
 * configuration from the global ServerConfiguration of Carbon. Note that this method
 * does not start the created synchronizers. It only creates and initializes them using
 * the available configuration settings.
 *
 * @param tenantId ID of the tenant
 * @return a DeploymentSynchronizer instance or null if the synchronizer is disabled
 * @throws org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizerException If an error occurs while initializing the synchronizer
 */
public static DeploymentSynchronizer newCarbonRepositorySynchronizer(int tenantId)
        throws DeploymentSynchronizerException {

    DeploymentSynchronizerConfiguration config = getActiveSynchronizerConfiguration(tenantId);

    if (config.isEnabled()) {
        String filePath = MultitenantUtils.getAxis2RepositoryPath(tenantId);

        ArtifactRepository artifactRepository = createArtifactRepository(
                config.getRepositoryType());
        artifactRepository.init(tenantId);
        DeploymentSynchronizer synchronizer = DeploymentSynchronizationManager.getInstance().
                createSynchronizer(tenantId, artifactRepository, filePath);
        synchronizer.setAutoCommit(config.isAutoCommit());
        synchronizer.setAutoCheckout(config.isAutoCheckout());
        synchronizer.setPeriod(config.getPeriod());
        synchronizer.setUseEventing(config.isUseEventing());

        if (log.isDebugEnabled()) {
            log.debug("Registered file path:" + filePath + " for tenant: " + tenantId);
        }
        return synchronizer;
    }
    return null;
}
 
Example #5
Source File: IdentityManagementServiceUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Build user object from complete username
 * @param userName
 * @return
 */
public User getUser(String userName) {

    if (userName == null) {
        return null;
    }

    String userStoreDomain = extractDomainFromName(userName);
    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    String userNameWithoutTenantDomainAndUserStoreDomain = MultitenantUtils
            .getTenantAwareUsername(UserCoreUtil.removeDomainFromName(userName));

    User user = new User();
    user.setUsername(userNameWithoutTenantDomainAndUserStoreDomain);
    user.setRealm(userStoreDomain);
    user.setTenantDomain(tenantDomain);

    return user;
}
 
Example #6
Source File: IdentityManagementServiceUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Build a user object from tenant domain and username.
 *
 * @param username username provided by user
 * @param tenantDomain tenant domain of the application
 * @return User
 */
public User resolveUser(String username, String tenantDomain, boolean isSaaSEnabled) {

    if (username == null) {
        return null;
    }
    String userStoreDomain = extractDomainFromName(username);
    User user = new User();
    user.setUsername(MultitenantUtils
            .getTenantAwareUsername(UserCoreUtil.removeDomainFromName(username)));
    if (isSaaSEnabled) {
        user.setTenantDomain(MultitenantUtils.getTenantDomain(username));
    } else {
        user.setTenantDomain(tenantDomain);
    }
    user.setRealm(userStoreDomain);
    return user;
}
 
Example #7
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Check the case sensitivity of the user store in which the user is in.
 *
 * @param username Full qualified username
 * @return
 */
public static boolean isUserStoreInUsernameCaseSensitive(String username) {

    boolean isUsernameCaseSensitive = true;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = IdentityTenantUtil.getRealmService().getTenantManager().getTenantId(tenantDomain);
        return isUserStoreInUsernameCaseSensitive(username, tenantId);
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as case " +
                    "sensitive.");
        }
    }
    return isUsernameCaseSensitive;
}
 
Example #8
Source File: CarbonUserRealmHostObject.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static boolean jsFunction_isUserAuthorized(Context cx,
		Scriptable thisObj, Object[] args, Function funObj) throws Exception {
	boolean isAuthorized = false;
	int argLength = args.length;
	if (argLength != 3) {
		throw new ScriptException("Invalid arguments.");
	}
	String user = (String) args[0];
	String userName = MultitenantUtils.getTenantAwareUsername(user);
	String domainName = MultitenantUtils.getTenantDomain(user);
	RealmService service = ServiceHodler.getRealmService();
	int tenantId = service.getTenantManager().getTenantId(domainName);
	UserRealm realm = service.getTenantUserRealm(tenantId);
	isAuthorized = realm.getAuthorizationManager().isUserAuthorized(userName, (String) args[1], (String) args[2]);
	return isAuthorized;
}
 
Example #9
Source File: ApiProductsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override public Response apiProductsApiProductIdGet(String apiProductId, String accept, String ifNoneMatch,
        MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        if (log.isDebugEnabled()) {
            log.debug("API Product request: Id " +apiProductId + " by " + username);
        }
        APIProduct apiProduct = apiProvider.getAPIProductbyUUID(apiProductId, tenantDomain);
        if (apiProduct == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, log);
        }

        APIProductDTO createdApiProductDTO = APIMappingUtil.fromAPIProducttoDTO(apiProduct);
        return Response.ok().entity(createdApiProductDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API Product from Id  : " + apiProductId ;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #10
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices when user is unauthorized.")
public void testGetDevicesWhenUserIsUnauthorized() throws Exception {
    PowerMockito.spy(MultitenantUtils.class);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    PowerMockito.doReturn(TENANT_AWARE_USERNAME)
            .when(MultitenantUtils.class, "getTenantAwareUsername", DEFAULT_USERNAME);
    PowerMockito.doReturn("[email protected]").when(MultitenantUtils.class, "getTenantAwareUsername", "newuser");
    Mockito.when(this.deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(false);

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS, 1,
                    null, null, false, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode());
    Mockito.reset(this.deviceAccessAuthorizationService);
}
 
Example #11
Source File: LocalOAuthValidator.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
 * containing the validity and user details if valid.
 *
 * @param token which need to be validated.
 * @return OAuthValidationResponse with the validated results.
 */
public OAuthValidationResponse validateToken(String token) throws RemoteException{
    OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
    OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken =
            validationRequest.new OAuth2AccessToken();
    accessToken.setTokenType(BEARER_TOKEN_TYPE);
    accessToken.setIdentifier(token);
    validationRequest.setAccessToken(accessToken);
    OAuth2TokenValidationResponseDTO tokenValidationResponse = OAuthAuthenticatorDataHolder.getInstance().
            getOAuth2TokenValidationService().findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
    boolean isValid = tokenValidationResponse.isValid();
    String userName = null;
    String tenantDomain = null;
    if (isValid) {
        userName = MultitenantUtils.getTenantAwareUsername(
                tokenValidationResponse.getAuthorizedUser());
        tenantDomain =
                MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser());
    }
    return new OAuthValidationResponse(userName, tenantDomain, isValid);
}
 
Example #12
Source File: DeploymentSynchronizerAdmin.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public void disableSynchronizerForCarbonRepository() throws DeploymentSynchronizerException {

        int tenantId = MultitenantUtils.getTenantId(getConfigContext());
        try {
            DeploymentSynchronizerConfiguration config =
                    CarbonRepositoryUtils.getActiveSynchronizerConfiguration(tenantId);
            if (config == null || !config.isEnabled()) {
                log.warn("Attempted to disable an already disabled deployment synchronizer");
                return;
            }
            config.setEnabled(false);
            CarbonRepositoryUtils.persistConfiguration(config, tenantId);
        } catch (RegistryException e) {
            handleException("Error while persisting the deployment synchronizer configuration", e);
        }

        String filePath = CarbonRepositoryUtils.getCarbonRepositoryFilePath(getConfigContext());
        DeploymentSynchronizer synchronizer =  DeploymentSynchronizationManager.getInstance().
                deleteSynchronizer(filePath);
        if (synchronizer != null) {
            synchronizer.stop();
        }
    }
 
Example #13
Source File: LocalOAuthValidator.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
 * containing the validity and user details if valid.
 *
 * @param token which need to be validated.
 * @return OAuthValidationResponse with the validated results.
 */
public OAuthValidationResponse validateToken(String token) {
    OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
    OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken =
            validationRequest.new OAuth2AccessToken();
    accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE);
    accessToken.setIdentifier(token);
    validationRequest.setAccessToken(accessToken);
    OAuth2TokenValidationResponseDTO tokenValidationResponse = OAuthAuthenticatorDataHolder.getInstance().
            getOAuth2TokenValidationService().findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
    boolean isValid = tokenValidationResponse.isValid();
    String userName = null;
    String tenantDomain = null;
    if (isValid) {
        userName = MultitenantUtils.getTenantAwareUsername(
                tokenValidationResponse.getAuthorizedUser());
        tenantDomain =
                MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser());
    }
    return new OAuthValidationResponse(userName, tenantDomain, isValid);
}
 
Example #14
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices with IF-Modified-Since")
public void testGetDevicesWithModifiedSince() {
    String ifModifiedSince = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date());
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, ifModifiedSince, false, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
    response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, ifModifiedSince, true, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
    response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, "ErrorModifiedSince", false, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
 
Example #15
Source File: RegularExpressionProtector.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Using Regex Threat Protector mediator will be restricted to the tenants defined by the system property
 * 'regexThreatProtectorEnabledTenants' as a list of comma separated values and super tenant. If this system
 * property is not defined, then this restriction will not be applied at all. If invoked API is existing within a
 * tenant, which was defined in this list, this method returns true. If this system property is not defined, this
 * check won't be done and so will return true, hence all the tenants will be allowed to use this mediator
 *
 * @param messageContext contains the message properties of the relevant API request which was
 *                       enabled the regexValidator message mediation in flow.
 * @return true if the tenant is allowed to use this Mediator
 */
private boolean isTenantAllowed(MessageContext messageContext) {
    String allowedTenants = System.getProperty(APIMgtGatewayConstants.REGEX_THREAT_PROTECTOR_ENABLED_TENANTS);
    if (allowedTenants == null) {
        return true;
    }
    List<String> allowedTenantsList = Arrays.asList(allowedTenants.split(","));
    String tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(RESTUtils.getFullRequestPath
            (messageContext));
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    if (!allowedTenantsList.contains(tenantDomain) &&
            !(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME).equals(tenantDomain)) {
        GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE,
                "This tenant is not allowed to use Regular Expression Threat Protector mediator");
        return false;
    }
    return true;
}
 
Example #16
Source File: IdentityUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Check the case sensitivity of the user store in which the user is in.
 *
 * @param username Full qualified username
 * @return
 */
public static boolean isUserStoreInUsernameCaseSensitive(String username) {

    boolean isUsernameCaseSensitive = true;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = IdentityTenantUtil.getRealmService().getTenantManager().getTenantId(tenantDomain);
        return isUserStoreInUsernameCaseSensitive(username, tenantId);
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as case " +
                    "sensitive.");
        }
    }
    return isUsernameCaseSensitive;
}
 
Example #17
Source File: IdentityProviderData.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public String getTenantDomain() throws IdentityProviderException {
    if (this.authMechanism == IdentityConstants.AUTH_TYPE_SELF_ISSUED) { //only for tenant 0
        return null;
    }

    if (userIdentifier == null) {
        // auth type is not self issued and still the user identifier is null. 
        // this is a invalid case
        throw new IllegalStateException("User identifier must NOT be null");
    }

    String domain = null;
    domain = MultitenantUtils.getTenantDomain(userIdentifier);
    return domain;
}
 
Example #18
Source File: AbstractKeyValidationHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private boolean validateSubscriptionDetails(String context, String version, String consumerKey, String keyManager,
        APIKeyValidationInfoDTO infoDTO) throws APIManagementException {
    boolean defaultVersionInvoked = false;
    String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (apiTenantDomain == null) {
        apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    int apiOwnerTenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
    // Check if the api version has been prefixed with _default_
    if (version != null && version.startsWith(APIConstants.DEFAULT_VERSION_PREFIX)) {
        defaultVersionInvoked = true;
        // Remove the prefix from the version.
        version = version.split(APIConstants.DEFAULT_VERSION_PREFIX)[1];
    }

    validateSubscriptionDetails(infoDTO, context, version, consumerKey, keyManager, defaultVersionInvoked);
    return infoDTO.isAuthorized();
}
 
Example #19
Source File: OpenIDProviderService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Returns RP DTO for the given OpenID and RP
 *
 * @param openID
 * @param rpUrl
 * @return openIDUserRPDTO
 * @throws IdentityProviderException
 */
public OpenIDUserRPDTO getOpenIDUserRPInfo(String openID, String rpUrl) throws IdentityProviderException {

    String userName = null;
    try {
        userName = OpenIDUtil.getUserName(openID);
    } catch (MalformedURLException e) {
        throw new IdentityProviderException("Failed to get username from OpenID " + openID, e);
    }
    String domainName = MultitenantUtils.getTenantDomain(userName);
    int tenantId = IdentityTenantUtil.getTenantId(domainName);

    OpenIDUserRPDO rpdo = null;
    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    rpdo = dao.getOpenIDUserRP(userName, rpUrl, tenantId);
    if (rpdo == null) {
        return null;
    }
    return new OpenIDUserRPDTO(rpdo);
}
 
Example #20
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRoleNamesNonSuperTenant() throws Exception {
    String userName = "John";

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);

    String[] roleNames = {"role1", "role2"};

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Mockito.when(MultitenantUtils.getTenantDomain(userName)).
            thenReturn("test.com");
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.getRoleNames()).thenReturn(roleNames);

    Assert.assertEquals(roleNames, APIUtil.getRoleNames(userName));
}
 
Example #21
Source File: Utils.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public static int getTenantIdOFUser(String username) throws AuthenticationException {
    int tenantId = 0;
    String domainName = MultitenantUtils.getTenantDomain(username);
    if (domainName != null) {
        try {
            TenantManager tenantManager = AuthenticatorFrameworkDataHolder.getInstance().getRealmService()
                    .getTenantManager();
            tenantId = tenantManager.getTenantId(domainName);
        } catch (UserStoreException e) {
            String errorMsg = "Error when getting the tenant id from the tenant domain : " +
                    domainName;
            log.error(errorMsg, e);
            throw new AuthenticationException(errorMsg, e);
        }
    }
    return tenantId;
}
 
Example #22
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices when unable to retrieve devices")
public void testGetDeviceServerErrorWhenGettingDeviceList() throws DeviceManagementException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    Mockito.when(this.deviceManagementProviderService
            .getAllDevices(Mockito.any(PaginationRequest.class), Mockito.anyBoolean()))
            .thenThrow(new DeviceManagementException());

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, null, false, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    Mockito.reset(this.deviceManagementProviderService);
}
 
Example #23
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices when user is the device admin")
public void testGetDevicesWhenUserIsAdmin() throws DeviceAccessAuthorizationException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, null, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
    response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, null, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
 
Example #24
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private static void setEndpointSecurityFromModelToApiDTO(API api, APIDTO dto)
        throws APIManagementException {

    if (api.isEndpointSecured()) {
        APIEndpointSecurityDTO securityDTO = new APIEndpointSecurityDTO();
        securityDTO.setType(APIEndpointSecurityDTO.TypeEnum.BASIC); //set default as basic
        securityDTO.setUsername(api.getEndpointUTUsername());
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId()
                .getProviderName()));
        if (checkEndpointSecurityPasswordEnabled(tenantDomain)) {
            securityDTO.setPassword(api.getEndpointUTPassword());
        } else {
            securityDTO.setPassword(""); //Do not expose password
        }
        if (api.isEndpointAuthDigest()) {
            securityDTO.setType(APIEndpointSecurityDTO.TypeEnum.DIGEST);
        }
        dto.setEndpointSecurity(securityDTO);
    }
}
 
Example #25
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices with IF-Modified-Since")
public void testGetDevicesWithModifiedSince() {
    String ifModifiedSince = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date());
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, ifModifiedSince, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
    response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, ifModifiedSince, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
    response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, "ErrorModifiedSince", 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
 
Example #26
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices with Since")
public void testGetDevicesWithSince() {
    String since = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date());
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, since, null, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
    response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, since, null, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
    response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, "ErrorSince", null, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
 
Example #27
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices when unable to retrieve devices")
public void testGetDeviceServerErrorWhenGettingDeviceList() throws DeviceManagementException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    Mockito.when(this.deviceManagementProviderService
            .getAllDevices(Mockito.any(PaginationRequest.class))).thenThrow(new DeviceManagementException());

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, null, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    Mockito.reset(this.deviceManagementProviderService);
}
 
Example #28
Source File: DeviceManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Testing get devices when unable to check if the user is the admin user")
public void testGetDevicesServerErrorWhenCheckingAdminUser() throws DeviceAccessAuthorizationException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
            .toReturn(this.deviceAccessAuthorizationService);
    PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
            .toReturn(TENANT_AWARE_USERNAME);
    PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
    Mockito.when(this.deviceAccessAuthorizationService.isDeviceAdminUser())
            .thenThrow(new DeviceAccessAuthorizationException());

    Response response = this.deviceManagementService
            .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
                    DEFAULT_STATUS, 1, null, null, 10, 5);
    Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    Mockito.reset(this.deviceAccessAuthorizationService);
}
 
Example #29
Source File: OpenIDProviderService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * A new method to do XMPP based authentication for a given user
 *
 * @param userId
 * @return
 * @throws IdentityProviderException
 */
public boolean doXMPPBasedMultiFactorAuthForInfocard(String userId) throws IdentityProviderException {

    boolean authenticationStatus = true;
    XMPPSettingsDO xmppSettingsDO = null;
    try {
        IdentityPersistenceManager persistenceManager = IdentityPersistenceManager.getPersistanceManager();
        xmppSettingsDO = persistenceManager.getXmppSettings(IdentityTenantUtil.getRegistry(null, userId),
                                                            MultitenantUtils.getTenantAwareUsername(userId));
    } catch (IdentityException e) {
        throw new IdentityProviderException("Error while retriving XMPP settings", e);
    }

    // attempts to do multi-factor authentication, if the user has enabled
    // it.
    if (xmppSettingsDO != null && xmppSettingsDO.isXmppEnabled()) {
        MPAuthenticationProvider mpAuthenticationProvider = new MPAuthenticationProvider(xmppSettingsDO);
        authenticationStatus = mpAuthenticationProvider.authenticate();
    }

    if (log.isInfoEnabled()) {
        log.info("XMPP Multifactor Authentication was completed Successfully.");
    }

    return authenticationStatus;
}
 
Example #30
Source File: HostUtil.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * adding domain for service in registry
 * 
 * @param hostName
 * @param url
 * @throws UrlMapperException
 */
public static void addDomainToServiceEpr(String hostName, String url, String appType) throws UrlMapperException {

	// if the request if from tenant
	String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
	if (url.contains("/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/")) {
		tenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(url);
	}

	if (isServiceURLPattern(url)) {
		url = getServiceEndpoint(url);
	}
	try {
		// add entry to registry with the tenant domain if exist in the uri
		registryManager.addEprToRegistry(hostName, url, tenantDomain, appType);
		URLMappingHolder.getInstance().putUrlMappingForApplication(hostName,
				url);
           log.info("mapping added to service:***********: " + hostName + "******: " + url );
           //adding mapping to cluster message
           VirtualHostClusterUtil.addServiceMappingToCluster(hostName, url);
           addServiceParameter(url);
	} catch (Exception e) {
		log.error("error in adding the domain to the resitry", e);
		throw new UrlMapperException("error in adding the domain to the resitry");
	}
}