Search in sources :

Example 6 with IdentityMgtConfig

use of org.wso2.carbon.identity.mgt.IdentityMgtConfig in project carbon-identity-framework by wso2.

the class IdentityMgtEventListener method doPreAuthenticate.

/**
 * This method checks if the user account exist or is locked. If the account is
 * locked, the authentication process will be terminated after this method
 * returning false.
 */
@Override
public boolean doPreAuthenticate(String userName, Object credential, UserStoreManager userStoreManager) throws UserStoreException {
    if (!isEnable()) {
        return true;
    }
    // Top level try and finally blocks are used to unset thread local variables
    try {
        if (!IdentityUtil.threadLocalProperties.get().containsKey(DO_PRE_AUTHENTICATE)) {
            IdentityUtil.threadLocalProperties.get().put(DO_PRE_AUTHENTICATE, true);
            if (log.isDebugEnabled()) {
                log.debug("Pre authenticator is called in IdentityMgtEventListener");
            }
            IdentityUtil.clearIdentityErrorMsg();
            IdentityMgtConfig config = IdentityMgtConfig.getInstance();
            if (!config.isEnableAuthPolicy()) {
                return true;
            }
            String domainName = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
            String usernameWithDomain = UserCoreUtil.addDomainToName(userName, domainName);
            boolean isUserExistInCurrentDomain = userStoreManager.isExistingUser(usernameWithDomain);
            if (!isUserExistInCurrentDomain) {
                IdentityErrorMsgContext customErrorMessageContext = new IdentityErrorMsgContext(UserCoreConstants.ErrorCode.USER_DOES_NOT_EXIST);
                IdentityUtil.setIdentityErrorMsg(customErrorMessageContext);
                if (log.isDebugEnabled()) {
                    log.debug("Username :" + userName + "does not exists in the system, ErrorCode :" + UserCoreConstants.ErrorCode.USER_DOES_NOT_EXIST);
                }
                if (config.isAuthPolicyAccountExistCheck()) {
                    throw new UserStoreException(UserCoreConstants.ErrorCode.USER_DOES_NOT_EXIST);
                }
            } else {
                UserIdentityClaimsDO userIdentityDTO = module.load(userName, userStoreManager);
                if (userIdentityDTO == null) {
                    return true;
                }
                // If account is disabled, user should not be able to log in
                if (userIdentityDTO.getIsAccountDisabled()) {
                    IdentityErrorMsgContext customErrorMessageContext = new IdentityErrorMsgContext(IdentityCoreConstants.USER_ACCOUNT_DISABLED);
                    IdentityUtil.setIdentityErrorMsg(customErrorMessageContext);
                    String errorMsg = "User account is disabled for user : " + userName;
                    log.warn(errorMsg);
                    throw new UserStoreException(IdentityCoreConstants.USER_ACCOUNT_DISABLED_ERROR_CODE + " " + errorMsg);
                }
                // if the account is locked, should not be able to log in
                if (userIdentityDTO.isAccountLocked()) {
                    // If unlock time is specified then unlock the account.
                    if ((userIdentityDTO.getUnlockTime() != 0) && (System.currentTimeMillis() >= userIdentityDTO.getUnlockTime())) {
                        userIdentityDTO.getUserDataMap().put(UserIdentityDataStore.ACCOUNT_LOCKED_REASON, "");
                        userIdentityDTO.setAccountLock(false);
                        userIdentityDTO.setUnlockTime(0);
                        try {
                            module.store(userIdentityDTO, userStoreManager);
                        } catch (IdentityException e) {
                            throw new UserStoreException("Error while saving user store data for user : " + userName, e);
                        }
                    } else {
                        IdentityErrorMsgContext customErrorMessageContext = new IdentityErrorMsgContext(UserCoreConstants.ErrorCode.USER_IS_LOCKED + ":" + userIdentityDTO.getUserDataMap().get(UserIdentityDataStore.ACCOUNT_LOCKED_REASON), userIdentityDTO.getFailAttempts(), config.getAuthPolicyMaxLoginAttempts());
                        if (IdentityMgtConstants.LockedReason.MAX_ATTEMTS_EXCEEDED.toString().equals(userIdentityDTO.getUserDataMap().get(UserIdentityDataStore.ACCOUNT_LOCKED_REASON))) {
                            customErrorMessageContext.setFailedLoginAttempts(config.getAuthPolicyMaxLoginAttempts());
                        }
                        IdentityUtil.setIdentityErrorMsg(customErrorMessageContext);
                        String errorMsg = "User account is locked for user : " + userName + ". cannot login until the account is unlocked ";
                        log.warn(errorMsg);
                        throw new UserStoreException(UserCoreConstants.ErrorCode.USER_IS_LOCKED + " " + errorMsg);
                    }
                }
            }
        }
        return true;
    } finally {
        // remove thread local variable
        IdentityUtil.threadLocalProperties.get().remove(DO_PRE_AUTHENTICATE);
    }
}
Also used : UserStoreException(org.wso2.carbon.user.core.UserStoreException) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO) IdentityException(org.wso2.carbon.identity.base.IdentityException) IdentityErrorMsgContext(org.wso2.carbon.identity.core.model.IdentityErrorMsgContext)

