org.wso2.carbon.user.api.RealmConfiguration Java Examples

The following examples show how to use org.wso2.carbon.user.api.RealmConfiguration. 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: DirectoryServerManager.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the regular expression which defines the format of the service principle.
 * Current we use following like format,
 * ftp/localhost
 *
 * @return Service principle name format as a regular expression.
 * @throws DirectoryServerManagerException If unable to retrieve RealmConfiguration.
 */
public String getServiceNameConformanceRegularExpression() throws DirectoryServerManagerException {

    try {
        RealmConfiguration userStoreConfigurations = this.getUserRealm().getRealmConfiguration();
        if (userStoreConfigurations != null) {
            String serviceNameRegEx = userStoreConfigurations.getUserStoreProperty(
                    LDAPServerManagerConstants.SERVICE_PRINCIPLE_NAME_REGEX_PROPERTY);
            if (serviceNameRegEx == null) {
                return LDAPServerManagerConstants.DEFAULT_SERVICE_NAME_REGULAR_EXPRESSION;
            } else {
                log.info("Service name format is " + serviceNameRegEx);
                return serviceNameRegEx;
            }
        }
    } catch (UserStoreException e) {
        log.error("Unable to retrieve service name format.", e);
        throw new DirectoryServerManagerException("Unable to retrieve service name format.", e);
    }

    return LDAPServerManagerConstants.DEFAULT_SERVICE_NAME_REGULAR_EXPRESSION;
}
 
Example #2
Source File: UserStoreConfgurationContextObserver.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public void terminatingConfigurationContext(ConfigurationContext context) {
    try {
        org.wso2.carbon.user.api.UserRealm tenantRealm = CarbonContext
                .getThreadLocalCarbonContext().getUserRealm();
        RealmConfiguration realmConfig = tenantRealm.getRealmConfiguration();
        AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) tenantRealm
                .getUserStoreManager();
        userStoreManager.clearAllSecondaryUserStores();
        realmConfig.setSecondaryRealmConfig(null);
        userStoreManager.setSecondaryUserStoreManager(null);
        log.info("Unloaded all secondary user stores for tenant "
                + CarbonContext.getThreadLocalCarbonContext().getTenantId());
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }
}
 
Example #3
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public static UserStoreCountRetriever getUserStoreCountRetrieverService()
        throws UserStoreCounterException {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    List<Object> countRetrieverFactories = ctx.getOSGiServices(AbstractCountRetrieverFactory.class, null);
    RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
    RealmConfiguration realmConfiguration = realmService.getBootstrapRealmConfiguration();
    String userStoreType;
    //Ignoring Sonar warning as getUserStoreClass() returning string name of the class. So cannot use 'instanceof'.
    if (JDBCUserStoreManager.class.getName().equals(realmConfiguration.getUserStoreClass())) {
        userStoreType = JDBCCountRetrieverFactory.JDBC;
    } else {
        userStoreType = InternalCountRetrieverFactory.INTERNAL;
    }
    AbstractCountRetrieverFactory countRetrieverFactory = null;
    for (Object countRetrieverFactoryObj : countRetrieverFactories) {
        countRetrieverFactory = (AbstractCountRetrieverFactory) countRetrieverFactoryObj;
        if (userStoreType.equals(countRetrieverFactory.getCounterType())) {
            break;
        }
    }
    if (countRetrieverFactory == null) {
        return null;
    }
    return countRetrieverFactory.buildCountRetriever(realmConfiguration);
}
 
Example #4
Source File: JDBCUserStoreCountRetriever.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private Connection getDBConnection(RealmConfiguration realmConfiguration) throws SQLException, UserStoreException {

        Connection dbConnection = null;
        DataSource dataSource = DatabaseUtil.createUserStoreDataSource(realmConfiguration);

        if (dataSource != null) {
            dbConnection = DatabaseUtil.getDBConnection(dataSource);
        }

        //if primary user store, DB connection can be same as realm data source.
        if (dbConnection == null && realmConfiguration.isPrimary()) {
            dbConnection = IdentityDatabaseUtil.getUserDBConnection();
        } else if (dbConnection == null) {
            throw new UserStoreException("Could not create a database connection to " +
                    realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME));
        } else {
            // db connection is present
        }
        dbConnection.setAutoCommit(false);
        if (dbConnection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
            dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        }
        return dbConnection;
    }
 
