Search in sources :

Example 1 with TransportHeader

use of org.wso2.carbon.identity.mgt.mail.TransportHeader in project carbon-business-process by wso2.

the class SOAPTask method execute.

@Override
public void execute(DelegateExecution execution) {
    String endpointURL;
    String payloadRequest;
    String version;
    String connection;
    String transferEncoding;
    String[] transportHeaderList;
    String action = "";
    String soapVersionURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
    List<Header> headerList = new ArrayList<Header>();
    try {
        if (serviceURL != null) {
            endpointURL = serviceURL.getValue(execution).toString();
        } else if (serviceRef != null) {
            String resourcePath = serviceRef.getValue(execution).toString();
            String registryPath;
            String tenantId = execution.getTenantId();
            Registry registry;
            if (resourcePath.startsWith(GOVERNANCE_REGISTRY_PREFIX)) {
                registryPath = resourcePath.substring(GOVERNANCE_REGISTRY_PREFIX.length());
                registry = BPMNExtensionsComponent.getRegistryService().getGovernanceSystemRegistry(Integer.parseInt(tenantId));
            } else if (resourcePath.startsWith(CONFIGURATION_REGISTRY_PREFIX)) {
                registryPath = resourcePath.substring(CONFIGURATION_REGISTRY_PREFIX.length());
                registry = BPMNExtensionsComponent.getRegistryService().getConfigSystemRegistry(Integer.parseInt(tenantId));
            } else {
                String msg = "Registry type is not specified for service reference in " + " serviceRef should begin with gov:/ or conf:/ to indicate the registry type.";
                setErrorDetailsForTaskExecution(execution, BAD_REQUEST, msg);
                throw new SOAPException(BAD_REQUEST, msg);
            }
            if (log.isDebugEnabled()) {
                log.debug("Reading endpoint from registry location: " + registryPath + " for task " + execution.getCurrentActivityName());
            }
            Resource urlResource = registry.get(registryPath);
            if (urlResource != null) {
                String uepContent = new String((byte[]) urlResource.getContent(), Charset.defaultCharset());
                UnifiedEndpointFactory uepFactory = new UnifiedEndpointFactory();
                OMElement uepElement = AXIOMUtil.stringToOM(uepContent);
                UnifiedEndpoint uep = uepFactory.createEndpoint(uepElement);
                endpointURL = uep.getAddress();
            } else {
                String errorMsg = "Endpoint resource " + registryPath + " is not found. Failed to execute REST invocation in task " + execution.getCurrentActivityName();
                setErrorDetailsForTaskExecution(execution, BAD_REQUEST, errorMsg);
                throw new SOAPException(BAD_REQUEST, errorMsg);
            }
        } else {
            String urlNotFoundErrorMsg = "Service URL is not provided. serviceURL must be provided.";
            setErrorDetailsForTaskExecution(execution, BAD_REQUEST, urlNotFoundErrorMsg);
            throw new SOAPException(BAD_REQUEST, urlNotFoundErrorMsg);
        }
        if (payload != null) {
            payloadRequest = payload.getValue(execution).toString();
        } else {
            String payloadNotFoundErrorMsg = "Payload request is not provided. Payload must be provided.";
            setErrorDetailsForTaskExecution(execution, BAD_REQUEST, payloadNotFoundErrorMsg);
            throw new SOAPException(BAD_REQUEST, payloadNotFoundErrorMsg);
        }
        if (soapVersion != null) {
            version = soapVersion.getValue(execution).toString();
            if (version.equalsIgnoreCase(SOAP12_VERSION)) {
                soapVersionURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            } else if (version.equalsIgnoreCase(SOAP11_VERSION)) {
                soapVersionURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            } else {
                String invalidVersionErrorMsg = "Invalid soap version string specified";
                setErrorDetailsForTaskExecution(execution, BAD_REQUEST, invalidVersionErrorMsg);
                throw new SOAPException(BAD_REQUEST, invalidVersionErrorMsg);
            }
        }
        // Adding the connection
        Header connectionHeader = new Header();
        if (httpConnection != null) {
            connection = httpConnection.getValue(execution).toString();
            if (connection != null && !connection.trim().equals("Keep-Alive")) {
                log.debug("Setting Keep-Alive header ");
                connectionHeader.setName("Connection");
                connectionHeader.setValue(connection);
                headerList.add(connectionHeader);
            }
        }
        // Adding the additional transport headers
        if (transportHeaders != null) {
            String headerContent = transportHeaders.getValue(execution).toString();
            if (headerContent != null) {
                transportHeaderList = headerContent.split(",");
                for (String transportHeader : transportHeaderList) {
                    String[] pair = transportHeader.split(":");
                    Header additionalHeader = new Header();
                    if (pair.length == 1) {
                        additionalHeader.setName(pair[0]);
                        additionalHeader.setValue("");
                        if (log.isDebugEnabled()) {
                            log.debug("Adding transport headers " + pair[0]);
                        }
                    } else {
                        additionalHeader.setName(pair[0]);
                        additionalHeader.setValue(pair[1]);
                        if (log.isDebugEnabled()) {
                            log.debug("Adding transport headers " + pair[0] + " " + pair[1]);
                        }
                    }
                    headerList.add(additionalHeader);
                }
            }
        }
        // Adding the soap action
        if (soapAction != null) {
            action = soapAction.getValue(execution).toString();
            if (log.isDebugEnabled()) {
                log.debug("Setting soap action " + soapAction);
            }
        }
        // Converting the payload to an OMElement
        OMElement payLoad = AXIOMUtil.stringToOM(payloadRequest);
        // Creating the Service client
        ServiceClient sender = new ServiceClient();
        OMElement response;
        // Creating options to set the headers
        Options options = new Options();
        options.setTo(new EndpointReference(endpointURL));
        options.setAction(action);
        options.setSoapVersionURI(soapVersionURI);
        options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList);
        // Adding the soap header block to the SOAP Header block when creating the SOAP Envelope
        if (headers != null) {
            String headerContent = headers.getValue(execution).toString();
            OMElement headerElement = AXIOMUtil.stringToOM(headerContent);
            sender.addHeader(headerElement);
            if (log.isDebugEnabled()) {
                log.debug("Adding soap header " + headerContent);
            }
        }
        // Adding the transfer encoding
        if (httpTransferEncoding != null) {
            transferEncoding = httpTransferEncoding.getValue(execution).toString();
            if (transferEncoding.equalsIgnoreCase("chunked")) {
                options.setProperty(HTTPConstants.CHUNKED, Boolean.TRUE);
                if (log.isDebugEnabled()) {
                    log.debug("Enabling transfer encoding chunked ");
                }
            } else {
                options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);
                if (log.isDebugEnabled()) {
                    log.debug("Disabling transfer encoding chunked ");
                }
            }
        }
        sender.setOptions(options);
        // Invoking the endpoint
        response = sender.sendReceive(payLoad);
        // Getting the response as a string
        String responseStr = response.toStringWithConsume();
        if (outputVariable != null) {
            String outVarName = outputVariable.getValue(execution).toString();
            execution.setVariable(outVarName, responseStr);
        } else {
            String outputNotFoundErrorMsg = "Output variable is not provided. " + "outputVariable must be provided to save " + "the response.";
            setErrorDetailsForTaskExecution(execution, BAD_REQUEST, outputNotFoundErrorMsg);
            throw new SOAPException(BAD_REQUEST, outputNotFoundErrorMsg);
        }
    } catch (AxisFault axisFault) {
        log.error("Axis2 Fault", axisFault);
        String errMsg = "Exception while getting response :" + axisFault.getMessage();
        setErrorDetailsForTaskExecution(execution, SOAP_INVOKE_ERROR_CODE, errMsg);
        throw new SOAPException(SOAP_INVOKE_ERROR_CODE, "Exception while getting response :" + axisFault.getMessage());
    } catch (XMLStreamException | RegistryException e) {
        log.error("Exception in processing", e);
        String errMsg = "Exception in processing  :" + e.getMessage();
        setErrorDetailsForTaskExecution(execution, INTERNAL_SERVER_ERROR, errMsg);
        throw new SOAPException(INTERNAL_SERVER_ERROR, errMsg);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Options(org.apache.axis2.client.Options) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.api.Resource) OMElement(org.apache.axiom.om.OMElement) Registry(org.wso2.carbon.registry.api.Registry) RegistryException(org.wso2.carbon.registry.api.RegistryException) UnifiedEndpointFactory(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointFactory) EndpointReference(org.apache.axis2.addressing.EndpointReference) Header(org.apache.commons.httpclient.Header) XMLStreamException(javax.xml.stream.XMLStreamException) ServiceClient(org.apache.axis2.client.ServiceClient) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint)

Example 2 with TransportHeader

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

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

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

Aggregations

HashMap (java.util.HashMap)3 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 ArrayList (java.util.ArrayList)1 XMLStreamException (javax.xml.stream.XMLStreamException)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 Header (org.apache.commons.httpclient.Header)1 IdentityErrorMsgContext (org.wso2.carbon.identity.core.model.IdentityErrorMsgContext)1