Search in sources :

Example 1 with NotificationDataDTO

use of org.wso2.carbon.identity.mgt.dto.NotificationDataDTO 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)

Example 2 with NotificationDataDTO

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

the class IdentityMgtEventListener method doPostAddUser.

/**
 * This method locks the created accounts based on the account policies or
 * based on the account confirmation method being used. Two account
 * confirmation methods are used : Temporary Password and Verification Code.
 * In the case of temporary password is used the temporary password will be
 * emailed to the user. In the case of verification code, the code will be
 * emailed to the user. The security questions filter ad doPreAddUser will
 * be persisted in this method.
 */
@Override
public boolean doPostAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims, String profile, 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_POST_ADD_USER)) {
            IdentityUtil.threadLocalProperties.get().put(DO_POST_ADD_USER, true);
            if (log.isDebugEnabled()) {
                log.debug("Post add user is called in IdentityMgtEventListener");
            }
            IdentityMgtConfig config = IdentityMgtConfig.getInstance();
            // reading the value from the thread local
            UserIdentityClaimsDO userIdentityClaimsDO = (UserIdentityClaimsDO) IdentityUtil.threadLocalProperties.get().get(USER_IDENTITY_DO);
            if (config.isEnableUserAccountVerification() && IdentityUtil.threadLocalProperties.get().containsKey(EMPTY_PASSWORD_USED)) {
                // empty password account creation
                String domainName = ((org.wso2.carbon.user.core.UserStoreManager) userStoreManager).getRealmConfiguration().getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                if (!UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domainName)) {
                    userName = domainName + UserCoreConstants.DOMAIN_SEPARATOR + userName;
                }
                // store identity data
                userIdentityClaimsDO.getUserDataMap().put(UserIdentityDataStore.ACCOUNT_LOCKED_REASON, "");
                userIdentityClaimsDO.setAccountLock(false);
                try {
                    module.store(userIdentityClaimsDO, userStoreManager);
                } catch (IdentityException e) {
                    // roleback user
                    userStoreManager.deleteUser(userName);
                    throw new UserStoreException("Error while saving user store for user : " + userName, e);
                }
                // store identity metadata
                UserRecoveryDataDO metadataDO = new UserRecoveryDataDO();
                metadataDO.setUserName(userName).setTenantId(userStoreManager.getTenantId()).setCode((String) credential);
                // set recovery data
                RecoveryProcessor processor = new RecoveryProcessor();
                UserRecoveryDTO recoveryDto = new UserRecoveryDTO(userName);
                recoveryDto.setNotification(IdentityMgtConstants.Notification.ASK_PASSWORD);
                recoveryDto.setNotificationType("EMAIL");
                recoveryDto.setTenantId(userStoreManager.getTenantId());
                NotificationDataDTO notificationDto = null;
                try {
                    notificationDto = processor.recoverWithNotification(recoveryDto);
                } catch (IdentityException e) {
                    // roleback user
                    userStoreManager.deleteUser(userName);
                    throw new UserStoreException("Error while sending notification for user : " + userName, e);
                }
                return notificationDto != null && notificationDto.isNotificationSent();
            }
            // No account recoveries are defined, no email will be sent.
            if (config.isAuthPolicyAccountLockOnCreation()) {
                // accounts are locked. Admin should unlock
                userIdentityClaimsDO.getUserDataMap().put(UserIdentityDataStore.ACCOUNT_LOCKED_REASON, IdentityMgtConstants.LockedReason.UNVERIFIED.toString());
                userIdentityClaimsDO.setAccountLock(true);
                try {
                    config.getIdentityDataStore().store(userIdentityClaimsDO, userStoreManager);
                } catch (IdentityException e) {
                    // roleback user
                    userStoreManager.deleteUser(userName);
                    throw new UserStoreException("Error while saving user store data for user : " + userName, e);
                }
            }
            // When claims available in user add request like http://wso2.org/claims/identity/accountLocked
            if (!config.isEnableUserAccountVerification() && !config.isAuthPolicyAccountLockOnCreation() && userIdentityClaimsDO != null) {
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Storing identity-mgt claims since they are available in the addUser request");
                    }
                    module.store(userIdentityClaimsDO, userStoreManager);
                } catch (IdentityException e) {
                    // roleback user
                    userStoreManager.deleteUser(userName);
                    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_ADD_USER);
        IdentityUtil.threadLocalProperties.get().remove(EMPTY_PASSWORD_USED);
        IdentityUtil.threadLocalProperties.get().remove(USER_IDENTITY_DO);
    }
}
Also used : UserRecoveryDataDO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO) UserStoreException(org.wso2.carbon.user.core.UserStoreException) NotificationDataDTO(org.wso2.carbon.identity.mgt.dto.NotificationDataDTO) UserIdentityClaimsDO(org.wso2.carbon.identity.mgt.dto.UserIdentityClaimsDO) UserRecoveryDTO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDTO) IdentityException(org.wso2.carbon.identity.base.IdentityException)