Example #5
Source File: UserManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() throws UserStoreException {
    initMocks(this);
    userManagementService = new UserManagementServiceImpl();
    userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS);
    deviceManagementProviderService = Mockito
            .mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
    userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.doReturn(null).when(realmConfiguration).getSecondaryRealmConfig();
    Mockito.doReturn(realmConfiguration).when(userRealm).getRealmConfiguration();
    enrollmentInvitation = new EnrollmentInvitation();
    List<String> recipients = new ArrayList<>();
    recipients.add(TEST_USERNAME);
    enrollmentInvitation.setDeviceType("android");
    enrollmentInvitation.setRecipients(recipients);
    userList = new ArrayList<>();
    userList.add(TEST_USERNAME);
}
 
Example #6
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public static UserStoreCountRetriever getUserStoreCountRetrieverService()
        throws UserStoreCounterException, UserStoreException {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    List<Object> countRetrieverFactories = ctx.getOSGiServices(AbstractCountRetrieverFactory.class, null);
    RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
    RealmConfiguration realmConfiguration = realmService.getBootstrapRealmConfiguration();
    String userStoreType;
    if(DeviceMgtAPIUtils.getUserStoreManager() instanceof JDBCUserStoreManager) {
        userStoreType = JDBCCountRetrieverFactory.JDBC;
    } else {
        userStoreType = InternalCountRetrieverFactory.INTERNAL;
    }
    AbstractCountRetrieverFactory countRetrieverFactory = null;
    for (Object countRetrieverFactoryObj : countRetrieverFactories) {
        countRetrieverFactory = (AbstractCountRetrieverFactory) countRetrieverFactoryObj;
        if (userStoreType.equals(countRetrieverFactory.getCounterType())) {
            break;
        }
    }
    if (countRetrieverFactory == null) {
        return null;
    }
    return countRetrieverFactory.buildCountRetriever(realmConfiguration);
}
 
Example #7
Source File: UserManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() throws UserStoreException {
    initMocks(this);
    userManagementService = new UserManagementServiceImpl();
    userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS);
    deviceManagementProviderService = Mockito
            .mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
    userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.doReturn(null).when(realmConfiguration).getSecondaryRealmConfig();
    Mockito.doReturn(realmConfiguration).when(userRealm).getRealmConfiguration();
    enrollmentInvitation = new EnrollmentInvitation();
    List<String> recipients = new ArrayList<>();
    recipients.add(TEST_USERNAME);
    enrollmentInvitation.setDeviceType("android");
    enrollmentInvitation.setRecipients(recipients);
    userList = new ArrayList<>();
    userList.add(TEST_USERNAME);
}
 
Example #8
Source File: DirectoryServerManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the regular expression which defines the format of the service principle, password.
 *
 * @return Regular expression.
 * @throws DirectoryServerManagerException If unable to get RealmConfiguration.
 */
public String getPasswordConformanceRegularExpression() throws DirectoryServerManagerException {

    try {
        RealmConfiguration userStoreConfigurations = this.getUserRealm().getRealmConfiguration();
        if (userStoreConfigurations != null) {
            String passwordRegEx = userStoreConfigurations.getUserStoreProperty(
                    LDAPServerManagerConstants.SERVICE_PASSWORD_REGEX_PROPERTY);
            if (passwordRegEx == null) {
                return LDAPServerManagerConstants.DEFAULT_PASSWORD_REGULAR_EXPRESSION;
            } else {
                log.info("Service password format is " + passwordRegEx);
                return passwordRegEx;
            }
        }
    } catch (UserStoreException e) {
        log.error("Unable to retrieve service password format.", e);
        throw new DirectoryServerManagerException("Unable to retrieve service password format.", e);
    }

    return LDAPServerManagerConstants.DEFAULT_PASSWORD_REGULAR_EXPRESSION;
}
 
Example #9
Source File: DirectoryServerManager.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the regular expression which defines the format of the service principle.
 * Current we use following like format,
 * ftp/localhost
 *
 * @return Service principle name format as a regular expression.
 * @throws DirectoryServerManagerException If unable to retrieve RealmConfiguration.
 */
