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

The following examples show how to use org.wso2.carbon.user.api.UserStoreManager. 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: 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 #2
Source File: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private static UserStoreManager getUserStoreManager(int tenantId, String userStoreDomain)
        throws UserStoreException {

    UserStoreManager userStoreManager = FrameworkServiceComponent.getRealmService().getTenantUserRealm(tenantId)
            .getUserStoreManager();
    if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
        return ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).getSecondaryUserStoreManager(
                userStoreDomain);
    }
    if (log.isDebugEnabled()) {
        log.debug("Unable to resolve the corresponding user store manager for the domain: " + userStoreDomain
                + ", as the provided user store manager: " + userStoreManager.getClass() + ", is not an instance " +
                "of org.wso2.carbon.user.core.UserStoreManager. Therefore returning the user store " +
                "manager: " + userStoreManager.getClass() + ", from the realm.");
    }
    return userStoreManager;
}
 
Example #3
Source File: StratosApiV41Utils.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Get Tenant UserStoreManager
 *
 * @return UserStoreManager
 * @throws UserManagerException
 */
private static UserStoreManager getTenantUserStoreManager() throws UserManagerException {

    CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
    UserRealm userRealm;
    UserStoreManager userStoreManager;

    try {
        userRealm = carbonContext.getUserRealm();
        userStoreManager = userRealm.getUserStoreManager();

    } catch (UserStoreException e) {
        String msg = "Error in retrieving UserStore Manager";
        log.error(msg, e);
        throw new UserManagerException(msg, e);
    }

    return userStoreManager;
}
 
Example #4
Source File: APIUtil.java    From product-iots with Apache License 2.0 6 votes vote down vote up
public static void registerApiAccessRoles(String user) {
    UserStoreManager userStoreManager = null;
    try {
        userStoreManager = getUserStoreManager();
        String[] userList = new String[]{user};
        if (userStoreManager != null) {
            String rolesOfUser[] = userStoreManager.getRoleListOfUser(user);
            if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) {
                userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION);
            } else if (rolesOfUser != null && Arrays.asList(rolesOfUser).contains(Constants.DEFAULT_ROLE_NAME)) {
                return;
            } else {
                userStoreManager.updateUserListOfRole(Constants.DEFAULT_ROLE_NAME, new String[0], userList);
            }
        }
    } catch (UserStoreException e) {
        log.error("Error while creating a role and adding a user for virtual_firealarm.", e);
    }
}
 
Example #5
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/checkUser")
@Override
public Response isUserExists(@QueryParam("username") String userName) {
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        if (userStoreManager.isExistingUser(userName)) {
            return Response.status(Response.Status.OK).entity(true).build();
        } else {
            return Response.status(Response.Status.OK).entity(false).build();
        }
    } catch (UserStoreException e) {
        String msg = "Error while retrieving the user.";
        log.error(msg, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
    }
}
 
Example #6
Source File: DefaultClaimHandler.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void setSubjectClaimForStandardDialect(String tenantAwareUserId, UserStoreManager userStore,
                                               AuthenticationContext context, String subjectURI) {
    try {
        String value = userStore.getUserClaimValue(tenantAwareUserId, subjectURI, null);
        if (value != null) {
            context.setProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE, value);
            if (log.isDebugEnabled()) {
                log.debug("Setting \'ServiceProviderSubjectClaimValue\' property value " +
                          "from user store " + value);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Subject claim for " + tenantAwareUserId + " not found in user store");
            }
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while retrieving " + subjectURI + " claim value for user " + tenantAwareUserId,
                e);
    }
}
 
Example #7
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private UserStoreManager getUserStoreManager(String tenantDomain, UserRealm realm, String userDomain) throws
        FrameworkException {
    UserStoreManager userStore = null;
    try {
        userStore = realm.getUserStoreManager();
        if (StringUtils.isNotBlank(userDomain)) {
            userStore = realm.getUserStoreManager().getSecondaryUserStoreManager(userDomain);
        }

        if (userStore == null) {
            // To avoid NPEs
            throw new FrameworkException("Invalid user store domain name : " + userDomain + " in tenant : "
                    + tenantDomain);
        }
    } catch (UserStoreException e) {
        throw new FrameworkException("Error occurred while retrieving the UserStoreManager " +
                                     "from Realm for " + tenantDomain + " to handle local claims", e);
    }
    return userStore;
}
 
