Search in sources :

Example 21 with UserRealm

use of org.wso2.carbon.user.core.UserRealm in project carbon-apimgt by wso2.

the class SelfSignupUtilTestCase method testIsUserNameWithAllowedDomainNameWhenDomainNotGiven.

@Test
public void testIsUserNameWithAllowedDomainNameWhenDomainNotGiven() throws Exception {
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = new RealmConfiguration();
    realmConfiguration.addRestrictedDomainForSelfSignUp("foo.com");
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
    boolean result = SelfSignUpUtil.isUserNameWithAllowedDomainName("john", userRealm);
    Assert.assertTrue(result);
}
Also used : RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) UserRealm(org.wso2.carbon.user.core.UserRealm) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 22 with UserRealm

use of org.wso2.carbon.user.core.UserRealm in project carbon-apimgt by wso2.

the class SelfSignupUtilTestCase method testIsUserNameWithAllowedDomainNameFalse.

@Test
public void testIsUserNameWithAllowedDomainNameFalse() throws Exception {
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = new RealmConfiguration();
    realmConfiguration.addRestrictedDomainForSelfSignUp("bar.com");
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
    boolean result = SelfSignUpUtil.isUserNameWithAllowedDomainName("bar.com/john", userRealm);
    Assert.assertFalse(result);
}
Also used : RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) UserRealm(org.wso2.carbon.user.core.UserRealm) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 23 with UserRealm

use of org.wso2.carbon.user.core.UserRealm in project carbon-apimgt by wso2.

the class APIManagerComponentTest method testShouldActivateWhenAllPrerequisitesMet.

