Search in sources :

Example 1 with UserIdentityClaimsDO

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

the class UserIdentityManagementUtil method updateUserIdentityClaims.

/**
 * Updates users recovery data such as the phone number, email etc
 *
 * @param userStoreManager
 * @param userIdentityRecoveryData
 * @throws IdentityException
 */
public static void updateUserIdentityClaims(String userName, UserStoreManager userStoreManager, UserIdentityClaimDTO[] userIdentityRecoveryData) throws IdentityException {
    UserIdentityDataStore store = IdentityMgtConfig.getInstance().getIdentityDataStore();
    UserIdentityClaimsDO userIdentityDO = store.load(userName, userStoreManager);
    if (userIdentityDO != null) {
        userIdentityDO.updateUserIdentityRecoveryData(userIdentityRecoveryData);
        store.store(userIdentityDO, userStoreManager);
    } else {
        throw IdentityException.error("No user account found for user " + userName);
    }
}
Also used : UserIdentityDataStore(org.wso2.carbon.identity.mgt.store.UserIdentityDataStore) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO)

Example 2 with UserIdentityClaimsDO

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

the class InMemoryIdentityDataStore method load.

@Override
public UserIdentityClaimsDO load(String userName, UserStoreManager userStoreManager) {
    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 && cache != null) {
            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);
            UserIdentityClaimsDO userIdentityDTO = (UserIdentityClaimsDO) cache.get(domainName + userStoreManager.getTenantId() + userName);
            if (userIdentityDTO != null && log.isDebugEnabled()) {
                StringBuilder data = new StringBuilder("{");
                if (userIdentityDTO.getUserIdentityDataMap() != null) {
                    for (Map.Entry<String, String> entry : userIdentityDTO.getUserIdentityDataMap().entrySet()) {
                        data.append("[" + entry.getKey() + " = " + entry.getValue() + "], ");
                    }
                }
                if (data.indexOf(",") >= 0) {
                    data.deleteCharAt(data.lastIndexOf(","));
                }
                data.append("}");
                log.debug("Loaded UserIdentityClaimsDO from cache for user :" + userName + " with claims: " + data);
            }
            return userIdentityDTO;
        }
    } catch (UserStoreException e) {
        log.error("Error while obtaining tenant ID from user store manager");
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return null;
}
Also used : UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO) Map(java.util.Map)

Example 3 with UserIdentityClaimsDO

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

the class UserStoreBasedIdentityDataStore method load.

/**
 * This method loads identity and security questions from the user stores
 */
@Override
public UserIdentityClaimsDO load(String userName, UserStoreManager userStoreManager) {
    UserIdentityClaimsDO userIdentityDTO = super.load(userName, userStoreManager);
    if (userIdentityDTO != null) {
        return userIdentityDTO;
    }
    // which happen calling getUserClaimValues()
    if (TRUE_STRING.equals(userStoreInvoked.get())) {
        if (log.isDebugEnabled()) {
            log.debug("UserStoreBasedIdentityDataStore.load() already been called in the stack." + "Hence returning without processing load() again.");
        }
        return null;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Set flag to indicate method UserStoreBasedIdentityDataStore.load() been called");
        }
        userStoreInvoked.set(TRUE_STRING);
    }
    Map<String, String> userDataMap = new HashMap<String, String>();
    try {
        // reading all claims of the user
        Claim[] claims = ((AbstractUserStoreManager) userStoreManager).getUserClaimValues(userName, null);
        // select the security questions and identity claims
        if (claims != null) {
            for (Claim claim : claims) {
                String claimUri = claim.getClaimUri();
                if (claimUri.contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI) || claimUri.contains(UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Adding UserIdentityClaim : " + claimUri + " with the value : " + claim.getValue());
                    }
                    userDataMap.put(claimUri, claim.getValue());
                }
            }
        } else {
            // null is returned when the user doesn't exist
            return null;
        }
    } catch (UserStoreException e) {
        if (!e.getMessage().startsWith(IdentityCoreConstants.USER_NOT_FOUND)) {
            log.error("Error while reading identity user data from 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 null;
    } finally {
        // reset to initial value
        if (log.isDebugEnabled()) {
            log.debug("Reset flag to indicate method UserStoreBasedIdentityDataStore.load() being completing");
        }
        userStoreInvoked.set(FALSE_STRING);
    }
    userIdentityDTO = new UserIdentityClaimsDO(userName, userDataMap);
    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    userIdentityDTO.setTenantId(tenantId);
    org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager;
    String domainName = store.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    try {
        super.store(userIdentityDTO, userStoreManager);
    } catch (IdentityException e) {
        log.error("Error while reading user identity data", e);
    }
    return userIdentityDTO;
}
Also used : HashMap(java.util.HashMap) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) ActiveDirectoryUserStoreManager(org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager) ReadWriteLDAPUserStoreManager(org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager) JDBCUserStoreManager(org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager) IdentityException(org.wso2.carbon.identity.base.IdentityException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO) Claim(org.wso2.carbon.user.core.claim.Claim)