Example #8
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Set federated subject's SP Subject Claim URI as a property
 */
private void setSubjectClaimForLocalClaims(String tenantAwareUserId,
                                           UserStoreManager userStore,
                                           Map<String, String> attributesMap,
                                           String spStandardDialect,
                                           AuthenticationContext context) {

    String subjectURI = context.getSequenceConfig().getApplicationConfig().getSubjectClaimUri();
    if (subjectURI != null && !subjectURI.isEmpty()) {
        if (spStandardDialect != null) {
            setSubjectClaim(tenantAwareUserId, userStore, attributesMap, spStandardDialect, context);
            if (context.getProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE) == null) {
                log.warn("Subject claim could not be found amongst unfiltered local claims");
            }
        } else {
            setSubjectClaim(tenantAwareUserId, userStore, attributesMap, null, context);
            if (context.getProperty(SERVICE_PROVIDER_SUBJECT_CLAIM_VALUE) == null) {
                log.warn("Subject claim could not be found amongst service provider mapped " +
                         "unfiltered local claims");
            }
        }
    }
}
 
Example #9
Source File: UserRoleCreator.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Creating Internal/user Role at Carbon Server Start-up
 */
public static void createInternalUserRole(UserStoreManager userStoreManager) throws UserManagerException {
    String userRole = "Internal/user";
    try {
        if (!userStoreManager.isExistingRole(userRole)) {
            log.info("Creating internal user role: " + userRole);

            //Set permissions to the Internal/user role
            List<Permission> permissions = new ArrayList<Permission>();
            for (String permissionResourceId : PermissionConstants.STRATOS_PERMISSIONS) {
                Permission permission = new Permission(permissionResourceId, UserMgtConstants.EXECUTE_ACTION);
                permissions.add(permission);
            }
            String[] userList = new String[]{};
            userStoreManager.addRole(userRole, userList, permissions.toArray(new Permission[permissions.size()]));
        }
    } catch (UserStoreException e) {
        String msg = "Error while creating the role: " + userRole;
        log.error(msg, e);
        throw new UserManagerException(msg, e);
    }
}
 
Example #10
Source File: UserIdentityManagementAdminService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * User change the password of the user.
 *
 * @param newPassword
 * @throws IdentityMgtServiceException
 */
public void changeUserPassword(String newPassword, String oldPassword) throws IdentityMgtServiceException {

    String userName = CarbonContext.getThreadLocalCarbonContext().getUsername();

    try {
        UserStoreManager userStoreManager = getUserStore(userName);
        userName = UserCoreUtil.removeDomainFromName(userName);
        userStoreManager.updateCredential(userName, newPassword, oldPassword);
        log.info("Password changed for: " + userName);
    } catch (UserStoreException e) {
        String message = "Error while resetting the password for: " + userName;
        log.error(message, e);
        throw new IdentityMgtServiceException(message, e);
    }
}
 
Example #11
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/checkUser")
@Override
public Response isUserExists(@QueryParam("username") String userName) {
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        if (userStoreManager.isExistingUser(userName)) {
            return Response.status(Response.Status.OK).entity(true).build();
        } else {
            return Response.status(Response.Status.OK).entity(false).build();
        }
    } catch (UserStoreException e) {
        String msg = "Error while retrieving the user.";
        log.error(msg, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
    }
}
 
Example #12
Source File: AuthenticatorUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test(expected = AuthenticationException.class)
public void authorizeUser_throwsException() 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()).thenThrow(UserStoreException.class);

    AuthenticatorUtil.authorizeUser(httpHeaders);
}
 
Example #13
Source File: UserIdentityManagementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Locks the user account.
 *
 * @param userName
 * @param userStoreManager
 * @throws IdentityException
 */
