Search in sources :

Example 1 with NotificationData

use of org.wso2.carbon.identity.mgt.mail.NotificationData 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 NotificationData

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

the class DefaultEmailSendingModule method sendEmail.

@Override
public void sendEmail() {
    Map<String, String> headerMap = new HashMap<String, String>();
    try {
        Notification notification = notificationQueue.take();
        if (notification == null) {
            throw new IllegalStateException("Notification not set. " + "Please set the notification before sending messages");
        }
        PrivilegedCarbonContext.startTenantFlow();
        if (notificationData != null) {
            String tenantDomain = notificationData.getDomainName();
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(tenantDomain, true);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("notification data not found. Tenant might not be loaded correctly");
            }
        }
        headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, notification.getSubject());
        OMElement payload = OMAbstractFactory.getOMFactory().createOMElement(BaseConstants.DEFAULT_TEXT_WRAPPER, null);
        StringBuilder contents = new StringBuilder();
        contents.append(notification.getBody()).append(System.getProperty("line.separator")).append(System.getProperty("line.separator")).append(notification.getFooter());
        payload.setText(contents.toString());
        ServiceClient serviceClient;
        ConfigurationContext configContext = CarbonConfigurationContextFactory.getConfigurationContext();
        if (configContext != null) {
            serviceClient = new ServiceClient(configContext, null);
        } else {
            serviceClient = new ServiceClient();
        }
        Options options = new Options();
        options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE);
        options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
        options.setProperty(MailConstants.TRANSPORT_MAIL_FORMAT, MailConstants.TRANSPORT_FORMAT_TEXT);
        options.setTo(new EndpointReference(SEND_MAIL_PROPERTY + notification.getSendTo()));
        serviceClient.setOptions(options);
        log.info("Sending an email notification to " + notification.getSendTo());
        serviceClient.fireAndForget(payload);
        if (log.isDebugEnabled()) {
            log.debug("Email content : " + notification.getBody());
        }
        log.info("Email notification has been sent to " + notification.getSendTo());
    } catch (AxisFault axisFault) {
        log.error("Failed Sending Email", axisFault);
    } catch (InterruptedException e) {
        log.error("Interrupted while waiting until an element becomes available in the notification queue.", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) Options(org.apache.axis2.client.Options) HashMap(java.util.HashMap) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) OMElement(org.apache.axiom.om.OMElement) EndpointReference(org.apache.axis2.addressing.EndpointReference) ServiceClient(org.apache.axis2.client.ServiceClient)

Example 3 with NotificationData

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

Example 4 with NotificationData

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

the class RecoveryProcessor method recoverWithNotification.

/**
 * Processing recovery
 *
 * @param recoveryDTO class that contains user and tenant Information
 * @return true if the reset request is processed successfully.
 * @throws IdentityException if fails
 */
