Java Code Examples for org.wso2.carbon.user.api.UserStoreManager#setUserClaimValues()

The following examples show how to use org.wso2.carbon.user.api.UserStoreManager#setUserClaimValues() . 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: FrameworkUtils.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private static String addUserId(String username, UserStoreManager userStoreManager) {

        String userId;
        userId = UUID.randomUUID().toString();
        Map<String, String> claims = new HashMap<>();
        claims.put(UserCoreClaimConstants.USER_ID_CLAIM_URI, userId);
        try {
            userStoreManager.setUserClaimValues(username, claims, null);
        } catch (UserStoreException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while updating " + UserCoreClaimConstants.USER_ID_CLAIM_URI + " claim of the user: "
                        + username + " with the unique user id.");
            }
        }
        return userId;
    }
 
Example 2
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 3
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 4
Source File: UserIdentityManagementAdminService.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * User updates/add account recovery data such as the email address or the
 * phone number etc.
 *
 * @param userIdentityClaims
 * @throws IdentityMgtServiceException
 */
public void updateUserIdentityClaims(UserIdentityClaimDTO[] userIdentityClaims)
        throws IdentityMgtServiceException {
    String userName = CarbonContext.getThreadLocalCarbonContext().getUsername();

    try {
        UserStoreManager userStoreManager = IdentityMgtServiceComponent.getRealmService()
                .getTenantUserRealm(CarbonContext.getThreadLocalCarbonContext().getTenantId())
                .getUserStoreManager();

        Map<String, String> claims = new HashMap<String, String>();
        for (UserIdentityClaimDTO dto : userIdentityClaims) {
            if (dto.getClaimUri().contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI)) {
                log.warn("WARNING! User " + userName + " tried to alter " + dto.getClaimUri());
                throw IdentityException.error("Updates to the claim " + dto.getClaimUri() +
                        " are not allowed");
            }
            claims.put(dto.getClaimUri(), dto.getClaimValue());
        }
        userStoreManager.setUserClaimValues(userName, claims, null);

    } catch (UserStoreException|IdentityException e) {
        String errorMessage = "Error while updating identity recovery data for : " + userName;
        log.error(errorMessage, e);
        throw new IdentityMgtServiceException(errorMessage, e);
    }
}
 
Example 5
Source File: UserIdentityManagementAdminService.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * User updates/add account recovery data such as the email address or the
 * phone number etc.
 *
 * @param userIdentityClaims
 * @throws IdentityMgtServiceException
 */
public void updateUserIdentityClaims(UserIdentityClaimDTO[] userIdentityClaims)
        throws IdentityMgtServiceException {
    String userName = CarbonContext.getThreadLocalCarbonContext().getUsername();

    try {
        UserStoreManager userStoreManager = IdentityMgtServiceComponent.getRealmService()
                .getTenantUserRealm(CarbonContext.getThreadLocalCarbonContext().getTenantId())
                .getUserStoreManager();

        Map<String, String> claims = new HashMap<String, String>();
        for (UserIdentityClaimDTO dto : userIdentityClaims) {
            if (dto.getClaimUri().contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI)) {
                log.warn("WARNING! User " + userName + " tried to alter " + dto.getClaimUri());
                throw IdentityException.error("Updates to the claim " + dto.getClaimUri() +
                        " are not allowed");
            }
            claims.put(dto.getClaimUri(), dto.getClaimValue());
        }
        userStoreManager.setUserClaimValues(userName, claims, null);

    } catch (UserStoreException|IdentityException e) {
        String errorMessage = "Error while updating identity recovery data for : " + userName;
        log.error(errorMessage, e);
        throw new IdentityMgtServiceException(errorMessage, e);
    }
}
 
Example 6
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@PUT
@Path("/{username}")
@Override
public Response updateUser(@PathParam("username") String username, @QueryParam("domain") String domain, UserInfo userInfo) {
    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 +
                        " doesn't exists. Therefore, request made to update user was refused.");
            }
            return Response.status(Response.Status.NOT_FOUND).entity(
                    new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
                            username + " doesn't  exist.").build()).build();
        }

        Map<String, String> defaultUserClaims =
                this.buildDefaultUserClaims(userInfo.getFirstname(), userInfo.getLastname(),
                        userInfo.getEmailAddress());
        if (StringUtils.isNotEmpty(userInfo.getPassword())) {
            // Decoding Base64 encoded password
            userStoreManager.updateCredentialByAdmin(username,
                    userInfo.getPassword());
            log.debug("User credential of username: " + username + " has been changed");
        }
        List<String> currentRoles = this.getFilteredRoles(userStoreManager, username);

        List<String> newRoles = new ArrayList<>();
        if (userInfo.getRoles() != null) {
            newRoles = Arrays.asList(userInfo.getRoles());
        }

        List<String> rolesToAdd = new ArrayList<>(newRoles);
        List<String> rolesToDelete = new ArrayList<>();

        for (String role : currentRoles) {
            if (newRoles.contains(role)) {
                rolesToAdd.remove(role);
            } else {
                rolesToDelete.add(role);
            }
        }
        rolesToDelete.remove(ROLE_EVERYONE);
        rolesToAdd.remove(ROLE_EVERYONE);
        userStoreManager.updateRoleListOfUser(username,
                rolesToDelete.toArray(new String[rolesToDelete.size()]),
                rolesToAdd.toArray(new String[rolesToAdd.size()]));
        userStoreManager.setUserClaimValues(username, defaultUserClaims, null);
        // Outputting debug message upon successful addition of user
        if (log.isDebugEnabled()) {
            log.debug("User by username: " + username + " was successfully updated.");
        }

        BasicUserInfo updatedUserInfo = this.getBasicUserInfo(username);
        return Response.ok().entity(updatedUserInfo).build();
    } catch (UserStoreException e) {
        String msg = "Error occurred while trying to update user '" + username + "'";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}
 