public static void lockUserAccount(String userName, UserStoreManager userStoreManager)
        throws IdentityException {
    if (!isIdentityMgtListenerEnable()) {
        throw IdentityException.error("Cannot lock account, IdentityMgtEventListener is not enabled.");
    }

    String domainName = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).getRealmConfiguration().
            getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    userName = UserCoreUtil.addDomainToName(userName, domainName);

    try {
        if (!userStoreManager.isExistingUser(userName)) {
            log.error("User " + userName + " does not exist in tenant " + userStoreManager.getTenantId());
            throw IdentityException.error("No user account found for user " + userName);
        }

        Map<String, String> claims = new HashMap<>();
        claims.put(UserIdentityDataStore.ACCOUNT_LOCK, "true");
        claims.put(UserIdentityDataStore.UNLOCKING_TIME, "0");
        userStoreManager.setUserClaimValues(userName, claims, null);
    } catch (UserStoreException e) {
        log.error("Error while reading/storing user identity data", e);
        throw IdentityException.error("Error while lock user account : " + userName);
    }
}
 
Example #14
Source File: UserIdentityManagementUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Unlocks the user account
 *
 * @param userName
 * @param userStoreManager
 * @throws IdentityException
 */
public static void unlockUserAccount(String userName, UserStoreManager userStoreManager)
        throws IdentityException {

    if (!isIdentityMgtListenerEnable()) {
        throw IdentityException.error("Cannot unlock account, IdentityMgtEventListener is not enabled.");
    }

    String domainName = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).getRealmConfiguration().
            getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    userName = UserCoreUtil.addDomainToName(userName, domainName);

    try {
        if (!userStoreManager.isExistingUser(userName)) {
            log.error("User " + userName + " does not exist in tenant " + userStoreManager.getTenantId());
            throw IdentityException.error("No user account found for user " + userName);
        }
        Map<String, String> claims = new HashMap<>();
        claims.put(UserIdentityDataStore.ACCOUNT_LOCK, "false");
        claims.put(UserIdentityDataStore.UNLOCKING_TIME, "0");
        userStoreManager.setUserClaimValues(userName, claims, null);
    } catch (UserStoreException e) {
        log.error("Error while reading/storing user identity data", e);
        throw IdentityException.error("Error while unlock user account " + userName);
    }
}
 
Example #15
Source File: BaseWebAppAuthenticatorFrameworkTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * To get the registry service.
 * @return RegistryService
 * @throws RegistryException Registry Exception
 */
private  RegistryService getRegistryService() throws RegistryException, UserStoreException {
    RealmService realmService = new InMemoryRealmService();
    AuthenticatorFrameworkDataHolder.getInstance().setRealmService(realmService);
    UserStoreManager userStoreManager = AuthenticatorFrameworkDataHolder.getInstance().getRealmService()
            .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager();
    Permission adminPermission = new Permission(PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH,
            CarbonConstants.UI_PERMISSION_ACTION);
    userStoreManager.addRole(ADMIN_ROLE + "t", new String[] { ADMIN_USER }, new Permission[] { adminPermission });
    RegistryDataHolder.getInstance().setRealmService(realmService);
    DeviceManagementDataHolder.getInstance().setRealmService(realmService);
    InputStream is = BaseWebAppAuthenticatorFrameworkTest.class.getClassLoader()
            .getResourceAsStream("carbon-home/repository/conf/registry.xml");
    RegistryContext context = RegistryContext.getBaseInstance(is, realmService);
    context.setSetup(true);
    return context.getEmbeddedRegistryService();
}
 
Example #16
Source File: FederatedAssociationManagerImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void validateUserExistence(User user, int tenantId) throws FederatedAssociationManagerException {

        try {
            UserStoreManager userStoreManager = IdentityUserProfileServiceDataHolder.getInstance().getRealmService()
                    .getTenantUserRealm(tenantId).getUserStoreManager();
            if (!userStoreManager.isExistingUser(
                    UserCoreUtil.addDomainToName(user.getUserName(), user.getUserStoreDomain()))) {
                if (log.isDebugEnabled()) {
                    log.error("UserNotFound: userName: " + user.getUserName() + ", in the domain: "
                            + user.getUserStoreDomain() + ", and in the tenant: " + user.getTenantDomain());
                }
                throw handleFederatedAssociationManagerClientException(INVALID_USER_IDENTIFIER_PROVIDED, null, true);
            }
        } catch (UserStoreException e) {
            if (log.isDebugEnabled()) {
                String msg = "Error occurred while verifying the existence of the userName: " + user.getUserName()
                        + ", in the domain: " + user.getUserStoreDomain() + ", and in the tenant: "
                        + user.getTenantDomain();
                log.debug(msg);
            }
            throw handleFederatedAssociationManagerServerException(ERROR_WHILE_GETTING_THE_USER, e, true);
        }
    }
 