Example 7 with IdentityMgtConfig

use of org.wso2.carbon.identity.mgt.IdentityMgtConfig in project carbon-identity-framework by wso2.

the class IdentityMgtEventListener method doPreAddUser.

/**
 * This method will set the default/random password if the password provided is
 * null. The thread local parameter EMPTY_PASSWORD_USED will be used to
 * track if the password empty in the doPostAddUser.
 * This method will filter the security question URIs from claims and put those
 * to the thread local properties.
 */
@Override
public boolean doPreAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims, String profile, UserStoreManager userStoreManager) throws UserStoreException {
    if (!isEnable()) {
        return true;
    }
    if (log.isDebugEnabled()) {
        log.debug("Pre add user is called in IdentityMgtEventListener");
    }
    // Removing existing thread local before setting
    IdentityUtil.threadLocalProperties.get().remove(EMPTY_PASSWORD_USED);
    IdentityUtil.threadLocalProperties.get().remove(USER_IDENTITY_DO);
    IdentityMgtConfig config = IdentityMgtConfig.getInstance();
    try {
        // Enforcing the password policies.
        if (credential != null && (credential instanceof StringBuffer && (credential.toString().trim().length() > 0))) {
            policyRegistry.enforcePasswordPolicies(credential.toString(), userName);
        }
    } catch (PolicyViolationException pe) {
        throw new UserStoreException(pe.getMessage(), pe);
    }
    // empty password account creation
    if (credential == null || (credential instanceof StringBuffer && (credential.toString().trim().length() < 1))) {
        if (!config.isEnableTemporaryPassword()) {
            log.error("Temporary password property is disabled");
            throw new UserStoreException(ASK_PASSWORD_FEATURE_IS_DISABLED);
        }
        if (log.isDebugEnabled()) {
            log.debug("Credentials are null. Using a temporary password as credentials");
        }
        // setting the thread-local to check in doPostAddUser
        IdentityUtil.threadLocalProperties.get().put(EMPTY_PASSWORD_USED, true);
        // temporary passwords will be used
        char[] temporaryPassword = null;
        temporaryPassword = UserIdentityManagementUtil.generateTemporaryPassword();
        // setting the password value
        ((StringBuffer) credential).replace(0, temporaryPassword.length, new String(temporaryPassword));
    }
    // Filtering security question URIs from claims and add them to the thread local dto
    Map<String, String> userDataMap = new HashMap<String, String>();
    // TODO why challenge Q
    Iterator<Entry<String, String>> it = claims.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, String> claim = it.next();
        if (claim.getKey().contains(UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI) || claim.getKey().contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI)) {
            userDataMap.put(claim.getKey(), claim.getValue());
            it.remove();
        }
    }
    UserIdentityClaimsDO identityDTO = new UserIdentityClaimsDO(userName, userDataMap);
    identityDTO.setTenantId(userStoreManager.getTenantId());
    // adding dto to thread local to be read again from the doPostAddUser method
    IdentityUtil.threadLocalProperties.get().put(USER_IDENTITY_DO, identityDTO);
    return true;
}
Also used : Entry(java.util.Map.Entry) HashMap(java.util.HashMap) UserStoreException(org.wso2.carbon.user.core.UserStoreException) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO) PolicyViolationException(org.wso2.carbon.identity.mgt.policy.PolicyViolationException)

Example 8 with IdentityMgtConfig

use of org.wso2.carbon.identity.mgt.IdentityMgtConfig in project carbon-identity-framework by wso2.

the class IdentityMgtEventListener method doPreSetUserClaimValues.

/**
 * As in the above method the user account lock claim, primary challenges
 * claim will be separately handled. Identity claims will be removed from
 * the claim set before adding claims to the user store.
 */
