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

The following examples show how to use org.wso2.carbon.user.api.UserStoreManager#isExistingUser() . 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: 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 2
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 3
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 4
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 5
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 6
Source File: UserIdentityManagementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Enable the user account
 *
 * @param userName
 * @param userStoreManager
 * @throws IdentityException
 */
public static void enableUserAccount(String userName, UserStoreManager userStoreManager)
        throws IdentityException {

    if (!isIdentityMgtListenerEnable()) {
        throw IdentityException.error("Cannot enable 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 + "to enable");
        }
    } catch (UserStoreException e) {
        log.error("Error while reading user identity data", e);
        throw IdentityException.error("Error while enabling user account " + userName);

    }

    UserIdentityDataStore store = IdentityMgtConfig.getInstance().getIdentityDataStore();
    UserIdentityClaimsDO userIdentityDO = store.load(UserCoreUtil.removeDomainFromName(userName), userStoreManager);
    if (userIdentityDO != null) {
        userIdentityDO.setAccountDisabled(false);
        store.store(userIdentityDO, userStoreManager);
    } else {
        throw IdentityException.error("No user account found for user " + userName);
    }

}
 
Example 7
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 8
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{username}")
@Override
public Response removeUser(@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 removal.");
            }
            return Response.status(Response.Status.NOT_FOUND).entity(
                    new ErrorResponse.ErrorResponseBuilder().setMessage("User '" +
                            username + "' does not exist for removal.").build()).build();
        }
        // Un-enroll all devices for the user
        DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
        deviceManagementService.setStatus(username, EnrolmentInfo.Status.REMOVED);

        userStoreManager.deleteUser(username);
        if (log.isDebugEnabled()) {
            log.debug("User '" + username + "' was successfully removed.");
        }
        return Response.status(Response.Status.OK).build();
    } catch (DeviceManagementException | UserStoreException e) {
        String msg = "Exception in trying to remove user by username: " + username;
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}
 
Example 9
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();
    }
}
 
Example 10
Source File: UserIdentityManagementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Disable the user account.
 *
 * @param userName
 * @param userStoreManager
 * @throws IdentityException
 */
public static void disableUserAccount(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 + "to disable");
        }
    } catch (UserStoreException e) {
        log.error("Error while reading user identity data", e);
        throw IdentityException.error("Error while disabling user account : " + userName);

    }

    UserIdentityDataStore store = IdentityMgtConfig.getInstance().getIdentityDataStore();
    UserIdentityClaimsDO userIdentityDO = store.load(UserCoreUtil.removeDomainFromName(userName), userStoreManager);
    if (userIdentityDO != null) {
        userIdentityDO.setAccountDisabled(true);
        store.store(userIdentityDO, userStoreManager);
    } else {
        throw IdentityException.error("No user account found for user " + userName);
    }
}
 
Example 11
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 12
Source File: UserManagementServiceImpl.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{username}")
@Override
public Response removeUser(@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 removal.");
            }
            return Response.status(Response.Status.NOT_FOUND).entity(
                    new ErrorResponse.ErrorResponseBuilder().setMessage("User '" +
                            username + "' does not exist for removal.").build()).build();
        }
        // Un-enroll all devices for the user
        DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
        deviceManagementService.setStatus(username, EnrolmentInfo.Status.REMOVED);

        userStoreManager.deleteUser(username);
        if (log.isDebugEnabled()) {
            log.debug("User '" + username + "' was successfully removed.");
        }
        return Response.status(Response.Status.OK).build();
    } catch (DeviceManagementException | UserStoreException e) {
        String msg = "Exception in trying to remove user by username: " + username;
        log.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
    }
}
 
Example 13
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();
    }
}
 
Example 14
Source File: UserIdentityManagementUtil.java    From carbon-identity with Apache License 2.0 5 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);
        }
    } catch (UserStoreException e) {
        log.error("Error while reading user identity data", e);
        throw IdentityException.error("Error while lock user account : " + userName);

    }

    UserIdentityDataStore store = IdentityMgtConfig.getInstance().getIdentityDataStore();
    UserIdentityClaimsDO userIdentityDO = store.load(UserCoreUtil.removeDomainFromName(userName), userStoreManager);
    if (userIdentityDO != null) {
        userIdentityDO.setAccountLock(true);
        userIdentityDO.setUnlockTime(0);
        store.store(userIdentityDO, userStoreManager);
    } else {
        throw IdentityException.error("No user account found for user " + userName);
    }
}
 