Example #17
Source File: UserStoreCountService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private long getRoleCount(String filter) throws UserStoreCounterException {

        try {
            UserStoreManager userStoreManager = getUserStoreManager();
            if (!(userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager)) {
                if (log.isDebugEnabled()) {
                    log.debug(" Cannot get role count. Provided user store manager : "
                            + userStoreManager.getClass() + ", is not not an instance of : "
                            + org.wso2.carbon.user.core.UserStoreManager.class);
                }
                throw new UserStoreCounterException("Unsupported user store manager to retrieve role count");
            }
            return ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).countRoles(filter);
        } catch (UserStoreException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while retrieving role count with tenent Id " + tenantId + ", and the filter "
                        + filter);
            }
            String errorMsg = "Error occurred while retrieving role count";
            throw new UserStoreCounterException(errorMsg, e);
        }
    }
 
Example #18
Source File: UserStoreCountService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Get User count.
 *
 * @param claimURI    claim uri.
 * @param valueFilter filter that filter the users.
 * @return user count.
 * @throws UserStoreCounterException UserStoreCounterException.
 */
private long getUserCountWithClaims(String claimURI, String valueFilter) throws UserStoreCounterException {

    try {
        UserStoreManager userStoreManager = getUserStoreManager();
        if (!(userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager)) {
            if (log.isDebugEnabled()) {
                log.debug(" Cannot get user count. Provided user store manager : "
                        + userStoreManager.getClass() + ", is not not an instance of : "
                        + org.wso2.carbon.user.core.UserStoreManager.class);
            }
            throw new UserStoreCounterException("Unsupported user store manager to retrieve user count");
        }
        return ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).getUserCountWithClaims(claimURI,
                valueFilter);
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while retrieving user count with tenant Id : " + tenantId + ", and the filter : "
                    + valueFilter);
        }
        String errorMsg = "Error occurred while retrieving user count";
        throw new UserStoreCounterException(errorMsg, e);
    }
}
 
Example #19
Source File: UserStoreBasedIdentityDataStore.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * This method sets user claim values in user store
 *
 * @param userStoreManager userStoreManager object
 * @param username         user name
 * @param claims           set of claims
 * @param profile          profile
 * @throws IdentityException
 */
protected void setUserClaimsValuesInUserStore(UserStoreManager userStoreManager,
                                              String username,
                                              Map<String, String> claims, String profile) throws IdentityException {

    try {
        // We are calling the doSetUserClaimsValues() method of the userstore to prevent Identity Management
        // listener being called once again for claim value set events.
        if (userStoreManager instanceof JDBCUserStoreManager) {
            ((JDBCUserStoreManager) userStoreManager).doSetUserClaimValues(username, claims, null);
        } else if (userStoreManager instanceof ActiveDirectoryUserStoreManager) {
            ((ActiveDirectoryUserStoreManager) userStoreManager).doSetUserClaimValues(username, claims, null);
        } else if (userStoreManager instanceof ReadWriteLDAPUserStoreManager) {
            ((ReadWriteLDAPUserStoreManager) userStoreManager).doSetUserClaimValues(username, claims, null);
        } else {
            String msg = "Cannot persist identity data to userstore for user:%s. Unsupported userstore type:%s to" +
                    " be used as UserStoreBasedIdentityDataStore.";
            throw IdentityException.error(String.format(msg, username, userStoreManager.getClass().getName()));
        }

    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        throw IdentityException.error("Error while persisting identity user data in to user store for user: "
                + username, e);
    }

}
 