@Override
public boolean doPreSetUserClaimValues(String userName, Map<String, String> claims, String profileName, UserStoreManager userStoreManager) throws UserStoreException {
    if (!isEnable()) {
        return true;
    }
    IdentityUtil.threadLocalProperties.get().remove(IdentityCoreConstants.USER_ACCOUNT_STATE);
    String accountLocked = claims.get(UserIdentityDataStore.ACCOUNT_LOCK);
    boolean isAccountLocked = false;
    // Following logic is to avoid null value been interpreted as false
    if (StringUtils.isNotEmpty(accountLocked)) {
        isAccountLocked = Boolean.parseBoolean(accountLocked);
    }
    // Top level try and finally blocks are used to unset thread local variables
    try {
        if (!IdentityUtil.threadLocalProperties.get().containsKey(DO_PRE_SET_USER_CLAIM_VALUES)) {
            IdentityUtil.threadLocalProperties.get().put(DO_PRE_SET_USER_CLAIM_VALUES, true);
            IdentityMgtConfig config = IdentityMgtConfig.getInstance();
            UserIdentityDataStore identityDataStore = IdentityMgtConfig.getInstance().getIdentityDataStore();
            UserIdentityClaimsDO identityDTO = identityDataStore.load(userName, userStoreManager);
            if (identityDTO == null) {
                identityDTO = new UserIdentityClaimsDO(userName);
                identityDTO.setTenantId(userStoreManager.getTenantId());
            }
            Boolean wasAccountDisabled = identityDTO.getIsAccountDisabled();
            String accountDisabled = claims.get(UserIdentityDataStore.ACCOUNT_DISABLED);
            boolean isAccountDisabled = false;
            if (StringUtils.isNotEmpty(accountDisabled)) {
                isAccountDisabled = Boolean.parseBoolean(accountDisabled);
            } else {
                isAccountDisabled = wasAccountDisabled;
            }
            if (isAccountLocked) {
                IdentityUtil.threadLocalProperties.get().put(IdentityCoreConstants.USER_ACCOUNT_STATE, UserCoreConstants.ErrorCode.USER_IS_LOCKED);
            } else if (isAccountDisabled) {
                IdentityUtil.threadLocalProperties.get().put(IdentityCoreConstants.USER_ACCOUNT_STATE, IdentityCoreConstants.USER_ACCOUNT_DISABLED_ERROR_CODE);
            } else {
            // do nothing
            }
            // account is already disabled and trying to update the claims without enabling it
            if (wasAccountDisabled && isAccountDisabled) {
                claims.clear();
                log.warn("Trying to update claims of a disabled user account. This is not permitted.");
                throw new UserStoreException("User account is disabled, can't update claims without enabling.");
            }
            Iterator<Entry<String, String>> it = claims.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, String> claim = it.next();
                if (claim.getKey().contains(UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI) || claim.getKey().contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI)) {
                    String key = claim.getKey();
                    String value = claim.getValue();
                    if (UserIdentityDataStore.ACCOUNT_LOCK.equals(key) && (Boolean.TRUE.toString()).equalsIgnoreCase(value)) {
                        identityDTO.getUserDataMap().put(UserIdentityDataStore.ACCOUNT_LOCKED_REASON, IdentityMgtConstants.LockedReason.ADMIN_INITIATED.toString());
                    }
                    identityDTO.setUserIdentityDataClaim(key, value);
                    it.remove();
                }
            }
            // storing the identity claims and security questions
            try {
                identityDataStore.store(identityDTO, userStoreManager);
                int tenantId = userStoreManager.getTenantId();
                String domainName = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                String usernameWithDomain = IdentityUtil.addDomainToName(userName, domainName);
                // case of enabling a disabled user account
                if (wasAccountDisabled && !isAccountDisabled && IdentityMgtConfig.getInstance().isAccountEnableNotificationSending()) {
                    sendEmail(usernameWithDomain, tenantId, IdentityMgtConstants.Notification.ACCOUNT_ENABLE);
                // case of disabling an enabled account
                } else if (!wasAccountDisabled && isAccountDisabled && IdentityMgtConfig.getInstance().isAccountDisableNotificationSending()) {
                    sendEmail(usernameWithDomain, tenantId, IdentityMgtConstants.Notification.ACCOUNT_DISABLE);
                }
            } catch (IdentityException e) {
                throw new UserStoreException("Error while saving user store data for user : " + userName, e);
            }
        }
        return true;
    } finally {
        // Remove thread local variable
        IdentityUtil.threadLocalProperties.get().remove(DO_PRE_SET_USER_CLAIM_VALUES);
    }
}
Also used : UserIdentityDataStore(org.wso2.carbon.identity.mgt.store.UserIdentityDataStore) IdentityException(org.wso2.carbon.identity.base.IdentityException) Entry(java.util.Map.Entry) UserStoreException(org.wso2.carbon.user.core.UserStoreException) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO)

