Search in sources :

Example 21 with UserStoreManager

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

the class UserSignUpWSWorkflowExecutorTest method testFailureToCompleteUserSignUpWorkflowApprovedByAdmin.

@Test
public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exception {
    Map<String, Boolean> roleMap = new HashMap<String, Boolean>();
    roleMap.put(signUpRole, false);
    UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO();
    userRegistrationConfigDTO.setRoles(roleMap);
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO);
    PowerMockito.when(SelfSignUpUtil.getRoleNames(userRegistrationConfigDTO)).thenCallRealMethod();
    PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO);
    Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true);
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(true);
    // Set workflow status to be approved
    workflowDTO.setStatus(WorkflowStatus.APPROVED);
    workflowDTO.setTenantDomain(tenantDomain);
    // Set tenant admin credentials
    userRegistrationConfigDTO.setAdminUserName("admin");
    userRegistrationConfigDTO.setAdminPassword("admin");
    // Test failure to complete workflow execution, when error has been occurred while updating user with signup roles
    Mockito.doThrow(UserStoreException.class).when(userStoreManager).updateRoleListOfUser(Mockito.anyString(), Mockito.any(), new String[] { Mockito.anyString() });
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup user role update failed");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when sign up roles are not existing in user realm
    Mockito.when(userStoreManager.isExistingRole("Internal/" + signUpRole)).thenReturn(false);
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while assigning role to user");
    }
    // Test failure to complete workflow execution, when error has been occurred while retrieving signup config
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException("Error occurred while retrieving signup configuration"));
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while accessing signup configuration");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 22 with UserStoreManager

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

the class UserSignUpWSWorkflowExecutorTest method testFailureToCompleteUserSignUpWorkflowRejectedByAdmin.

@Test
public void testFailureToCompleteUserSignUpWorkflowRejectedByAdmin() throws Exception {
    Map<String, Boolean> roleMap = new HashMap<String, Boolean>();
    roleMap.put(signUpRole, false);
    UserRegistrationConfigDTO userRegistrationConfigDTO = new UserRegistrationConfigDTO();
    userRegistrationConfigDTO.setAdminUserName("admin");
    userRegistrationConfigDTO.setAdminPassword("admin");
    userRegistrationConfigDTO.setRoles(roleMap);
    PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO);
    PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO);
    // Set workflow status to be approved
    workflowDTO.setStatus(WorkflowStatus.REJECTED);
    Mockito.doThrow(UserStoreException.class).when(userStoreManager).deleteUser(Mockito.anyString());
    try {
        userSignUpWSWorkflowExecutor.complete(workflowDTO);
        Assert.fail("Expected WorkflowException has not been thrown when user deletion failed");
    } catch (WorkflowException e) {
        Assert.assertEquals(e.getMessage(), "Error while deleting the user");
    }
}
Also used : HashMap(java.util.HashMap) UserRegistrationConfigDTO(org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 23 with UserStoreManager

use of org.wso2.carbon.user.core.UserStoreManager 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 24 with UserStoreManager

use of org.wso2.carbon.user.core.UserStoreManager in project carbon-business-process by wso2.

the class BPSUserIdentityManager method checkPassword.

@Override
public Boolean checkPassword(String userId, String password) {
    String tenantDomain = MultitenantUtils.getTenantDomain(userId);
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(userId);
    String userNameWithTenantDomain = tenantAwareUserName + "@" + tenantDomain;
    RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
    TenantManager mgr = realmService.getTenantManager();
    int tenantId = 0;
    try {
        tenantId = mgr.getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        throw new BPMNAuthenticationException("Identity exception thrown while getting tenant ID for user : " + userNameWithTenantDomain, e);
    }
    // tenantId == -1, means an invalid tenant.
    if (tenantId == -1) {
        if (log.isDebugEnabled()) {
            log.debug("Basic authentication request with an invalid tenant : " + userNameWithTenantDomain);
        }
        return false;
    }
    org.wso2.carbon.user.api.UserStoreManager userStoreManager = null;
    boolean authStatus = false;
    try {
        userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        authStatus = userStoreManager.authenticate(tenantAwareUserName, password);
    } catch (UserStoreException e) {
        throw new BPMNAuthenticationException("User store exception thrown while authenticating user : " + userNameWithTenantDomain, e);
    }
    /* IdentityService identityService = BPMNOSGIService.getIdentityService();
        authStatus = identityService.checkPassword(userName, password);*/
    if (log.isDebugEnabled()) {
        log.debug("Basic authentication request completed. " + "Username : " + userNameWithTenantDomain + ", Authentication State : " + authStatus);
    }
    return authStatus;
}
Also used : RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) BPMNAuthenticationException(org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager)

Example 25 with UserStoreManager

use of org.wso2.carbon.user.core.UserStoreManager in project carbon-business-process by wso2.

the class BPSUserIdentityManager method findUserById.

@Override
public UserEntity findUserById(String userId) {
    try {
        UserStoreManager userStoreManager = registryService.getUserRealm(getTenantIdFromUserId(userId)).getUserStoreManager();
        if (userStoreManager.isExistingUser(userId)) {
            UserEntity userEntity = new UserEntity(userId);
            String firstName = userStoreManager.getUserClaimValue(userId, FIRST_NAME_CLAIM_URI, null);
            userEntity.setFirstName(firstName);
            String lastName = userStoreManager.getUserClaimValue(userId, LAST_NAME_CLAIM_URI, null);
            userEntity.setLastName(lastName);
            String email = userStoreManager.getUserClaimValue(userId, EMAIL_CLAIM_URI, null);
            userEntity.setEmail(email);
            return userEntity;
        } else {
            log.error("No user exist with userId:" + userId);
            return null;
        }
    } catch (Exception e) {
        log.error("Error retrieving user info by id for: " + userId, e);
        return null;
    }
}
Also used : UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) UserEntity(org.activiti.engine.impl.persistence.entity.UserEntity) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) BPMNAuthenticationException(org.wso2.carbon.bpmn.core.exception.BPMNAuthenticationException)

Aggregations

RealmService (org.wso2.carbon.user.core.service.RealmService)27 UserStoreException (org.wso2.carbon.user.api.UserStoreException)25 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)24 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)19 Test (org.junit.Test)17 UserRealm (org.wso2.carbon.user.core.UserRealm)16 UserStoreManager (org.wso2.carbon.user.core.UserStoreManager)16 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)12 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)11 TenantManager (org.wso2.carbon.user.core.tenant.TenantManager)10 UserRealm (org.wso2.carbon.user.api.UserRealm)8 HashMap (java.util.HashMap)6 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)6 UserRegistrationConfigDTO (org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO)4 Assertion (org.opensaml.saml.saml2.core.Assertion)3 Response (org.opensaml.saml.saml2.core.Response)3 Subject (org.opensaml.saml.saml2.core.Subject)3 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)3 Endpoint (org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2