Example #20
Source File: DeviceAccessAuthorizationServiceTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private void initializeTestEnvironment() throws UserStoreException, GroupManagementException,
        RoleDoesNotExistException, DeviceNotFoundException {
    //creating UI permission
    Permission adminPermission = new Permission(ADMIN_PERMISSION, CarbonConstants.UI_PERMISSION_ACTION);
    Permission deviceViewPermission = new Permission(NON_ADMIN_PERMISSION, CarbonConstants.UI_PERMISSION_ACTION);
    UserStoreManager userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService()
            .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager();
    //Adding a non Admin User
    userStoreManager.addUser(NON_ADMIN_ALLOWED_USER, PASSWORD, null, defaultUserClaims, null);
    //Adding a normal user
    userStoreManager.addUser(NORMAL_USER, PASSWORD, null, defaultUserClaims, null);
    //Adding role with permission to Admin user
    userStoreManager.addRole(ADMIN_ROLE, new String[]{ADMIN_USER}, new Permission[]{adminPermission});
    //Adding role with permission to non Admin user
    userStoreManager.addRole(NON_ADMIN_ROLE, new String[]{NON_ADMIN_ALLOWED_USER},
            new Permission[]{deviceViewPermission});
    //Creating default group
    GroupManagementProviderService groupManagementProviderService = DeviceManagementDataHolder.getInstance()
            .getGroupManagementProviderService();
    groupManagementProviderService.createDefaultGroup(DEFAULT_GROUP);
    int groupId = groupManagementProviderService.getGroup(DEFAULT_GROUP).getGroupId();
    //Sharing group with admin and non admin roles
    groupManagementProviderService.manageGroupSharing(groupId, new ArrayList<>(Arrays.asList(ADMIN_ROLE,
            NON_ADMIN_ROLE)));
    //Adding first 2 devices to the group
    groupDeviceIds.add(deviceIds.get(0));
    groupDeviceIds.add(deviceIds.get(1));
    groupManagementProviderService.addDevices(groupId, groupDeviceIds);
}
 
Example #21
Source File: InMemoryIdentityDataStore.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String userName, UserStoreManager userStoreManager) throws IdentityException {

    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);

        Cache<String, UserIdentityClaimsDO> cache = getCache();
        if (userName == null) {
            return;
        }
        if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
            if (!IdentityUtil.isUserStoreCaseSensitive((org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) {
                if (log.isDebugEnabled()) {
                    log.debug("Case insensitive user store found. Changing username from : " + userName + " to : " +
                            userName.toLowerCase());
                }
                userName = userName.toLowerCase();
            }
        }
        org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager)
                userStoreManager;
        String domainName = store.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig
                .PROPERTY_DOMAIN_NAME);

        cache.remove(domainName + userStoreManager.getTenantId() + userName);
    } catch (UserStoreException e) {
        log.error("Error while obtaining tenant ID from user store manager");
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
 
Example #22
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{username}")
@Override
public Response getUser(@PathParam("username") String username, @QueryParam("domain") String domain,
                        @HeaderParam("If-Modified-Since") String ifModifiedSince) {
    if (domain != null && !domain.isEmpty()) {
        username = domain + '/' + username;
    }
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        if (!userStoreManager.isExistingUser(username)) {
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + username + " does not exist.");
            }
            return Response.status(Response.Status.NOT_FOUND).entity(
                    new ErrorResponse.ErrorResponseBuilder().setMessage(
                            "User doesn't exist.").build()).build();
        }

        BasicUserInfo user = this.getBasicUserInfo(username);
        return Response.status(Response.Status.OK).entity(user).build();
    } catch (UserStoreException e) {
        String msg = "Error occurred while retrieving information of the user '" + username + "'";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}
 
Example #23
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/search/usernames")
@Override
public Response getUserNames(@QueryParam("filter") String filter, @QueryParam("domain") String domain,
                             @HeaderParam("If-Modified-Since") String timestamp,
                             @QueryParam("offset") int offset, @QueryParam("limit") int limit) {
    if (log.isDebugEnabled()) {
        log.debug("Getting the list of users with all user-related information using the filter : " + filter);
    }
    String userStoreDomain = Constants.PRIMARY_USER_STORE;
    if (domain != null && !domain.isEmpty()) {
        userStoreDomain = domain;
    }
    if (limit == 0){
        //If there is no limit is passed, then return all.
        limit = -1;
    }
    List<UserInfo> userList;
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        String[] users = userStoreManager.listUsers(userStoreDomain + "/" + filter + "*", limit);
        userList = new ArrayList<>();
        UserInfo user;
        for (String username : users) {
            user = new UserInfo();
            user.setUsername(username);
            user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
            user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
            user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
            userList.add(user);
        }
        return Response.status(Response.Status.OK).entity(userList).build();
    } catch (UserStoreException e) {
        String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}
 
