Search in sources :

Example 11 with UserStoreManager

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

the class APIUtil method isUserExist.

/**
 * Check whether user is exist
 *
 * @param username A username
 * @throws APIManagementException If an error occurs
 */
public static boolean isUserExist(String username) throws APIManagementException {
    if (username == null) {
        throw new APIManagementException("Attempt to execute privileged operation as the anonymous user");
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
    try {
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        UserStoreManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
        return manager.isExistingUser(tenantAwareUserName);
    } catch (UserStoreException e) {
        throw new APIManagementException("UserStoreException while trying the user existence " + username, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 12 with UserStoreManager

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

the class SystemScopesIssuer method getUserRoles.

/**
 * This method is used to get roles list of the user.
 *
 * @param authenticatedUser Authenticated user
 * @return roles list
 */
private String[] getUserRoles(AuthenticatedUser authenticatedUser) {
    String[] userRoles = null;
    String tenantDomain;
    String username;
    if (authenticatedUser.isFederatedUser()) {
        tenantDomain = MultitenantUtils.getTenantDomain(authenticatedUser.getAuthenticatedSubjectIdentifier());
        username = MultitenantUtils.getTenantAwareUsername(authenticatedUser.getAuthenticatedSubjectIdentifier());
    } else {
        tenantDomain = authenticatedUser.getTenantDomain();
        username = authenticatedUser.getUserName();
    }
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    RealmService realmService = getRealmService();
    try {
        int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
        // If tenant Id is not set in the tokenReqContext, deriving it from username.
        if (tenantId == 0 || tenantId == -1) {
            tenantId = getTenantIdOfUser(username);
        }
        UserStoreManager userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        String endUsernameWithDomain = addDomainToName(username, userStoreDomain);
        userRoles = userStoreManager.getRoleListOfUser(endUsernameWithDomain);
    } catch (UserStoreException e) {
        // Log and return since we do not want to stop issuing the token in case of scope validation failures.
        log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
    }
    return userRoles;
}
Also used : RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 13 with UserStoreManager

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

the class UserPostSelfRegistrationHandler method executeUserRegistrationWorkflow.

/**
 * This method adds new role to the existing user roles
 * @param tenantDomain tenant domain extracted from the event
 * @param userName username extracted from the event
 * @throws org.wso2.carbon.identity.recovery.IdentityRecoveryServerException when unable to retrieve
 * userStoreManager instance
 */
private void executeUserRegistrationWorkflow(String tenantDomain, String userName) throws org.wso2.carbon.identity.recovery.IdentityRecoveryServerException {
    try {
        // Realm service is used for user management tasks
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        UserStoreManager userStoreManager;
        try {
            userStoreManager = realmService.getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getUserStoreManager();
        } catch (UserStoreException e) {
            throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, userName, e);
        }
        // Start a tenant flow
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantId(IdentityTenantUtil.getTenantId(tenantDomain));
        carbonContext.setTenantDomain(tenantDomain);
        if (userStoreManager.isExistingUser(userName)) {
            List<String> roleList = asList(userStoreManager.getRoleListOfUser(userName));
            // User should have selfSignup role. Checking whether the user is in the new role
            if (roleList.contains(SELF_SIGNUP_ROLE) && !roleList.contains(SUBSCRIBER_ROLE)) {
                WorkflowExecutor userSignUpWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
                // initiate a new signup workflow
                WorkflowDTO signUpWFDto = new WorkflowDTO();
                signUpWFDto.setWorkflowReference(userName);
                signUpWFDto.setStatus(WorkflowStatus.CREATED);
                signUpWFDto.setCreatedTime(System.currentTimeMillis());
                signUpWFDto.setTenantDomain(tenantDomain);
                signUpWFDto.setTenantId(IdentityTenantUtil.getTenantId(tenantDomain));
                signUpWFDto.setExternalWorkflowReference(userSignUpWFExecutor.generateUUID());
                signUpWFDto.setWorkflowType(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP);
                signUpWFDto.setCallbackUrl(userSignUpWFExecutor.getCallbackURL());
                userSignUpWFExecutor.execute(signUpWFDto);
            }
        }
    } catch (UserStoreException | WorkflowException e) {
        throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_UNEXPECTED, userName, e);
    } finally {
        Utils.clearArbitraryProperties();
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) RealmService(org.wso2.carbon.user.core.service.RealmService) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Example 14 with UserStoreManager

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

the class APIUtilTest method testGetListOfRolesNonSuperTenant.

@Test
public void testGetListOfRolesNonSuperTenant() throws Exception {
    int tenantID = 1;
    String username = "Kelso";
    String[] roles = { "PUBLISHER", "ADMIN", "TEST-ROLE" };
    String tenantDomain = "Insta.com";
    String tenantAwareUsername = "Insta_User";
    PowerMockito.spy(APIUtil.class);
    PowerMockito.doReturn(null).when(APIUtil.class, "getValueFromCache", APIConstants.API_USER_ROLE_CACHE, username);
    PowerMockito.mockStatic(MultitenantUtils.class);
    Mockito.when(MultitenantUtils.getTenantDomain(username)).thenReturn(tenantDomain);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    RealmService realmService = Mockito.mock(RealmService.class);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    Mockito.when(realmService.getTenantUserRealm(tenantID)).thenReturn(userRealm);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(MultitenantUtils.getTenantAwareUsername(username)).thenReturn(tenantAwareUsername);
    Mockito.when(userStoreManager.getRoleListOfUser(tenantAwareUsername)).thenReturn(roles);
    PowerMockito.doNothing().when(APIUtil.class, "addToRolesCache", Mockito.any(), Mockito.any(), Mockito.any());
    Assert.assertEquals(roles, APIUtil.getListOfRoles(username));
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) UserRealm(org.wso2.carbon.user.api.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 15 with UserStoreManager

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

the class APIUtilRolesTest method testCreateDefaultRoles.

@Test
public void testCreateDefaultRoles() throws Exception {
    System.setProperty("carbon.home", APIUtilRolesTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        final int tenantId = MultitenantConstants.SUPER_TENANT_ID;
        final String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        File siteConfFile = new File(Thread.currentThread().getContextClassLoader().getResource("tenant-conf.json").getFile());
        String tenantConfValue = FileUtils.readFileToString(siteConfFile);
        InputStream signUpConfStream = new FileInputStream(Thread.currentThread().getContextClassLoader().getResource("default-sign-up-config.xml").getFile());
        ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
        RealmService realmService = Mockito.mock(RealmService.class);
        RegistryService registryService = Mockito.mock(RegistryService.class);
        TenantManager tenantManager = Mockito.mock(TenantManager.class);
        TenantIndexingLoader indexingLoader = Mockito.mock(TenantIndexingLoader.class);
        UserRealm userRealm = Mockito.mock(UserRealm.class);
        UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
        RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class);
        APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
        PowerMockito.mockStatic(PrivilegedCarbonContext.class);
        PowerMockito.mockStatic(ServiceReferenceHolder.class);
        PowerMockito.mockStatic(APIManagerComponent.class);
        Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
        Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
        Mockito.when(serviceReferenceHolder.getIndexLoaderService()).thenReturn(indexingLoader);
        Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
        Mockito.when(realmService.getBootstrapRealm()).thenReturn(userRealm);
        Mockito.when(realmService.getTenantUserRealm(tenantId)).thenReturn(userRealm);
        Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
        Mockito.when(userRealm.getRealmConfiguration()).thenReturn(realmConfiguration);
        Mockito.when(realmConfiguration.getAdminUserName()).thenReturn("admin");
        Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
        Mockito.when(tenantManager.getDomain(tenantId)).thenReturn(tenantDomain);
        Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
        Mockito.when(apimConfigService.getTenantConfig(tenantDomain)).thenReturn(tenantConfValue);
        Mockito.when(apimConfigService.getSelfSighupConfig(tenantDomain)).thenReturn(IOUtils.toString(signUpConfStream));
        APIUtil.createDefaultRoles(tenantId);
        String[] adminName = { "admin" };
        Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/publisher"), eq(adminName), new Permission[] { Mockito.any(Permission.class) });
        Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/subscriber"), eq(adminName), new Permission[] { Mockito.any(Permission.class) });
        Mockito.verify(userStoreManager, Mockito.atLeastOnce()).addRole(eq("Internal/creator"), eq(adminName), new Permission[] { Mockito.any(Permission.class) });
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) FileInputStream(java.io.FileInputStream) RealmConfiguration(org.wso2.carbon.user.core.config.RealmConfiguration) TenantIndexingLoader(org.wso2.carbon.registry.indexing.service.TenantIndexingLoader) UserRealm(org.wso2.carbon.user.core.UserRealm) RealmService(org.wso2.carbon.user.core.service.RealmService) Permission(org.wso2.carbon.user.api.Permission) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) APIMConfigService(org.wso2.carbon.apimgt.impl.config.APIMConfigService) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

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