@Test
public void testShouldActivateWhenAllPrerequisitesMet() throws Exception {
    PowerMockito.mockStatic(APIMgtDBUtil.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(AuthorizationUtils.class);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(SQLConstantManagerFactory.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    ComponentContext componentContext = Mockito.mock(ComponentContext.class);
    BundleContext bundleContext = Mockito.mock(BundleContext.class);
    APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);
    APIManagerConfigurationService configurationService = Mockito.mock(APIManagerConfigurationService.class);
    AuthorizationManager authManager = Mockito.mock(AuthorizationManager.class);
    Registry registry = Mockito.mock(Registry.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    OutputEventAdapterService adapterService = Mockito.mock(OutputEventAdapterService.class);
    ThrottleProperties throttleProperties = new ThrottleProperties();
    Mockito.doNothing().when(configuration).load(Mockito.anyString());
    Mockito.doNothing().when(authManager).authorizeRole(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Mockito.doNothing().when(adapterService).create(null);
    Mockito.when(componentContext.getBundleContext()).thenReturn(bundleContext);
    Mockito.when(registry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(configuration.getFirstProperty(Mockito.anyString())).thenReturn("").thenReturn(null);
    Mockito.when(bundleContext.registerService("", CommonConfigDeployer.class, null)).thenReturn(null);
    Mockito.when(authManager.isRoleAuthorized(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(true);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(configurationService);
    Mockito.when(serviceReferenceHolder.getOutputEventAdapterService()).thenReturn(adapterService);
    Mockito.when(configurationService.getAPIManagerConfiguration()).thenReturn(configuration);
    Mockito.when(realmService.getTenantUserRealm(Mockito.anyInt())).thenReturn(userRealm);
    Mockito.when(userRealm.getAuthorizationManager()).thenReturn(authManager);
    Mockito.when(configuration.getThrottleProperties()).thenReturn(throttleProperties);
    PowerMockito.doNothing().when(APIMgtDBUtil.class, "initialize");
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantExternalStoreConfig", Mockito.anyString());
    PowerMockito.doNothing().when(AuthorizationUtils.class, "addAuthorizeRoleListener", Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    PowerMockito.doNothing().when(SQLConstantManagerFactory.class, "initializeSQLConstantManager");
    PowerMockito.when(APIUtil.getMountedPath(null, "")).thenReturn("");
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(RegistryUtils.getAbsolutePath(null, null)).thenReturn("");
    PowerMockito.whenNew(APIManagerConfiguration.class).withAnyArguments().thenReturn(configuration);
    PowerMockito.mockStatic(ApiMgtDAO.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    APIManagerComponent apiManagerComponent = new APIManagerComponentWrapper(registry);
    GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
    Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setInitDelay(0);
    eventHubConfigurationDto.setUsername("a");
    eventHubConfigurationDto.setPassword("sss".toCharArray());
    eventHubConfigurationDto.setServiceUrl("https://localhost");
    EventHubConfigurationDto.EventHubPublisherConfiguration eventHubPublisherConfiguration = new EventHubConfigurationDto.EventHubPublisherConfiguration();
    eventHubConfigurationDto.setEventHubPublisherConfiguration(eventHubPublisherConfiguration);
    Mockito.when(config.getEventHubConfigurationDto()).thenReturn(eventHubConfigurationDto);
    try {
        apiManagerComponent.activate(componentContext);
    } catch (FileNotFoundException f) {
        // Exception thrown here means that method was continued without the configuration file
        Assert.fail("Should not throw an exception");
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) ComponentContext(org.osgi.service.component.ComponentContext) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) FileNotFoundException(java.io.FileNotFoundException) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) Registry(org.wso2.carbon.registry.api.Registry) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) OutputEventAdapterService(org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService) APIManagerComponentWrapper(org.wso2.carbon.apimgt.impl.internal.util.APIManagerComponentWrapper) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) BundleContext(org.osgi.framework.BundleContext) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 24 with UserRealm

use of org.wso2.carbon.user.core.UserRealm in project carbon-apimgt by wso2.

the class SettingsMappingUtil method fromSettingstoDTO.

public SettingsDTO fromSettingstoDTO(Boolean isUserAvailable, Boolean moneatizationEnabled, boolean recommendationEnabled, boolean anonymousEnabled, String organization) throws APIManagementException {
    SettingsDTO settingsDTO = new SettingsDTO();
    settingsDTO.setScopes(GetScopeList());
    settingsDTO.setApplicationSharingEnabled(APIUtil.isMultiGroupAppSharingEnabled());
    settingsDTO.setRecommendationEnabled(recommendationEnabled);
    settingsDTO.setMapExistingAuthApps(APIUtil.isMapExistingAuthAppsEnabled());
    settingsDTO.setMonetizationEnabled(moneatizationEnabled);
    SettingsIdentityProviderDTO identityProviderDTO = new SettingsIdentityProviderDTO();
    identityProviderDTO.setExternal(APIUtil.getIdentityProviderConfig() != null);
    settingsDTO.setIdentityProvider(identityProviderDTO);
    settingsDTO.setIsAnonymousModeEnabled(anonymousEnabled);
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    boolean enableChangePassword = Boolean.parseBoolean(config.getFirstProperty(APIConstants.ENABLE_CHANGE_PASSWORD));
    settingsDTO.setIsPasswordChangeEnabled(enableChangePassword);
    String username = RestApiCommonUtil.getLoggedInUsername();
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    String userStorePasswordPattern = null;
    String passwordPolicyPattern = null;
    int passwordPolicyMinLength = -1;
    int passwordPolicyMaxLength = -1;
    try {
        // Get password pattern from the UserStoreManager configuration
        RealmConfiguration realmConfiguration = null;
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        if (realmService != null && tenantId != MultitenantConstants.INVALID_TENANT_ID) {
            UserStoreManager userStoreManager = null;
            userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
            realmConfiguration = userStoreManager.getRealmConfiguration();
        }
        if (realmConfiguration != null) {
            String passwordJavaRegEx = realmConfiguration.getUserStoreProperty(APIConstants.PASSWORD_JAVA_REGEX_PROPERTY);
            if (passwordJavaRegEx != null && !passwordJavaRegEx.trim().isEmpty()) {
                userStorePasswordPattern = passwordJavaRegEx;
            }
        }
        // Get password pattern from the Password policy
        Property passwordPolicyEnabledProperty = FrameworkUtils.getResidentIdpConfiguration(APIConstants.IS_PASSWORD_POLICY_ENABLED_PROPERTY, tenantDomain);
        boolean isPasswordPolicyEnabled = Boolean.parseBoolean(passwordPolicyEnabledProperty.getValue());
        if (isPasswordPolicyEnabled) {
            passwordPolicyPattern = FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_PATTERN_PROPERTY, tenantDomain).getValue();
            passwordPolicyMinLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MIN_LENGTH_PROPERTY, tenantDomain).getValue());
            passwordPolicyMaxLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MAX_LENGTH_PROPERTY, tenantDomain).getValue());
        }
    } catch (UserStoreException e) {
        String errorMessage = "Error occurred in getting userRealm for the tenant: " + tenantId;
        throw new APIManagementException(errorMessage, e);
    } catch (FrameworkException e) {
        String errorMessage = "Error occurred in getting Resident Idp Configurations for tenant: " + tenantId;
        throw new APIManagementException(errorMessage, e);
    }
    settingsDTO.setUserStorePasswordPattern(userStorePasswordPattern);
    settingsDTO.setPasswordPolicyPattern(passwordPolicyPattern);
    settingsDTO.setPasswordPolicyMinLength(passwordPolicyMinLength);
    settingsDTO.setPasswordPolicyMaxLength(passwordPolicyMaxLength);
    if (isUserAvailable) {
        settingsDTO.setGrantTypes(APIUtil.getGrantTypes());
        Map<String, Environment> environments = APIUtil.getEnvironments(organization);
        if (environments.isEmpty()) {
            settingsDTO.apiGatewayEndpoint("http://localhost:8280, https://localhost:8243");
        } else {
            for (Map.Entry<String, Environment> entry : environments.entrySet()) {
                Environment environment = environments.get(entry.getKey());
                if (environment.isDefault()) {
                    settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
                    break;
                }
            }
            if (settingsDTO.getApiGatewayEndpoint() == null) {
                Map.Entry<String, Environment> entry = environments.entrySet().iterator().next();
                Environment environment = environments.get(entry.getKey());
                settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
            }
        }
    }
    return settingsDTO;
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) SettingsIdentityProviderDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SettingsIdentityProviderDTO) RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) SettingsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SettingsDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Environment(org.wso2.carbon.apimgt.api.model.Environment) Property(org.wso2.carbon.identity.application.common.model.Property) Map(java.util.Map)