Example 3 with NotificationDataDTO

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

the class UserIdentityManagementService method processPasswordRecovery.

/**
 * process password recovery for given user
 *
 * @return recovery process success or not
 * @throws IdentityException if fails
 */
public boolean processPasswordRecovery(String userId, String confirmationCode, String notificationType) throws IdentityMgtServiceException {
    UserDTO userDTO = null;
    try {
        userDTO = Utils.processUserId(userId);
    } catch (IdentityException e) {
        throw new IdentityMgtServiceException("invalid user name", e);
    }
    RecoveryProcessor processor = IdentityMgtServiceComponent.getRecoveryProcessor();
    VerificationBean bean = processor.verifyConfirmationKey(confirmationCode);
    if (!bean.isVerified()) {
        log.warn("Invalid user is trying to recover the password : " + userId);
        return false;
    }
    UserRecoveryDTO dto = new UserRecoveryDTO(userDTO);
    dto.setNotification(IdentityMgtConstants.Notification.PASSWORD_RESET_RECOVERY);
    dto.setNotificationType(notificationType);
    NotificationDataDTO dataDTO = null;
    try {
        dataDTO = processor.recoverWithNotification(dto);
    } catch (IdentityException e) {
        throw new IdentityMgtServiceException("Error while password recovery.", e);
    }
    return dataDTO.isNotificationSent();
}
Also used : VerificationBean(org.wso2.carbon.identity.mgt.beans.VerificationBean) IdentityMgtServiceException(org.wso2.carbon.identity.mgt.IdentityMgtServiceException) UserDTO(org.wso2.carbon.identity.mgt.dto.UserDTO) NotificationDataDTO(org.wso2.carbon.identity.mgt.dto.NotificationDataDTO) RecoveryProcessor(org.wso2.carbon.identity.mgt.RecoveryProcessor) UserRecoveryDTO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDTO) IdentityException(org.wso2.carbon.identity.base.IdentityException)

Example 4 with NotificationDataDTO

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

the class UserInformationRecoveryService method resendSignUpConfiramtionCode.

/**
 * This method is used to resend selef sign up confiration code when user is not recieved email properly
 *
 * @param userName
 * @param code
 * @param profileName
 * @param tenantDomain
 * @return
 * @throws IdentityMgtServiceException
 */