public String getServiceNameConformanceRegularExpression() throws DirectoryServerManagerException {

    try {
        RealmConfiguration userStoreConfigurations = this.getUserRealm().getRealmConfiguration();
        if (userStoreConfigurations != null) {
            String serviceNameRegEx = userStoreConfigurations.getUserStoreProperty(
                    LDAPServerManagerConstants.SERVICE_PRINCIPLE_NAME_REGEX_PROPERTY);
            if (serviceNameRegEx == null) {
                return LDAPServerManagerConstants.DEFAULT_SERVICE_NAME_REGULAR_EXPRESSION;
            } else {
                log.info("Service name format is " + serviceNameRegEx);
                return serviceNameRegEx;
            }
        }
    } catch (UserStoreException e) {
        log.error("Unable to retrieve service name format.", e);
        throw new DirectoryServerManagerException("Unable to retrieve service name format.", e);
    }

    return LDAPServerManagerConstants.DEFAULT_SERVICE_NAME_REGULAR_EXPRESSION;
}
 
Example #10
Source File: UserStoreCountUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Create an instance of the given count retriever class
 *
 * @param domain
 * @return
 * @throws UserStoreCounterException
 */
public static UserStoreCountRetriever getCounterInstanceForDomain(String domain) throws UserStoreCounterException {
    if (StringUtils.isEmpty(domain)) {
        domain = IdentityUtil.getPrimaryDomainName();
    }

    RealmConfiguration realmConfiguration = getUserStoreList().get(domain);
    if (realmConfiguration != null && realmConfiguration.getUserStoreProperty(COUNT_RETRIEVER_CLASS) != null) {
        String retrieverType = realmConfiguration.getUserStoreProperty(COUNT_RETRIEVER_CLASS);
        UserStoreCountRetriever userStoreCountRetriever = UserStoreCountDataHolder.getInstance()
                .getCountRetrieverFactories().get(retrieverType).buildCountRetriever(realmConfiguration);
        if (userStoreCountRetriever == null) {
            throw new UserStoreCounterException(
                    "Could not create an instance of class: " + retrieverType + " for " +
                            "the domain: " + domain);
        }
        return userStoreCountRetriever;
    } else {
        return null;
    }
}
 
Example #11
Source File: UserStoreCountUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static boolean isUserStoreEnabled(String domain) throws UserStoreCounterException {

        RealmConfiguration realmConfiguration;
        boolean isEnabled = false;
        try {
            realmConfiguration = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration();

            do {
                String userStoreDomain = realmConfiguration.
                        getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

                if (domain.equals(userStoreDomain)) {
                    isEnabled = !Boolean.valueOf(realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.
                            USER_STORE_DISABLED));
                    break;
                }
                realmConfiguration = realmConfiguration.getSecondaryRealmConfig();
            } while (realmConfiguration != null);

        } catch (UserStoreException e) {
            throw new UserStoreCounterException("Error occurred while getting Secondary Realm Configuration", e);
        }
        return isEnabled;
    }
 
Example #12
Source File: DirectoryServerManager.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the regular expression which defines the format of the service principle, password.
 *
 * @return Regular expression.
 * @throws DirectoryServerManagerException If unable to get RealmConfiguration.
 */
public String getPasswordConformanceRegularExpression() throws DirectoryServerManagerException {

    try {
        RealmConfiguration userStoreConfigurations = this.getUserRealm().getRealmConfiguration();
        if (userStoreConfigurations != null) {
            String passwordRegEx = userStoreConfigurations.getUserStoreProperty(
                    LDAPServerManagerConstants.SERVICE_PASSWORD_REGEX_PROPERTY);
            if (passwordRegEx == null) {
                return LDAPServerManagerConstants.DEFAULT_PASSWORD_REGULAR_EXPRESSION;
            } else {
                log.info("Service password format is " + passwordRegEx);
                return passwordRegEx;
            }
        }
    } catch (UserStoreException e) {
        log.error("Unable to retrieve service password format.", e);
        throw new DirectoryServerManagerException("Unable to retrieve service password format.", e);
    }

    return LDAPServerManagerConstants.DEFAULT_PASSWORD_REGULAR_EXPRESSION;
}
 