Example #24
Source File: IdentityProviderManager.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private void verifyAndUpdateRoleConfiguration(String tenantDomain, int tenantId,
                                              PermissionsAndRoleConfig roleConfiguration)
        throws IdentityProviderManagementException {

    List<RoleMapping> validRoleMappings = new ArrayList<>();
    List<String> validIdPRoles = new ArrayList<>();

    for (RoleMapping mapping : roleConfiguration.getRoleMappings()) {
        try {
            if (mapping.getRemoteRole() == null || mapping.getLocalRole() == null || StringUtils
                    .isBlank(mapping.getLocalRole().getLocalRoleName())) {
                continue;
            }

            UserStoreManager usm = IdPManagementServiceComponent.getRealmService().getTenantUserRealm(tenantId)
                    .getUserStoreManager();
            String role = mapping.getLocalRole().getLocalRoleName();
            if (StringUtils.isNotBlank(mapping.getLocalRole().getUserStoreId())) {
                role = IdentityUtil.addDomainToName(role, mapping.getLocalRole().getUserStoreId());
            }
            // Remove invalid mappings if local role does not exists.
            if (usm.isExistingRole(role)) {
                validRoleMappings.add(mapping);
                validIdPRoles.add(mapping.getRemoteRole());
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Invalid local role name: " + role + " for the federated role: " + mapping
                            .getRemoteRole());
                }
            }
        } catch (UserStoreException e) {
            throw new IdentityProviderManagementException(
                    "Error occurred while retrieving UserStoreManager for tenant " + tenantDomain, e);
        }
    }

    roleConfiguration.setRoleMappings(validRoleMappings.toArray(new RoleMapping[0]));
    roleConfiguration.setIdpRoles(validIdPRoles.toArray(new String[0]));
}
 
Example #25
Source File: UserIdentityManagementAdminService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Admin locks the user account. Only the admin can unlock the account using
 * the {@literal unlockUserAccount} method.
 *
 * @param userName
 * @throws IdentityMgtServiceException
 */
public void lockUserAccount(String userName) throws IdentityMgtServiceException {

    try {
        UserStoreManager userStoreManager = getUserStore(userName);
        String userNameWithoutDomain = UserCoreUtil.removeDomainFromName(userName);
        UserIdentityManagementUtil.lockUserAccount(userNameWithoutDomain, userStoreManager);
        log.info("User account locked: " + userName);
    } catch (UserStoreException|IdentityException e) {
        log.error("Error occurred while trying to lock the account " + userName, e);
        throw new IdentityMgtServiceException("Error occurred while trying to lock the account " + userName, e);
    }
}
 
Example #26
Source File: RegistryTopicManager.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new role which has the same name as the destinationName and assign the logged in
 * user to the newly created role. Then, authorize the newly created role to subscribe and
 * publish to the destination.
 *
 * @param username        name of the logged in user
 * @param destinationName destination name. Either topic or queue name
 * @param destinationId   ID given to the destination
 * @param userRealm       the  user store
 * @throws UserStoreException
 */
private static void authorizePermissionsToLoggedInUser(String username, String destinationName,
                                                       String destinationId,
                                                       UserRealm userRealm) throws
                                                                            UserStoreException {

    //For registry we use a modified queue name
    String newDestinationName = destinationName.replace("@", AT_REPLACE_CHAR);

    // creating the internal role name
    String roleName = UserCoreUtil.addInternalDomainName(TOPIC_ROLE_PREFIX +
                                                         newDestinationName.replace("/", "-"));

    // the interface to store user data
    UserStoreManager userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();

    if (!userStoreManager.isExistingRole(roleName)) {
        String[] user = {MultitenantUtils.getTenantAwareUsername(username)};

        // adds the internal role to user store
        userStoreManager.addRole(roleName, user, null);
        // gives subscribe permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_SUBSCRIBE);
        // gives publish permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_PUBLISH);
        // gives change permissions to the internal role in the user store
        userRealm.getAuthorizationManager().authorizeRole(
                roleName, destinationId, EventBrokerConstants.EB_PERMISSION_CHANGE_PERMISSION);

    } else {
        log.warn("Unable to provide permissions to the user, " +
                 " " + username + ", to subscribe and publish to " + newDestinationName);
    }
}
 