public VerificationBean resendSignUpConfiramtionCode(String userName, String code, String profileName, String tenantDomain) throws IdentityMgtServiceException {
    VerificationBean vBean = new VerificationBean();
    RecoveryProcessor processor = IdentityMgtServiceComponent.getRecoveryProcessor();
    if (!IdentityMgtConfig.getInstance().isSaasEnabled()) {
        String loggedInTenant = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        if (tenantDomain != null && !tenantDomain.isEmpty() && !loggedInTenant.equals(tenantDomain)) {
            String msg = "Trying to resend self sign up code  in unauthorized tenant space";
            log.error(msg);
            throw new IdentityMgtServiceException(msg);
        }
        if (tenantDomain == null || tenantDomain.isEmpty()) {
            tenantDomain = loggedInTenant;
        }
    }
    int tenantId;
    try {
        tenantId = Utils.getTenantId(tenantDomain);
    } catch (IdentityException e) {
        vBean = handleError(VerificationBean.ERROR_CODE_UNEXPECTED + " Error while resending confirmation code", e);
        return vBean;
    }
    try {
        if (IdentityMgtConfig.getInstance().isSaasEnabled()) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantId(tenantId);
            carbonContext.setTenantDomain(tenantDomain);
        }
        try {
            vBean = processor.verifyConfirmationCode(1, userName, code);
            if (!vBean.isVerified()) {
                vBean.setError(VerificationBean.ERROR_CODE_INVALID_CODE);
                return vBean;
            }
        } catch (IdentityException e) {
            vBean = handleError("Error while validating confirmation code for user : " + userName, e);
            return vBean;
        }
        try {
            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");
                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 (IdentityException e) {
            vBean = UserIdentityManagementUtil.getCustomErrorMessagesWhenRegistering(e, 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) UserDTO(org.wso2.carbon.identity.mgt.dto.UserDTO) NotificationDataDTO(org.wso2.carbon.identity.mgt.dto.NotificationDataDTO) RecoveryProcessor(org.wso2.carbon.identity.mgt.RecoveryProcessor) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) UserRecoveryDTO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDTO) IdentityException(org.wso2.carbon.identity.base.IdentityException) IdentityMgtEventListener(org.wso2.carbon.identity.mgt.IdentityMgtEventListener) IdentityEventListenerConfig(org.wso2.carbon.identity.core.model.IdentityEventListenerConfig) IdentityMgtConfig(org.wso2.carbon.identity.mgt.IdentityMgtConfig)

Example 5 with NotificationDataDTO

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

the class RecoveryProcessor method notifyWithEmail.

/*
     * TODO - Important. Refactor this method and use recoveryWithNotification instead.
     */
public NotificationDataDTO notifyWithEmail(UserRecoveryDTO notificationBean) throws IdentityException {
    String notificationAddress;
    String confirmationKey = null;
    NotificationSendingModule module = null;
    String userId = notificationBean.getUserId();
    String domainName = notificationBean.getTenantDomain();
    int tenantId = notificationBean.getTenantId();
    confirmationKey = notificationBean.getConfirmationCode();
    String userStore = IdentityUtil.extractDomainFromName(userId);
    String userName = UserCoreUtil.removeDomainFromName(userId);
    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);
        }
    }
    String type = notificationBean.getNotificationType();
    if (type != null) {
        module = modules.get(type);
    }
    if (module == null) {
        module = defaultModule;
    }
    NotificationData emailNotificationData = new NotificationData();
    String emailTemplate = null;
    notificationAddress = module.getNotificationAddress(userId, tenantId);
    if ((notificationAddress == null) || (notificationAddress.trim().length() < 0)) {
        log.warn("Notification address is not defined for user " + userId);
    }
    String firstName = Utils.getClaimFromUserStoreManager(userId, tenantId, "http://wso2.org/claims/givenname");
    emailNotificationData.setTagData(FIRST_NAME, firstName);
    emailNotificationData.setTagData(USER_STORE_DOMAIN, userStore);
    emailNotificationData.setTagData(USER_NAME, userName);
    emailNotificationData.setTagData(TENANT_DOMAIN, domainName);
    emailNotificationData.setSendTo(notificationAddress);
    Config config = null;
    ConfigBuilder configBuilder = ConfigBuilder.getInstance();
    try {
        config = configBuilder.loadConfiguration(ConfigType.EMAIL, StorageType.REGISTRY, tenantId);
    } catch (Exception e1) {
        throw IdentityException.error("Error occurred while loading email templates for user : " + userId, e1);
    }
    if (notificationBean.getNotification() != null) {
        emailTemplate = config.getProperty(notificationBean.getNotification().trim());
        String notification = notificationBean.getNotification().trim();
        notificationData.setNotification(notification);
        if (IdentityMgtConstants.Notification.PASSWORD_RESET_RECOVERY.equals(notification)) {
            notificationData.setNotificationCode(confirmationKey);
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.PASSWORD_RESET_RECOVERY);
        } else if (IdentityMgtConstants.Notification.ACCOUNT_CONFORM.equals(notification)) {
            notificationData.setNotificationCode(confirmationKey);
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_CONFORM);
        } else if (IdentityMgtConstants.Notification.TEMPORARY_PASSWORD.equals(notification)) {
            // TODO
            String temporaryPassword = notificationBean.getTemporaryPassword();
            notificationData.setNotificationCode(temporaryPassword);
            emailNotificationData.setTagData(TEMPORARY_PASSWORD, temporaryPassword);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.TEMPORARY_PASSWORD);
        } else if (IdentityMgtConstants.Notification.ACCOUNT_UNLOCK.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_UNLOCK);
            notificationData.setNotificationCode(userId);
        } else if (IdentityMgtConstants.Notification.ACCOUNT_ID_RECOVERY.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_ID_RECOVERY);
            notificationData.setNotificationCode(userId);
        } else if (IdentityMgtConstants.Notification.ASK_PASSWORD.equals(notification)) {
            notificationData.setNotificationCode(confirmationKey);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ASK_PASSWORD);
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
        } else if (IdentityMgtConstants.Notification.ACCOUNT_ENABLE.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_ENABLE);
            notificationData.setNotificationCode(userId);
        } else if (IdentityMgtConstants.Notification.ACCOUNT_DISABLE.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_DISABLE);
            notificationData.setNotificationCode(userId);
        }
    }
    Notification emailNotification = null;
    try {
        emailNotification = NotificationBuilder.createNotification("EMAIL", emailTemplate, emailNotificationData);
    } catch (Exception e) {
        throw IdentityException.error("Error occurred while creating notification from email template : " + emailTemplate, e);
    }
    notificationData.setNotificationAddress(notificationAddress);
    notificationData.setUserId(userId);
    notificationData.setDomainName(domainName);
    notificationData.setNotificationType(notificationBean.getNotificationType());
    if (IdentityMgtConfig.getInstance().isNotificationInternallyManaged()) {
        module.setNotificationData(notificationData);
        module.setNotification(emailNotification);
        notificationSender.sendNotification(module);
        notificationData.setNotificationSent(true);
    } else {
        notificationData.setNotificationSent(false);
        notificationData.setNotificationCode(confirmationKey);
    }
    return notificationData;
}
Also used : Config(org.wso2.carbon.identity.mgt.config.Config) NotificationDataDTO(org.wso2.carbon.identity.mgt.dto.NotificationDataDTO) UserStoreException(org.wso2.carbon.user.api.UserStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IdentityException(org.wso2.carbon.identity.base.IdentityException) Notification(org.wso2.carbon.identity.mgt.mail.Notification) TransportHeader(org.wso2.carbon.identity.mgt.mail.TransportHeader) ConfigBuilder(org.wso2.carbon.identity.mgt.config.ConfigBuilder) HashMap(java.util.HashMap) Map(java.util.Map) NotificationData(org.wso2.carbon.identity.mgt.mail.NotificationData)

Aggregations

IdentityException (org.wso2.carbon.identity.base.IdentityException)9 NotificationDataDTO (org.wso2.carbon.identity.mgt.dto.NotificationDataDTO)9 UserRecoveryDTO (org.wso2.carbon.identity.mgt.dto.UserRecoveryDTO)6 RecoveryProcessor (org.wso2.carbon.identity.mgt.RecoveryProcessor)5 VerificationBean (org.wso2.carbon.identity.mgt.beans.VerificationBean)5 UserDTO (org.wso2.carbon.identity.mgt.dto.UserDTO)5 HashMap (java.util.HashMap)4 IdentityMgtServiceException (org.wso2.carbon.identity.mgt.IdentityMgtServiceException)4 UserStoreException (org.wso2.carbon.user.api.UserStoreException)4 Map (java.util.Map)3 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)3 Config (org.wso2.carbon.identity.mgt.config.Config)3 ConfigBuilder (org.wso2.carbon.identity.mgt.config.ConfigBuilder)3 Notification (org.wso2.carbon.identity.mgt.mail.Notification)3 NotificationData (org.wso2.carbon.identity.mgt.mail.NotificationData)3 TransportHeader (org.wso2.carbon.identity.mgt.mail.TransportHeader)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)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