Example 15
Source File: UserIdentityManagementUtil.java    From carbon-identity with Apache License 2.0 5 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);
        }
    } catch (UserStoreException e) {
        log.error("Error while reading user identity data", e);
        throw IdentityException.error("Error while unlock user account " + userName);

    }

    UserIdentityDataStore store = IdentityMgtConfig.getInstance().getIdentityDataStore();
    UserIdentityClaimsDO userIdentityDO = store.load(UserCoreUtil.removeDomainFromName(userName), userStoreManager);
    if (userIdentityDO != null) {
        userIdentityDO.setAccountLock(false);
        userIdentityDO.setUnlockTime(0);
        store.store(userIdentityDO, userStoreManager);
    } else {
        throw IdentityException.error("No user account found for user " + userName);
    }

}
 
Example 16
Source File: MutualAuthHostObject.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the provided user name against user store
 * @param cx context
 * @param thisObj this object
 * @param args arguments
 * @return boolean
 * @throws Exception
 */
public static boolean jsFunction_validateUserNameHeader(Context cx, Scriptable thisObj,
                                                        Object[] args, Function funObj) throws Exception {

    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String) ) {
        throw new ScriptException("Invalid argument. User Name is not set properly");
    }

    boolean isValidUser = false;
    String userNameHeader = (String) args[0];

    try {

        String tenantDomain = MultitenantUtils.getTenantDomain(userNameHeader);
        String userName = MultitenantUtils.getTenantAwareUsername(userNameHeader);
        TenantManager tenantManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager();
        int tenantId = tenantManager.getTenantId(tenantDomain);

        UserStoreManager userstore = ServiceReferenceHolder.getInstance().getRealmService().
                getTenantUserRealm(tenantId).getUserStoreManager();

        if (userstore.isExistingUser(userName)) {
            isValidUser = true;
        }

    } catch (Exception e) {
        log.error("Error validating the user " + e.getMessage(), e);
        throw new ScriptException("Error validating the user " + userNameHeader);

    }

    return isValidUser;

}
 
Example 17
Source File: UserSignUpWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Method updates Roles users with list of roles
 * @param serverURL
 * @param adminUsername
 * @param adminPassword
 * @param userName
 * @param tenantID
 * @param role
 * @throws Exception
 */
protected static void updateRolesOfUser(String serverURL, String adminUsername,
                                        String adminPassword, String userName,
                                        List<String> roleList, String tenantDomain)
                                        		throws Exception {

	if (log.isDebugEnabled()) {
		log.debug("Adding roles to " + userName + "in " + tenantDomain + " Domain");
	}
	String url = serverURL + "UserAdmin";
	RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
	int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
			.getTenantId(tenantDomain);
	UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
	UserStoreManager manager = realm.getUserStoreManager();
	
	if(manager.isExistingUser(userName)) {
		// check whether given roles exist
		for (String role : roleList) {
			if (!manager.isExistingRole(role)) {
				log.error("Could not find role " + role + " in the user store");
				throw new Exception("Could not find role " + role + " in the user store");
			}
		}

		UserAdminStub userAdminStub = new UserAdminStub(url);
		CarbonUtils.setBasicAccessSecurityHeaders(adminUsername, adminPassword, userAdminStub._getServiceClient());
		
		FlaggedName[] flaggedNames = userAdminStub.getRolesOfUser(userName, "*", -1);
		List<String> roles = new ArrayList<String>();
		if (flaggedNames != null) {
			for (FlaggedName flaggedName : flaggedNames) {
				if (flaggedName.getSelected()) {
					roles.add(flaggedName.getItemName());
				}
			}
		}
		roles.addAll(roleList);
		userAdminStub.updateRolesOfUser(userName, roles.toArray(new String[roles.size()]));
	} else {
		log.error("User does not exist. Unable to approve user " + userName);
	} 
	
}
 
Example 18
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 19
Source File: RecoveryProcessor.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies user id with underline user store
 *
 * @param sequence TODO
 * @param userDTO  bean class that contains user and tenant Information
 * @return true/false whether user is verified or not. If user is a tenant
 * user then always return false
 */