Example #27
Source File: UserStoreCountService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private UserStoreManager getUserStoreManager() throws UserStoreCounterException {

        if (UserStoreCountDSComponent.getRealmService() == null) {
            String errorMsg = "Unable to retrieve realm service";
            throw new UserStoreCounterException(errorMsg);
        }
        try {
            return UserStoreCountDSComponent.getRealmService().getTenantUserRealm(tenantId).getUserStoreManager();
        } catch (UserStoreException e) {
            throw new UserStoreCounterException("Error while retrieving userStoreManager");
        }
    }
 
Example #28
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void addMultiAttributeSperatorToRequestedClaims(AuthenticatedUser authenticatedUser,
                                                        org.wso2.carbon.user.core.UserStoreManager userStore,
                                                        Map<String, String> spRequestedClaims) {
    if (!spRequestedClaims.isEmpty()) {
        RealmConfiguration realmConfiguration = userStore.getRealmConfiguration();

        String claimSeparator = realmConfiguration.getUserStoreProperty(IdentityCoreConstants
                .MULTI_ATTRIBUTE_SEPARATOR);
        if (StringUtils.isNotBlank(claimSeparator)) {
            spRequestedClaims.put(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR, claimSeparator);
        }
    }
}
 
Example #29
Source File: DefaultClaimHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Map<String, String> retrieveAllNunNullUserClaimValues(AuthenticatedUser authenticatedUser,
                                                              String tenantDomain,
                                                              String tenantAwareUserName, ClaimManager claimManager,
                                                              UserStoreManager userStore)
        throws FrameworkException {

    Map<String, String> allLocalClaims = new HashMap<>();
    try {

        org.wso2.carbon.user.api.ClaimMapping[] claimMappings = claimManager
                .getAllClaimMappings(ApplicationConstants.LOCAL_IDP_DEFAULT_CLAIM_DIALECT);
        List<String> localClaimURIs = new ArrayList<>();
        for (org.wso2.carbon.user.api.ClaimMapping mapping : claimMappings) {
            String claimURI = mapping.getClaim().getClaimUri();
            localClaimURIs.add(claimURI);
        }
        allLocalClaims = userStore.getUserClaimValues(tenantAwareUserName,
                localClaimURIs.toArray(new String[localClaimURIs.size()]), null);
    } catch (UserStoreException e) {
        if (e.getMessage().contains("UserNotFound")) {
            if (log.isDebugEnabled()) {
                log.debug("User " + tenantAwareUserName + " not found in user store");
            }
        } else {
            throw new FrameworkException("Error occurred while getting all user claims for " +
                    authenticatedUser + " in " + tenantDomain, e);
        }
    }
    if (allLocalClaims == null) {
        allLocalClaims = new HashMap<>();
    }
    return allLocalClaims;
}
 
Example #30
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{username}/roles")
@Override
public Response getRolesOfUser(@PathParam("username") String username, @QueryParam("domain") String domain) {
    if (domain != null && !domain.isEmpty()) {
        username = domain + '/' + username;
    }
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        if (!userStoreManager.isExistingUser(username)) {
            if (log.isDebugEnabled()) {
                log.debug("User by username: " + username + " does not exist for role retrieval.");
            }
            return Response.status(Response.Status.NOT_FOUND).entity(
                    new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username +
                            " does not exist for role retrieval.").build()).build();
        }

        RoleList result = new RoleList();
        result.setList(getFilteredRoles(userStoreManager, username));
        return Response.status(Response.Status.OK).entity(result).build();
    } catch (UserStoreException e) {
        String msg = "Error occurred while trying to retrieve roles of the user '" + username + "'";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}