Example 4 with UserIdentityClaimsDO

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

the class UserStoreBasedIdentityDataStore method store.

/**
 * 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());
    int tenantId;
    try {
        tenantId = userStoreManager.getTenantId();
    } catch (UserStoreException e) {
        throw IdentityException.error("Error while getting tenant Id.", e);
    }
    newIdentityClaimDO.setTenantId(tenantId);
    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 {
        // store then log a warn.
        if (!userStoreManager.isReadOnly()) {
            // Need to clone the map. If not iterative calls will refer the same map
            setUserClaimsValuesInUserStore(userStoreManager, username, new HashMap<>(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;
        }
    }
}
Also used : UserStoreException(org.wso2.carbon.user.api.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO)

Example 5 with UserIdentityClaimsDO

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

the class IdentityMgtEventListener method doPostAuthenticate.

/**
 * This method locks the accounts after a configured number of
 * authentication failure attempts. And unlocks accounts based on successful
 * authentications.
 */
@Override
public boolean doPostAuthenticate(String userName, boolean authenticated, UserStoreManager userStoreManager) throws UserStoreException {
    if (!isEnable()) {
        return true;
    }
    IdentityUtil.threadLocalProperties.get().remove(IdentityCoreConstants.USER_ACCOUNT_STATE);
    String domainName = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
    String usernameWithDomain = IdentityUtil.addDomainToName(userName, domainName);
    boolean isUserExistInCurrentDomain = userStoreManager.isExistingUser(usernameWithDomain);
    if (authenticated && isUserExistInCurrentDomain) {
        if (isUserExistInCurrentDomain) {
            UserIdentityClaimsDO userIdentityDTO = module.load(userName, userStoreManager);
            userIdentityDTO.setLastLogonTime(System.currentTimeMillis());
            try {
                module.store(userIdentityDTO, userStoreManager);
            } catch (IdentityException e) {
                throw new UserStoreException(String.format("Error while saving user store data : %s for user : %s.", UserIdentityDataStore.LAST_LOGON_TIME, userName), e);
            }
        }
    }
    // Top level try and finally blocks are used to unset thread local variables
    try {
        if (!IdentityUtil.threadLocalProperties.get().containsKey(DO_POST_AUTHENTICATE)) {
            IdentityUtil.threadLocalProperties.get().put(DO_POST_AUTHENTICATE, true);
            if (log.isDebugEnabled()) {
                log.debug("Post authenticator is called in IdentityMgtEventListener");
            }
            IdentityMgtConfig config = IdentityMgtConfig.getInstance();
            if (!config.isEnableAuthPolicy()) {
                return true;
            }
            UserIdentityClaimsDO userIdentityDTO = module.load(userName, userStoreManager);
            if (userIdentityDTO == null) {
                userIdentityDTO = new UserIdentityClaimsDO(userName);
                userIdentityDTO.setTenantId(userStoreManager.getTenantId());
            }
            boolean userOTPEnabled = userIdentityDTO.getOneTimeLogin();
            // One time password check
            if (authenticated && config.isAuthPolicyOneTimePasswordCheck() && (!userStoreManager.isReadOnly()) && userOTPEnabled) {
                // reset password of the user and notify user of the new password
                String password = new String(UserIdentityManagementUtil.generateTemporaryPassword());
                userStoreManager.updateCredentialByAdmin(userName, password);
                // Get email user claim value
                String email = userStoreManager.getUserClaimValue(userName, UserCoreConstants.ClaimTypeURIs.EMAIL_ADDRESS, null);
                if (StringUtils.isBlank(email)) {
                    throw new UserStoreException("No user email provided for user : " + userName);
                }
                List<NotificationSendingModule> notificationModules = config.getNotificationSendingModules();
                if (notificationModules != null) {
                    NotificationDataDTO notificationData = new NotificationDataDTO();
                    if (MessageContext.getCurrentMessageContext() != null && MessageContext.getCurrentMessageContext().getProperty(MessageContext.TRANSPORT_HEADERS) != null) {
                        Map<String, String> transportHeaderMap = (Map) MessageContext.getCurrentMessageContext().getProperty(MessageContext.TRANSPORT_HEADERS);
                        if (MapUtils.isNotEmpty(transportHeaderMap)) {
                            TransportHeader[] transportHeadersArray = new TransportHeader[transportHeaderMap.size()];
                            int i = 0;
                            for (Map.Entry<String, String> entry : transportHeaderMap.entrySet()) {
                                TransportHeader transportHeader = new TransportHeader();
                                transportHeader.setHeaderName(entry.getKey());
                                transportHeader.setHeaderValue(entry.getValue());
                                transportHeadersArray[i] = transportHeader;
                                ++i;
                            }
                            notificationData.setTransportHeaders(transportHeadersArray);
                        }
                    }
                    NotificationData emailNotificationData = new NotificationData();
                    String emailTemplate = null;
                    int tenantId = userStoreManager.getTenantId();
                    String firstName = null;
                    String userStoreDomain = userStoreManager.getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                    String domainSpecificUserName = UserCoreUtil.addDomainToName(userName, userStoreDomain);
                    String tenantDomain = IdentityTenantUtil.getTenantDomain(userStoreManager.getTenantId());
                    try {
                        firstName = Utils.getClaimFromUserStoreManager(domainSpecificUserName, tenantId, UserCoreConstants.ClaimTypeURIs.GIVEN_NAME);
                    } catch (IdentityException e2) {
                        throw new UserStoreException("Could not load user given name", e2);
                    }
                    emailNotificationData.setTagData("first-name", firstName);
                    emailNotificationData.setTagData("user-name", userName);
                    emailNotificationData.setTagData("otp-password", password);
                    emailNotificationData.setTagData("userstore-domain", userStoreDomain);
                    emailNotificationData.setTagData("tenant-domain", tenantDomain);
                    emailNotificationData.setSendTo(email);
                    Config emailConfig = null;
                    ConfigBuilder configBuilder = ConfigBuilder.getInstance();
                    try {
                        emailConfig = configBuilder.loadConfiguration(ConfigType.EMAIL, StorageType.REGISTRY, tenantId);
                    } catch (Exception e1) {
                        throw new UserStoreException("Could not load the email template configuration for user : " + userName, e1);
                    }
                    emailTemplate = emailConfig.getProperty("otp");
                    Notification emailNotification = null;
                    try {
                        emailNotification = NotificationBuilder.createNotification(EMAIL_NOTIFICATION_TYPE, emailTemplate, emailNotificationData);
                    } catch (Exception e) {
                        throw new UserStoreException("Could not create the email notification for template: " + emailTemplate, e);
                    }
                    NotificationSender sender = new NotificationSender();
                    for (NotificationSendingModule notificationSendingModule : notificationModules) {
                        if (IdentityMgtConfig.getInstance().isNotificationInternallyManaged()) {
                            notificationSendingModule.setNotificationData(notificationData);
                            notificationSendingModule.setNotification(emailNotification);
                            sender.sendNotification(notificationSendingModule);
                            notificationData.setNotificationSent(true);
                        }
                    }
                } else {
                    throw new UserStoreException("No notification modules configured");
                }
            }
            // Password expire check. Not for OTP enabled users.
            if (authenticated && config.isAuthPolicyExpirePasswordCheck() && !userOTPEnabled && (!userStoreManager.isReadOnly())) {
            // TODO - password expire impl
            // Refactor adduser and change password api to stamp the time
            // Check user's expire time in the claim
            // if expired redirect to change password
            // else pass through
            }
            if (!authenticated && config.isAuthPolicyAccountLockOnFailure()) {
                // reading the max allowed #of failure attempts
                if (isUserExistInCurrentDomain) {
                    userIdentityDTO.setFailAttempts();
                    if (userIdentityDTO.getFailAttempts() >= config.getAuthPolicyMaxLoginAttempts()) {
                        log.info("User, " + userName + " has exceed the max failed login attempts. " + "User account would be locked");
                        IdentityErrorMsgContext customErrorMessageContext = new IdentityErrorMsgContext(UserCoreConstants.ErrorCode.USER_IS_LOCKED + ":" + IdentityMgtConstants.LockedReason.MAX_ATTEMTS_EXCEEDED.toString(), userIdentityDTO.getFailAttempts(), config.getAuthPolicyMaxLoginAttempts());
                        IdentityUtil.setIdentityErrorMsg(customErrorMessageContext);
                        IdentityUtil.threadLocalProperties.get().put(IdentityCoreConstants.USER_ACCOUNT_STATE, UserCoreConstants.ErrorCode.USER_IS_LOCKED);
                        if (log.isDebugEnabled()) {
                            log.debug("Username :" + userName + "Exceeded the maximum login attempts. User locked, ErrorCode :" + UserCoreConstants.ErrorCode.USER_IS_LOCKED);
                        }
                        userIdentityDTO.getUserDataMap().put(UserIdentityDataStore.ACCOUNT_LOCKED_REASON, IdentityMgtConstants.LockedReason.MAX_ATTEMTS_EXCEEDED.toString());
                        userIdentityDTO.setAccountLock(true);
                        userIdentityDTO.setFailAttempts(0);
                        // lock time from the config
                        int lockTime = IdentityMgtConfig.getInstance().getAuthPolicyLockingTime();
                        if (lockTime != 0) {
                            userIdentityDTO.setUnlockTime(System.currentTimeMillis() + (lockTime * 60 * 1000L));
                        }
                    } else {
                        IdentityErrorMsgContext customErrorMessageContext = new IdentityErrorMsgContext(UserCoreConstants.ErrorCode.INVALID_CREDENTIAL, userIdentityDTO.getFailAttempts(), config.getAuthPolicyMaxLoginAttempts());
                        IdentityUtil.setIdentityErrorMsg(customErrorMessageContext);
                        if (log.isDebugEnabled()) {
                            log.debug("Username :" + userName + "Invalid Credential, ErrorCode :" + UserCoreConstants.ErrorCode.INVALID_CREDENTIAL);
                        }
                    }
                    try {
                        module.store(userIdentityDTO, userStoreManager);
                    } catch (IdentityException e) {
                        throw new UserStoreException("Error while saving user store data for user : " + userName, e);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("User, " + userName + " is not exists in " + domainName);
                    }
                }
            } else {
                // the unlock the account and reset the number of failedAttempts
                if (userIdentityDTO.isAccountLocked() || userIdentityDTO.getFailAttempts() > 0 || userIdentityDTO.getAccountLock()) {
                    userIdentityDTO.getUserDataMap().put(UserIdentityDataStore.ACCOUNT_LOCKED_REASON, "");
                    userIdentityDTO.setAccountLock(false);
                    userIdentityDTO.setFailAttempts(0);
                    userIdentityDTO.setUnlockTime(0);
                    try {
                        module.store(userIdentityDTO, userStoreManager);
                    } 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_POST_AUTHENTICATE);
    }
}
Also used : Config(org.wso2.carbon.identity.mgt.config.Config) NotificationDataDTO(org.wso2.carbon.identity.mgt.dto.NotificationDataDTO) IdentityException(org.wso2.carbon.identity.base.IdentityException) IdentityErrorMsgContext(org.wso2.carbon.identity.core.model.IdentityErrorMsgContext) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) IdentityException(org.wso2.carbon.identity.base.IdentityException) PolicyViolationException(org.wso2.carbon.identity.mgt.policy.PolicyViolationException) Notification(org.wso2.carbon.identity.mgt.mail.Notification) TransportHeader(org.wso2.carbon.identity.mgt.mail.TransportHeader) UserStoreException(org.wso2.carbon.user.core.UserStoreException) ConfigBuilder(org.wso2.carbon.identity.mgt.config.ConfigBuilder) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO) HashMap(java.util.HashMap) Map(java.util.Map) NotificationData(org.wso2.carbon.identity.mgt.mail.NotificationData)

Aggregations

UserIdentityClaimsDO (org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO)19 UserIdentityDataStore (org.wso2.carbon.identity.mgt.store.UserIdentityDataStore)10 UserStoreException (org.wso2.carbon.user.api.UserStoreException)8 UserStoreException (org.wso2.carbon.user.core.UserStoreException)7 IdentityException (org.wso2.carbon.identity.base.IdentityException)6 Map (java.util.Map)5 HashMap (java.util.HashMap)4 IdentityErrorMsgContext (org.wso2.carbon.identity.core.model.IdentityErrorMsgContext)4 PolicyViolationException (org.wso2.carbon.identity.mgt.policy.PolicyViolationException)4 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)4 Entry (java.util.Map.Entry)2 IdentityDataStoreCacheKey (org.wso2.carbon.identity.governance.internal.cache.IdentityDataStoreCacheKey)2 UserIdentityClaim (org.wso2.carbon.identity.governance.model.UserIdentityClaim)2 NotificationDataDTO (org.wso2.carbon.identity.mgt.dto.NotificationDataDTO)2 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)2 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 CacheManager (javax.cache.CacheManager)1