public NotificationDataDTO recoverWithNotification(UserRecoveryDTO recoveryDTO) throws IdentityException {
    String notificationAddress;
    String secretKey = null;
    String confirmationKey = null;
    NotificationSendingModule module = null;
    boolean persistData = true;
    String userId = recoveryDTO.getUserId();
    String domainName = recoveryDTO.getTenantDomain();
    int tenantId = recoveryDTO.getTenantId();
    String userStore = IdentityUtil.extractDomainFromName(userId);
    String userName = UserCoreUtil.removeDomainFromName(userId);
    TenantManager tenantManager = IdentityMgtServiceComponent.getRealmService().getTenantManager();
    try {
        Tenant tenant = tenantManager.getTenant(tenantId);
        if (tenant != null) {
            domainName = tenant.getDomain();
        }
    } catch (UserStoreException e) {
        if (log.isDebugEnabled()) {
            log.debug("No Tenant domain for tenant id " + tenantId, e);
        }
    }
    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 internalCode = null;
    String type = recoveryDTO.getNotificationType();
    if (type != null) {
        module = modules.get(type);
    }
    if (module == null) {
        module = defaultModule;
    }
    NotificationData emailNotificationData = new NotificationData();
    String emailTemplate = null;
    notificationAddress = Utils.getEmailAddressForUser(userId, tenantId);
    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);
    if ((notificationAddress == null) || (notificationAddress.trim().length() < 0)) {
        throw IdentityException.error("Notification sending failure. Notification address is not defined for user : " + userId);
    }
    emailNotificationData.setSendTo(notificationAddress);
    if (log.isDebugEnabled()) {
        log.debug("Building notification with data - First name: " + firstName + " User name: " + userId + " Send To: " + notificationAddress);
    }
    Config config = null;
    ConfigBuilder configBuilder = ConfigBuilder.getInstance();
    try {
        config = configBuilder.loadConfiguration(ConfigType.EMAIL, StorageType.REGISTRY, tenantId);
    } catch (Exception e1) {
        throw IdentityException.error("Error while loading email templates for user : " + userId, e1);
    }
    if (recoveryDTO.getNotification() != null) {
        emailTemplate = config.getProperty(recoveryDTO.getNotification().trim());
        String notification = recoveryDTO.getNotification().trim();
        notificationData.setNotification(notification);
        if (IdentityMgtConstants.Notification.PASSWORD_RESET_RECOVERY.equals(notification) || IdentityMgtConstants.Notification.RESEND_NOTIFICATION.equals(notification)) {
            internalCode = generateUserCode(2, userId);
            try {
                confirmationKey = getUserExternalCodeStr(internalCode);
            } catch (Exception e) {
                throw IdentityException.error("Error while getting user's external code string.", e);
            }
            secretKey = UUIDGenerator.generateUUID();
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
            emailTemplate = config.getProperty(notification);
        } else if (IdentityMgtConstants.Notification.ACCOUNT_CONFORM.equals(notification)) {
            confirmationKey = UUIDGenerator.generateUUID();
            secretKey = UUIDGenerator.generateUUID();
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_CONFORM);
        } else if (IdentityMgtConstants.Notification.TEMPORARY_PASSWORD.equals(notification)) {
            // TODO
            String temporaryPassword = recoveryDTO.getTemporaryPassword();
            if (temporaryPassword == null || temporaryPassword.trim().length() < 1) {
                char[] chars = IdentityMgtConfig.getInstance().getPasswordGenerator().generatePassword();
                temporaryPassword = new String(chars);
            }
            Utils.updatePassword(userId, tenantId, temporaryPassword);
            emailNotificationData.setTagData(TEMPORARY_PASSWORD, temporaryPassword);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.TEMPORARY_PASSWORD);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ACCOUNT_UNLOCK.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_UNLOCK);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ACCOUNT_ENABLE.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_ENABLE);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ACCOUNT_DISABLE.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_DISABLE);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ACCOUNT_ID_RECOVERY.equals(notification)) {
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ACCOUNT_ID_RECOVERY);
            persistData = false;
        } else if (IdentityMgtConstants.Notification.ASK_PASSWORD.equals(notification)) {
            if (firstName == null || firstName.isEmpty()) {
                emailNotificationData.setTagData(FIRST_NAME, userId);
            }
            internalCode = generateUserCode(2, userId);
            try {
                confirmationKey = getUserExternalCodeStr(internalCode);
            } catch (Exception e) {
                throw IdentityException.error("Error while with recovering with password.", e);
            }
            secretKey = UUIDGenerator.generateUUID();
            emailNotificationData.setTagData(CONFIRMATION_CODE, confirmationKey);
            emailTemplate = config.getProperty(IdentityMgtConstants.Notification.ASK_PASSWORD);
        }
        if (log.isDebugEnabled()) {
            log.debug("Notification type: " + notification);
        }
    }
    Notification emailNotification = null;
    try {
        emailNotification = NotificationBuilder.createNotification("EMAIL", emailTemplate, emailNotificationData);
    } catch (Exception e) {
        throw IdentityException.error("Error when creating notification for user : " + userId, e);
    }
    notificationData.setNotificationAddress(notificationAddress);
    notificationData.setUserId(userId);
    notificationData.setDomainName(domainName);
    notificationData.setNotificationType(recoveryDTO.getNotificationType());
    if (persistData) {
        UserRecoveryDataDO recoveryDataDO = new UserRecoveryDataDO(userId, tenantId, internalCode, secretKey);
        dataStore.invalidate(userId, tenantId);
        dataStore.store(recoveryDataDO);
    }
    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) Tenant(org.wso2.carbon.user.api.Tenant) UserRecoveryDataDO(org.wso2.carbon.identity.mgt.dto.UserRecoveryDataDO) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ConfigBuilder(org.wso2.carbon.identity.mgt.config.ConfigBuilder) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) HashMap(java.util.HashMap) Map(java.util.Map) NotificationData(org.wso2.carbon.identity.mgt.mail.NotificationData)

Example 5 with NotificationData

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

the class NotificationBuilder method createNotification.

public static Notification createNotification(String notificationType, String template, NotificationData data) throws IdentityMgtServiceException {
    String subject = null;
    String body = null;
    String footer = null;
    Notification notificatoin = null;
    if ("EMAIL".equals(notificationType)) {
        String[] contents = template.split("\\|");
        if (contents.length > 3) {
            throw new IdentityMgtServiceException("Contents must be 3 or less");
        }
        subject = contents[0];
        body = contents[1];
        footer = contents[2];
        // Replace all the tags in the NotificationData.
        Map<String, String> tagsData = data.getTagsData();
        try {
            subject = replaceTags(tagsData, subject);
            body = replaceTags(tagsData, body);
            footer = replaceTags(tagsData, footer);
        } catch (UnsupportedEncodingException e) {
            throw new IdentityMgtServiceException("Unsupported encoding while creating notification", e);
        }
        notificatoin = new EmailNotification();
        notificatoin.setSubject(subject);
        notificatoin.setBody(body);
        notificatoin.setFooter(footer);
        notificatoin.setSendFrom(data.getSendFrom());
        notificatoin.setSendTo(data.getSendTo());
    }
    return notificatoin;
}
Also used : IdentityMgtServiceException(org.wso2.carbon.identity.mgt.IdentityMgtServiceException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

HashMap (java.util.HashMap)4 Map (java.util.Map)3 IdentityException (org.wso2.carbon.identity.base.IdentityException)3 Config (org.wso2.carbon.identity.mgt.config.Config)3 ConfigBuilder (org.wso2.carbon.identity.mgt.config.ConfigBuilder)3 NotificationDataDTO (org.wso2.carbon.identity.mgt.dto.NotificationDataDTO)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 UserStoreException (org.wso2.carbon.user.api.UserStoreException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 OMElement (org.apache.axiom.om.OMElement)1 AxisFault (org.apache.axis2.AxisFault)1 EndpointReference (org.apache.axis2.addressing.EndpointReference)1 Options (org.apache.axis2.client.Options)1 ServiceClient (org.apache.axis2.client.ServiceClient)1 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)1 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)1 IdentityErrorMsgContext (org.wso2.carbon.identity.core.model.IdentityErrorMsgContext)1