Example #13
Source File: JWTTokenGenerator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private String getMultiAttributeSeparator(String authenticatedUser, int tenantId) {
    String claimSeparator = null;
    String userDomain = IdentityUtil.extractDomainFromName(authenticatedUser);

    try {
        RealmConfiguration realmConfiguration = null;
        RealmService realmService = OAuthComponentServiceHolder.getRealmService();

        if (realmService != null && tenantId != MultitenantConstants.INVALID_TENANT_ID) {
            UserStoreManager userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId)
                    .getUserStoreManager();
            realmConfiguration = userStoreManager.getSecondaryUserStoreManager(userDomain).getRealmConfiguration();
        }

        if (realmConfiguration != null) {
            claimSeparator = realmConfiguration.getUserStoreProperty(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
            if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                return claimSeparator;
            }
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while getting the realm configuration, User store properties might not be " +
                  "returned", e);
    }
    return null;
}
 
Example #14
Source File: SecondaryUserStoreConfigurationUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> getSecondaryUserStorePropertiesFromTenantUserRealm(String userStoreDomain)
        throws IdentityUserStoreMgtException {

    Map<String, String> secondaryUserStoreProperties = null;
    try {
        RealmConfiguration realmConfiguration = UserStoreConfigComponent.getRealmService().getTenantUserRealm(
                getTenantIdInTheCurrentContext()).getRealmConfiguration();
        while (realmConfiguration != null) {
            String domainName = realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig
                    .PROPERTY_DOMAIN_NAME);
            if (StringUtils.equalsIgnoreCase(domainName, userStoreDomain)) {
                secondaryUserStoreProperties = realmConfiguration.getUserStoreProperties();
                break;
            } else {
                realmConfiguration = realmConfiguration.getSecondaryRealmConfig();
            }
        }
    } catch (UserStoreException e) {
        String errorMessage = "Error while retrieving user store configurations for user store domain: "
                + userStoreDomain;
        throw new IdentityUserStoreMgtException(errorMessage, e);
    }
    return secondaryUserStoreProperties;
}
 
Example #15
Source File: UserStoreConfigAdminService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the RandomPassword[] from secondaryRealmConfiguration for given userStoreClass
 *
 * @param userStoreClass              Extract the mandatory properties of this class
 * @param randomPhrase                The randomly generated keyword which will be stored in
 *                                    RandomPassword object
 * @param secondaryRealmConfiguration RealmConfiguration object consists the properties
 * @return RandomPassword[] array for each property
 */
private RandomPassword[] getRandomPasswordProperties(String userStoreClass,
                                                     String randomPhrase, RealmConfiguration secondaryRealmConfiguration) {
    //First check for mandatory field with #encrypt
    Property[] mandatoryProperties = getMandatoryProperties(userStoreClass);
    ArrayList<RandomPassword> randomPasswordArrayList = new ArrayList<RandomPassword>();
    for (Property property : mandatoryProperties) {
        String propertyName = property.getName();
        if (property.getDescription().contains(UserStoreConfigurationConstant.ENCRYPT_TEXT)) {
            RandomPassword randomPassword = new RandomPassword();
            randomPassword.setPropertyName(propertyName);
            randomPassword.setPassword(secondaryRealmConfiguration.getUserStoreProperty(propertyName));
            randomPassword.setRandomPhrase(randomPhrase);
            randomPasswordArrayList.add(randomPassword);
        }
    }
    return randomPasswordArrayList.toArray(new RandomPassword[randomPasswordArrayList.size()]);
}
 
Example #16
Source File: UserStoreConfgurationContextObserver.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public void terminatingConfigurationContext(ConfigurationContext context) {
    try {
        org.wso2.carbon.user.api.UserRealm tenantRealm = CarbonContext
                .getThreadLocalCarbonContext().getUserRealm();
        RealmConfiguration realmConfig = tenantRealm.getRealmConfiguration();
        AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) tenantRealm
                .getUserStoreManager();
        userStoreManager.clearAllSecondaryUserStores();
        realmConfig.setSecondaryRealmConfig(null);
        userStoreManager.setSecondaryUserStoreManager(null);
        log.info("Unloaded all secondary user stores for tenant "
                + CarbonContext.getThreadLocalCarbonContext().getTenantId());
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }
}
 