Example 25 with UserRealm

use of org.wso2.carbon.user.core.UserRealm in project core-util by WSO2Telco.

the class BasicAuthenticator method isAuthenticatedUser.

public boolean isAuthenticatedUser(String userName, String password) {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
    RegistryService registryService = (RegistryService) carbonContext.getOSGiService(RegistryService.class, null);
    String tenantDomain = MultitenantUtils.getTenantDomain(userName);
    try {
        UserRealm userRealm = null;
        userRealm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain);
        if (userRealm == null) {
            log.error("invalid domain or unactivated tenant login");
            return false;
        }
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(userName);
        if (userRealm.getUserStoreManager().authenticate(tenantAwareUsername, password)) {
            return true;
        } else {
            log.error("authentication failed. please check your username/password");
            return false;
        }
    } catch (CarbonException | UserStoreException e) {
        log.error("authentication failed for user : " + userName, e);
        return false;
    }
}
Also used : UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) CarbonException(org.wso2.carbon.CarbonException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) RegistryService(org.wso2.carbon.registry.core.service.RegistryService)

Aggregations

RealmService (org.wso2.carbon.user.core.service.RealmService)34 UserRealm (org.wso2.carbon.user.core.UserRealm)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)23 Test (org.junit.Test)21 UserRealm (org.wso2.carbon.user.api.UserRealm)20 UserStoreException (org.wso2.carbon.user.api.UserStoreException)18 TenantManager (org.wso2.carbon.user.core.tenant.TenantManager)15 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)14 UserStoreManager (org.wso2.carbon.user.core.UserStoreManager)13 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)11 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)10 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)9 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)9 UserStoreException (org.wso2.carbon.user.core.UserStoreException)7 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)6 AuthenticationFailedException (org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException)6 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)5 RealmConfiguration (org.wso2.carbon.user.api.RealmConfiguration)5 Matchers.anyString (org.mockito.Matchers.anyString)4 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)4