Example 7
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@PUT
@Path("/{username}")
@Override
public Response updateUser(@PathParam("username") String username, @QueryParam("domain") String domain, UserInfo userInfo) {
    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 +
                        " doesn't exists. Therefore, request made to update user was refused.");
            }
            return Response.status(Response.Status.NOT_FOUND).entity(
                    new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
                            username + " doesn't  exist.").build()).build();
        }

        Map<String, String> defaultUserClaims =
                this.buildDefaultUserClaims(userInfo.getFirstname(), userInfo.getLastname(),
                        userInfo.getEmailAddress());
        if (StringUtils.isNotEmpty(userInfo.getPassword())) {
            // Decoding Base64 encoded password
            userStoreManager.updateCredentialByAdmin(username,
                    userInfo.getPassword());
            log.debug("User credential of username: " + username + " has been changed");
        }
        List<String> currentRoles = this.getFilteredRoles(userStoreManager, username);

        List<String> newRoles = new ArrayList<>();
        if (userInfo.getRoles() != null) {
            newRoles = Arrays.asList(userInfo.getRoles());
        }

        List<String> rolesToAdd = new ArrayList<>(newRoles);
        List<String> rolesToDelete = new ArrayList<>();

        for (String role : currentRoles) {
            if (newRoles.contains(role)) {
                rolesToAdd.remove(role);
            } else {
                rolesToDelete.add(role);
            }
        }
        rolesToDelete.remove(ROLE_EVERYONE);
        rolesToAdd.remove(ROLE_EVERYONE);
        userStoreManager.updateRoleListOfUser(username,
                rolesToDelete.toArray(new String[rolesToDelete.size()]),
                rolesToAdd.toArray(new String[rolesToAdd.size()]));
        userStoreManager.setUserClaimValues(username, defaultUserClaims, null);
        // Outputting debug message upon successful addition of user
        if (log.isDebugEnabled()) {
            log.debug("User by username: " + username + " was successfully updated.");
        }

        BasicUserInfo updatedUserInfo = this.getBasicUserInfo(username);
        return Response.ok().entity(updatedUserInfo).build();
    } catch (UserStoreException e) {
        String msg = "Error occurred while trying to update user '" + username + "'";
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}
 
Example 8
Source File: UserStoreBasedIdentityDataStore.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * This method stores data in the read write user stores.
 */
@Override
public void store(UserIdentityClaimsDO userIdentityDTO, UserStoreManager userStoreManager) throws IdentityException {

    UserIdentityClaimsDO newIdentityClaimDO = new UserIdentityClaimsDO(userIdentityDTO.getUserName(),
            userIdentityDTO.getUserDataMap());
    super.store(newIdentityClaimDO, userStoreManager);

    if (userIdentityDTO.getUserName() == null) {
        log.error("Error while persisting user data.  Null user name is provided.");
        return;
    }
    String username = UserCoreUtil.removeDomainFromName(userIdentityDTO.getUserName());

        try {
            // Check if the user store is read only. If it is read only and still uses user store based data
            // store then log a warn.
            if(!userStoreManager.isReadOnly()) {
                // Need to clone the map. If not iterative calls will refer the same map
                userStoreManager.setUserClaimValues(username, new HashMap<String,String>
                        (userIdentityDTO.getUserDataMap()), null);
            } else {
                // If the user store is read only and still uses UserStoreBasedIdentityDataStore, then log a warn
                log.warn("User store is read only. Changes to identities are only stored in memory, " +
                        "and not updated in user store.");
                return;
            }
        } catch (UserStoreException e) {
            if(!e.getMessage().startsWith(IdentityCoreConstants.USER_NOT_FOUND)){
                throw IdentityException.error("Error while persisting identity user data in to user store", e);
            } else if (log.isDebugEnabled()){
                String message = null;
                if(userStoreManager instanceof AbstractUserStoreManager){
                    String domain = ((AbstractUserStoreManager)userStoreManager).getRealmConfiguration()
                            .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                    if(domain != null){
                        message = "User: " + username + " does not exist in " + domain;
                    }
                }
                if(message == null) {
                    message = "User: " + username + " does not exist";
                }
                log.debug(message);
                return;
            }
        }
}