Example #17
Source File: UserRealmService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public RealmConfigurationDTO getRealmConfiguration() throws UserStoreException {
    UserRealm userRealm = getApplicableUserRealm();
    RealmConfiguration realmConfig = userRealm.getRealmConfiguration();
    RealmConfigurationDTO realmConfigDTO = new RealmConfigurationDTO();
    realmConfigDTO.setRealmClassName(realmConfig.getRealmClassName());
    realmConfigDTO.setUserStoreClass(realmConfig.getUserStoreClass());
    realmConfigDTO.setAuthorizationManagerClass(realmConfig.getAuthorizationManagerClass());
    realmConfigDTO.setAdminRoleName(realmConfig.getAdminRoleName());
    realmConfigDTO.setAdminUserName(realmConfig.getAdminUserName());
    realmConfigDTO.setAdminPassword(realmConfig.getAdminPassword());
    realmConfigDTO.setEveryOneRoleName(realmConfig.getEveryOneRoleName());
    realmConfigDTO.setUserStoreProperties(getPropertyValueArray(realmConfig
            .getUserStoreProperties()));
    realmConfigDTO.setAuthzProperties(getPropertyValueArray(realmConfig.getAuthzProperties()));
    realmConfigDTO.setRealmProperties(getPropertyValueArray(realmConfig.getRealmProperties()));
    return realmConfigDTO;
}
 
Example #18
Source File: SecondaryUserStoreConfigurationUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private static MaskedProperty[] getMaskedProperties(String userStoreClass, String maskValue,
                                                    RealmConfiguration secondaryRealmConfiguration) {
    //First check for mandatory field with #encrypt
    Property[] mandatoryProperties = getMandatoryProperties(userStoreClass);
    ArrayList<MaskedProperty> maskedProperties = new ArrayList<>();
    for (Property property : mandatoryProperties) {
        String propertyName = property.getName();
        if (property.getDescription().contains(UserStoreConfigurationConstant.ENCRYPT_TEXT)) {
            MaskedProperty maskedProperty = new MaskedProperty();
            maskedProperty.setName(propertyName);
            maskedProperty.setValue(secondaryRealmConfiguration.getUserStoreProperty(propertyName));
            maskedProperty.setMask(maskValue);
            maskedProperties.add(maskedProperty);
        }
    }
    return maskedProperties.toArray(new MaskedProperty[0]);
}
 
Example #19
Source File: WSRealm.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize WSRealm by Carbon
 *
 * @see org.wso2.carbon.user.core.UserRealm#init(org.wso2.carbon.user.api.RealmConfiguration, java.util.Map, int)
 */
@Override
public void init(RealmConfiguration configBean, Map<String, Object> properties, int tenantId)
        throws UserStoreException {
    ConfigurationContext configCtxt =
            UserMgtWSAPIDSComponent.
                    getCcServiceInstance().
                    getClientConfigContext();
    init(configBean, configCtxt);
}
 
Example #20
Source File: CarbonRemoteUserStoreManger.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param realmConfig
 * @param properties
 * @throws Exception
 */
public CarbonRemoteUserStoreManger(RealmConfiguration realmConfig, Map properties)
        throws Exception {

    ConfigurationContext configurationContext = ConfigurationContextFactory
            .createDefaultConfigurationContext();

    Map<String, TransportOutDescription> transportsOut = configurationContext
            .getAxisConfiguration().getTransportsOut();
    for (TransportOutDescription transportOutDescription : transportsOut.values()) {
        transportOutDescription.getSender().init(configurationContext, transportOutDescription);
    }

    String[] serverUrls = realmConfig.getUserStoreProperty(SERVER_URLS).split(",");

    for (int i = 0; i < serverUrls.length; i++) {
        remoteUserStore = new WSUserStoreManager(
                realmConfig.getUserStoreProperty(REMOTE_USER_NAME),
                realmConfig.getUserStoreProperty(PASSWORD), serverUrls[i],
                configurationContext);

        if (log.isDebugEnabled()) {
            log.debug("Remote Servers for User Management : " + serverUrls[i]);
        }

        remoteServers.put(serverUrls[i], remoteUserStore);
    }

    this.realmConfig = realmConfig;
    domainName = realmConfig.getUserStoreProperty(UserStoreConfigConstants.DOMAIN_NAME);
}
 