Example 9 with IdentityMgtConfig

use of org.wso2.carbon.identity.mgt.IdentityMgtConfig in project carbon-identity-framework by wso2.

the class UserInformationRecoveryService method registerUser.

/**
 * This method is used to register an user in the system. The account will be locked if the
 * Authentication.Policy.Account.Lock.On.Creation is set to true. Else user will be able to
 * login after registration.
 *
 * @param userName
 * @param password
 * @param claims
 * @param profileName
 * @param tenantDomain
 * @return
 * @throws IdentityMgtServiceException
 */
public VerificationBean registerUser(String userName, String password, UserIdentityClaimDTO[] claims, String profileName, String tenantDomain) throws IdentityMgtServiceException {
    VerificationBean vBean = new VerificationBean();
    org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
    Permission permission = null;
    if (!IdentityMgtConfig.getInstance().isSaasEnabled()) {
        String loggedInTenant = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        if (tenantDomain != null && !tenantDomain.isEmpty() && !loggedInTenant.equals(tenantDomain)) {
            String msg = "Trying to create users in unauthorized tenant space";
            log.error(msg);
            throw new IdentityMgtServiceException(msg);
        }
        if (tenantDomain == null || tenantDomain.isEmpty()) {
            tenantDomain = loggedInTenant;
        }
    }
    RealmService realmService = IdentityMgtServiceComponent.getRealmService();
    int tenantId;
    try {
        tenantId = Utils.getTenantId(tenantDomain);
        if (realmService.getTenantUserRealm(tenantId) != null) {
            userStoreManager = (org.wso2.carbon.user.core.UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        }
    } catch (Exception e) {
        vBean = handleError(VerificationBean.ERROR_CODE_UNEXPECTED + " Error retrieving the user store manager for the tenant", e);
        return vBean;
    }
    try {
        if (IdentityMgtConfig.getInstance().isSaasEnabled()) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantId(tenantId);
            carbonContext.setTenantDomain(tenantDomain);
        }
        if (userStoreManager == null) {
            vBean = new VerificationBean();
            vBean.setVerified(false);
            vBean.setError(VerificationBean.ERROR_CODE_UNEXPECTED + " Error retrieving the user store manager for the tenant");
            return vBean;
        }
        Map<String, String> claimsMap = new HashMap<String, String>();
        for (UserIdentityClaimDTO userIdentityClaimDTO : claims) {
            claimsMap.put(userIdentityClaimDTO.getClaimUri(), userIdentityClaimDTO.getClaimValue());
        }
        userStoreManager.addUser(userName, password, null, claimsMap, profileName);
        String identityRoleName = UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + IdentityConstants.IDENTITY_DEFAULT_ROLE;
        if (!userStoreManager.isExistingRole(identityRoleName, false)) {
            permission = new Permission("/permission/admin/login", UserMgtConstants.EXECUTE_ACTION);
            userStoreManager.addRole(identityRoleName, new String[] { userName }, new Permission[] { permission }, false);
        } else {
            userStoreManager.updateUserListOfRole(identityRoleName, new String[] {}, new String[] { userName });
        }
        String listenerClassName = IdentityMgtConfig.getInstance().getProperty(IdentityMgtConstants.PropertyConfig.IDENTITY_MGT_LISTENER_CLASS);
        if (StringUtils.isBlank(listenerClassName)) {
            listenerClassName = IdentityMgtEventListener.class.getName();
        }
        IdentityEventListenerConfig identityEventListenerConfig = IdentityUtil.readEventListenerProperty(UserOperationEventListener.class.getName(), listenerClassName);
        boolean isListenerEnable = true;
        if (identityEventListenerConfig != null) {
            if (StringUtils.isNotBlank(identityEventListenerConfig.getEnable())) {
                isListenerEnable = Boolean.parseBoolean(identityEventListenerConfig.getEnable());
            }
        }
        IdentityMgtConfig config = IdentityMgtConfig.getInstance();
        if (isListenerEnable && config.isAuthPolicyAccountLockOnCreation()) {
            UserDTO userDTO = new UserDTO(UserCoreUtil.addTenantDomainToEntry(userName, tenantDomain));
            userDTO.setTenantId(tenantId);
            UserRecoveryDTO dto = new UserRecoveryDTO(userDTO);
            dto.setNotification(IdentityMgtConstants.Notification.ACCOUNT_CONFORM);
            dto.setNotificationType("EMAIL");
            RecoveryProcessor processor = IdentityMgtServiceComponent.getRecoveryProcessor();
            vBean = processor.updateConfirmationCode(1, userName, tenantId);
            dto.setConfirmationCode(vBean.getKey());
            NotificationDataDTO notificationDto = processor.notifyWithEmail(dto);
            vBean.setVerified(notificationDto.isNotificationSent());
            // Send email data only if not internally managed.
            if (!(IdentityMgtConfig.getInstance().isNotificationInternallyManaged())) {
                vBean.setNotificationData(notificationDto);
            }
        } else {
            vBean.setVerified(true);
        }
    } catch (UserStoreException | IdentityException e) {
        vBean = UserIdentityManagementUtil.getCustomErrorMessagesWhenRegistering(e, userName);
        // Rollback if user exists
        try {
            if (!e.getMessage().contains(IdentityCoreConstants.EXISTING_USER) && userStoreManager.isExistingUser(userName)) {
                userStoreManager.deleteUser(userName);
            }
        } catch (UserStoreException e1) {
            vBean = UserIdentityManagementUtil.getCustomErrorMessagesWhenRegistering(e1, userName);
        }
        return vBean;
    } finally {
        if (IdentityMgtConfig.getInstance().isSaasEnabled()) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return vBean;
}
Also used : VerificationBean(org.wso2.carbon.identity.mgt.beans.VerificationBean) IdentityMgtServiceException(org.wso2.carbon.identity.mgt.IdentityMgtServiceException) UserOperationEventListener(org.wso2.carbon.user.core.listener.UserOperationEventListener) HashMap(java.util.HashMap) UserDTO(org.wso2.carbon.identity.mgt.dto.UserDTO) NotificationDataDTO(org.wso2.carbon.identity.mgt.dto.NotificationDataDTO) UserRecoveryDTO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDTO) IdentityException(org.wso2.carbon.identity.base.IdentityException) IdentityMgtEventListener(org.wso2.carbon.identity.mgt.IdentityMgtEventListener) Permission(org.wso2.carbon.user.core.Permission) UserStoreException(org.wso2.carbon.user.api.UserStoreException) IdentityEventListenerConfig(org.wso2.carbon.identity.core.model.IdentityEventListenerConfig) RecoveryProcessor(org.wso2.carbon.identity.mgt.RecoveryProcessor) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) UserStoreException(org.wso2.carbon.user.api.UserStoreException) IdentityMgtServiceException(org.wso2.carbon.identity.mgt.IdentityMgtServiceException) IdentityException(org.wso2.carbon.identity.base.IdentityException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserIdentityClaimDTO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimDTO) IdentityMgtConfig(org.wso2.carbon.identity.mgt.IdentityMgtConfig)