public VerificationBean verifyUserForRecovery(int sequence, UserDTO userDTO) {

    String userId = userDTO.getUserId();
    int tenantId = userDTO.getTenantId();
    boolean success = false;
    VerificationBean bean = null;
    try {
        UserStoreManager userStoreManager = IdentityMgtServiceComponent.getRealmService().
                getTenantUserRealm(tenantId).getUserStoreManager();

        if (userStoreManager.isExistingUser(userId)) {
            if (IdentityMgtConfig.getInstance().isAuthPolicyAccountLockCheck()) {
                String accountLock = Utils.getClaimFromUserStoreManager(
                        userId, tenantId, UserIdentityDataStore.ACCOUNT_LOCK);
                if (!Boolean.parseBoolean(accountLock)) {
                    success = true;
                } else {
                    //account is Locked. Not allowing to recover.
                }
            } else if (IdentityMgtConfig.getInstance().isAuthPolicyAccountDisableCheck()) {
                String accountDisable = Utils.getClaimFromUserStoreManager(
                        userId, tenantId, UserIdentityDataStore.ACCOUNT_DISABLED);
                if (!Boolean.parseBoolean(accountDisable)) {
                    success = true;
                } else {
                    //account is Disabled. Not allowing to recover.
                    if (log.isDebugEnabled()) {
                        log.debug("Account is disabled. Can not allow to recover.");
                    }
                    bean = new VerificationBean(VerificationBean.ERROR_CODE_DISABLED_ACCOUNT);
                }
            } else {
                success = true;
            }
        } else {
            log.error("User with user name : " + userId
                    + " does not exists in tenant domain : " + userDTO.getTenantDomain());
            bean = new VerificationBean(VerificationBean.ERROR_CODE_INVALID_USER + " "
                    + "User does not exists");
        }

        if (success) {
            String internalCode = generateUserCode(sequence, userId);
            String key = UUID.randomUUID().toString();
            UserRecoveryDataDO dataDO =
                    new UserRecoveryDataDO(userId, tenantId, internalCode, key);
            if (sequence != 3) {
                dataStore.invalidate(userId, tenantId);
            }
            dataStore.store(dataDO);
            log.info("User verification successful for user : " + userId +
                    " from tenant domain :" + userDTO.getTenantDomain());

            bean = new VerificationBean(userId, getUserExternalCodeStr(internalCode));
        }
    } catch (Exception e) {
        String errorMessage = "Error verifying user : " + userId;
        log.error(errorMessage, e);
        bean = new VerificationBean(VerificationBean.ERROR_CODE_UNEXPECTED + " "
                + errorMessage);
    }

    if (bean == null) {
        bean = new VerificationBean(VerificationBean.ERROR_CODE_UNEXPECTED);
    }
    return bean;
}
 
Example 20
Source File: RecoveryProcessor.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies user id with underline user store
 *
 * @param sequence TODO
 * @param userDTO  bean class that contains user and tenant Information
 * @return true/false whether user is verified or not. If user is a tenant
 * user then always return false
 */
public VerificationBean verifyUserForRecovery(int sequence, UserDTO userDTO) {

    String userId = userDTO.getUserId();
    int tenantId = userDTO.getTenantId();
    boolean success = false;
    VerificationBean bean = null;
    try {
        UserStoreManager userStoreManager = IdentityMgtServiceComponent.getRealmService().
                getTenantUserRealm(tenantId).getUserStoreManager();

        if (userStoreManager.isExistingUser(userId)) {
            if (IdentityMgtConfig.getInstance().isAuthPolicyAccountLockCheck()) {
                String accountLock = userStoreManager.
                        getUserClaimValue(userId, UserIdentityDataStore.ACCOUNT_LOCK, null);
                if (!Boolean.parseBoolean(accountLock)) {
                    success = true;
                }
            } else {
                success = true;
            }
        } else {
            log.error("User with user name : " + userId
                    + " does not exists in tenant domain : " + userDTO.getTenantDomain());
            bean = new VerificationBean(VerificationBean.ERROR_CODE_INVALID_USER + " "
                    + "User does not exists");
        }

        if (success) {
            String internalCode = generateUserCode(sequence, userId);
            String key = UUID.randomUUID().toString();
            UserRecoveryDataDO dataDO =
                    new UserRecoveryDataDO(userId, tenantId, internalCode, key);
            if (sequence != 3) {
                dataStore.invalidate(userId, tenantId);
            }
            dataStore.store(dataDO);
            log.info("User verification successful for user : " + userId +
                    " from tenant domain :" + userDTO.getTenantDomain());

            bean = new VerificationBean(userId, getUserExternalCodeStr(internalCode));
        }
    } catch (Exception e) {
        String errorMessage = "Error verifying user : " + userId;
        log.error(errorMessage, e);
        bean = new VerificationBean(VerificationBean.ERROR_CODE_UNEXPECTED + " "
                + errorMessage);
    }

    if (bean == null) {
        bean = new VerificationBean(VerificationBean.ERROR_CODE_UNEXPECTED);
    }
    return bean;
}