Example #21
Source File: SelfSignupUtilTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: SelfSignupUtilTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #23
Source File: IdentityUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public static String getPrimaryDomainName() {
    RealmConfiguration realmConfiguration = IdentityTenantUtil.getRealmService().getBootstrapRealmConfiguration();
    if(realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME) != null){
        return realmConfiguration.getUserStoreProperty(
                UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME).toUpperCase();
    } else {
        return UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME;
    }
}
 
Example #24
Source File: AuthenticatorUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void authorizeUser_unauthroizedUser() throws Exception {
    List<String> authorization = new ArrayList<>();
    authorization.add("OGpvbmExakBnb29nbC5pZ2cuYml6QGNjYzIyMjI6QW1hbmRhMTI=");
    HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class);
    Mockito.doReturn(authorization).when(httpHeaders).getRequestHeader("Authorization");

    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);

    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.mockStatic(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getUserRealm()).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.doReturn(true).when(userStoreManager).authenticate(any(String.class), any(String.class));

    RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
    Mockito.doReturn("admin").when(realmConfiguration).getAdminRoleName();

    String[] userRoles = new String[2];
    userRoles[0] = "subscriber";
    userRoles[1] = "publisher";

    Mockito.doReturn(userRoles).when(userStoreManager).getRoleListOfUser(any(String.class));

    AuthDTO response = AuthenticatorUtil.authorizeUser(httpHeaders);
    Assert.assertEquals(Response.Status.UNAUTHORIZED, response.getResponseStatus());
}
 
Example #25
Source File: ServerStartupListenerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private void mockCommonCases() throws Exception {
    ServiceDataHolder serviceDataHolder = Mockito.mock(ServiceDataHolder.class);
    PowerMockito.mockStatic(ServiceDataHolder.class);
    APIManagerConfigurationService apimConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apimConfig = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(ServiceDataHolder.getInstance()).thenReturn(serviceDataHolder);
    Mockito.when(serviceDataHolder.getAPIManagerConfigurationService()).thenReturn(apimConfigService);
    Mockito.when(apimConfigService.getAPIManagerConfiguration()).thenReturn(apimConfig);
    Mockito.when(apimConfig.getFirstProperty(Constants.KEY_VALIDATOR_USERNAME))
            .thenReturn(Constants.DEFAULT_KEY_VALIDATOR_USERNAME);
    Mockito.when(apimConfig.getFirstProperty(Constants.KEY_VALIDATOR_PASSWORD))
            .thenReturn(Constants.DEFAULT_KEY_VALIDATOR_PASSWORD);
    PowerMockito.mockStatic(CommonUtil.class);
    TenantMgtAdminService mgtAdminService = Mockito.spy(new TenantMgtAdminService());
    PowerMockito.whenNew(TenantMgtAdminService.class).withNoArguments().thenReturn(mgtAdminService);
    PowerMockito.doNothing().when(mgtAdminService).activateTenant(any(String.class));
    PowerMockito.doReturn("").when(mgtAdminService).addTenant(any(TenantInfoBean.class));
    AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class);
    ConfigurationContextService contextService = Mockito.mock(ConfigurationContextService.class);
    ConfigurationContext context = Mockito.mock(ConfigurationContext.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder referenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(referenceHolder);
    Mockito.when(ServiceReferenceHolder.getContextService()).thenReturn(contextService);
    Mockito.when(contextService.getServerConfigContext()).thenReturn(context);
    Mockito.when(context.getAxisConfiguration()).thenReturn(axisConfiguration);
    PowerMockito.mockStatic(RealmService.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceDataHolder.getRealmService()).thenReturn(realmService);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    RealmConfiguration configuration = Mockito.mock(RealmConfiguration.class);
    Mockito.when(realmService.getTenantUserRealm(any(Integer.class))).thenReturn(userRealm);
    Mockito.when(userRealm.getRealmConfiguration()).thenReturn(configuration);
    Mockito.when(configuration.getAdminUserName()).thenReturn(Constants.ADMIN_USERNAME);
    Mockito.when(configuration.getAdminPassword()).thenReturn(Constants.ADMIN_PASSWORD);
}
 
Example #26
Source File: FileBasedUserStoreDAOImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get a List of existing domain names.
 *
 * @return : list of domain names
 * @throws IdentityUserStoreMgtException
 */