Aggregations

UserIdentityClaimsDO (org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO)7 UserStoreException (org.wso2.carbon.user.core.UserStoreException)7 IdentityException (org.wso2.carbon.identity.base.IdentityException)6 IdentityErrorMsgContext (org.wso2.carbon.identity.core.model.IdentityErrorMsgContext)4 NotificationDataDTO (org.wso2.carbon.identity.mgt.dto.NotificationDataDTO)4 PolicyViolationException (org.wso2.carbon.identity.mgt.policy.PolicyViolationException)4 HashMap (java.util.HashMap)3 UserRecoveryDTO (org.wso2.carbon.identity.mgt.dto.UserRecoveryDTO)3 UserIdentityDataStore (org.wso2.carbon.identity.mgt.store.UserIdentityDataStore)3 Entry (java.util.Map.Entry)2 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)2 IdentityEventListenerConfig (org.wso2.carbon.identity.core.model.IdentityEventListenerConfig)2 IdentityMgtConfig (org.wso2.carbon.identity.mgt.IdentityMgtConfig)2 IdentityMgtEventListener (org.wso2.carbon.identity.mgt.IdentityMgtEventListener)2 IdentityMgtServiceException (org.wso2.carbon.identity.mgt.IdentityMgtServiceException)2 RecoveryProcessor (org.wso2.carbon.identity.mgt.RecoveryProcessor)2 VerificationBean (org.wso2.carbon.identity.mgt.beans.VerificationBean)2 UserDTO (org.wso2.carbon.identity.mgt.dto.UserDTO)2 UserOperationEventListener (org.wso2.carbon.user.core.listener.UserOperationEventListener)2 Map (java.util.Map)1