private List<String> getDomainNames() throws IdentityUserStoreMgtException {

    List<String> domains = new ArrayList<String>();

    RealmConfiguration realmConfiguration = null;
    try {
        realmConfiguration = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration();
    } catch (UserStoreException e) {
        throw new IdentityUserStoreMgtException(" Error occurred while retrieving the realm configuration ", e);
    }

    // To add PRIMARY domain to the domains list
    String domain = realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    if (domain == null) {
        domain = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME;
    }
    domains.add(domain);

    RealmConfiguration secondaryRealmConfiguration = realmConfiguration.getSecondaryRealmConfig();
    while (secondaryRealmConfiguration != null) {
        domains.add(secondaryRealmConfiguration.getUserStoreProperty(UserCoreConstants.
                RealmConfig.PROPERTY_DOMAIN_NAME));
        secondaryRealmConfiguration = secondaryRealmConfiguration.getSecondaryRealmConfig();
    }
    return domains;
}
 
Example #27
Source File: FileBasedUserStoreDAOImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private UserStoreDTO getUserStoreDTO(RealmConfiguration secondaryRealmConfiguration, Map<String, String>
        userStoreProperties) {

    UserStoreDTO userStoreDTO = new UserStoreDTO();
    userStoreDTO.setClassName(secondaryRealmConfiguration.getUserStoreClass());
    userStoreDTO.setDescription(secondaryRealmConfiguration.getUserStoreProperty(UserStoreConfigurationConstant
                                                                                         .DESCRIPTION));
    userStoreDTO.setDomainId(secondaryRealmConfiguration.getUserStoreProperty(UserStoreConfigConstants
                                                                                      .DOMAIN_NAME));
    userStoreDTO.setRepositoryClass(FILE_BASED);
    if (userStoreProperties.get(DISABLED) != null) {
        userStoreDTO.setDisabled(Boolean.valueOf(userStoreProperties.get(DISABLED)));
    }
    return userStoreDTO;
}
 
Example #28
Source File: DatabaseBasedUserStoreDAOImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void addRealmToSecondaryUserStoreManager(UserStorePersistanceDTO userStorePersistanceDTO) throws
        UserStoreException, XMLStreamException {

    UserRealm userRealm = (UserRealm) CarbonContext.getThreadLocalCarbonContext().getUserRealm();
    AbstractUserStoreManager primaryUSM = (AbstractUserStoreManager) userRealm.getUserStoreManager();
    InputStream targetStream = new ByteArrayInputStream(userStorePersistanceDTO.getUserStoreProperties()
                                                                               .getBytes());
    RealmConfiguration realmConfiguration = getRealmConfiguration(userStorePersistanceDTO.getUserStoreDTO().
            getDomainId(), targetStream);
    primaryUSM.addSecondaryUserStoreManager(realmConfiguration, userRealm);
}
 
Example #29
Source File: DatabaseBasedUserStoreDAOImpl.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private UserStoreDTO getUserStoreDTO(RealmConfiguration secondaryRealmConfiguration,
                                     Map<String, String> userStoreProperties) {

    UserStoreDTO userStoreDTO = new UserStoreDTO();
    userStoreDTO.setClassName(secondaryRealmConfiguration.getUserStoreClass());
    userStoreDTO.setDescription(secondaryRealmConfiguration.getUserStoreProperty(UserStoreConfigurationConstant
                                                                                         .DESCRIPTION));
    userStoreDTO.setDomainId(secondaryRealmConfiguration.getUserStoreProperty(UserStoreConfigConstants
                                                                                      .DOMAIN_NAME));
    userStoreDTO.setRepositoryClass(DATABASE_BASED);
    if (userStoreProperties.get(DISABLED) != null) {
        userStoreDTO.setDisabled(Boolean.valueOf(userStoreProperties.get(DISABLED)));
    }
    return userStoreDTO;
}
 
Example #30
Source File: RegistrationServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private boolean isUserSuperAdmin(String username) {

        try {
            RealmConfiguration realmConfig = new RealmConfigXMLProcessor().buildRealmConfigurationFromFile();
            String adminUserName = realmConfig.getAdminUserName();
            return adminUserName.equalsIgnoreCase(username);
        } catch (UserStoreException e) {
            log.error("Error while retrieving super admin username", e);
            return false;
        }
    }