Search in sources :

Example 21 with Notification

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

the class UserOperationsNotificationListener method sendNotification.

/**
 * This function builds the required configuration object for Notification sender and pass it
 * to the notification sender with the relevant event.
 *
 * @param operation Type or operation took place in user operation listener
 * @param username  username of the subjected user for attribute change
 */
private void sendNotification(String operation, String username) {
    NotificationSender notificationSender = IdentityMgtServiceComponent.getNotificationSender();
    if (notificationSender != null) {
        try {
            PublisherEvent event = new PublisherEvent(eventName);
            event.addEventProperty(operationLabel, operation);
            event.addEventProperty(usernameLabel, username);
            if (log.isDebugEnabled()) {
                log.debug("Invoking notification sender");
            }
            notificationSender.invoke(event);
        } catch (NotificationManagementException e) {
            log.error("Error while sending notifications on user operations", e);
        }
    } else {
        log.error("No registered notification sender found. Notification sending aborted");
    }
}
Also used : NotificationSender(org.wso2.carbon.identity.notification.mgt.NotificationSender) PublisherEvent(org.wso2.carbon.identity.notification.mgt.bean.PublisherEvent) NotificationManagementException(org.wso2.carbon.identity.notification.mgt.NotificationManagementException)

Example 22 with Notification

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

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

the class UserInfoRecoveryWithNotificationClient method sendUserNameRecoveryNotification.

// Send a email notification for username recovery
public Response sendUserNameRecoveryNotification(Claim[] userClaims, String tenantDomain) {
    UsernameRecoveryNotification usernameRecoveryNotification = JAXRSClientFactory.create(ENDPOINT_URL, UsernameRecoveryNotification.class, IdentityManagementServiceUtil.getInstance().getJSONProvider());
    Response response = usernameRecoveryNotification.sendUsernameRecoveryNotification(userClaims, tenantDomain);
    return response;
}
Also used : Response(javax.ws.rs.core.Response) UsernameRecoveryNotification(org.wso2.carbon.identity.mgt.endpoint.util.serviceclient.client.proxy.api.UsernameRecoveryNotification)

Example 24 with Notification

use of org.wso2.carbon.identity.mgt.mail.Notification in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method triggerNotification.

/**
 * We can reuse this method once the improvements done into the eventing and notification handler in IS.
 */
protected void triggerNotification(String userName, String tenantDomain, String userStoreDomainName, String mobileNumber, String otpCode) {
    String eventName = TRIGGER_SMS_NOTIFICATION;
    HashMap<String, Object> properties = new HashMap<>();
    properties.put(IdentityEventConstants.EventProperty.USER_NAME, userName);
    properties.put(IdentityEventConstants.EventProperty.USER_STORE_DOMAIN, userStoreDomainName);
    properties.put(IdentityEventConstants.EventProperty.TENANT_DOMAIN, tenantDomain);
    properties.put(SMSOTPConstants.ATTRIBUTE_SMS_SENT_TO, mobileNumber);
    properties.put(SMSOTPConstants.OTP_TOKEN, otpCode);
    properties.put(SMSOTPConstants.TEMPLATE_TYPE, SMSOTPConstants.EVENT_NAME);
    Event identityMgtEvent = new Event(eventName, properties);
    try {
        SMSOTPServiceDataHolder.getInstance().getIdentityEventService().handleEvent(identityMgtEvent);
    } catch (Exception e) {
        String errorMsg = "Error occurred while calling triggerNotification, detail : " + e.getMessage();
        // We are not throwing any exception from here, because this event notification should not break the main
        // flow.
        log.warn(errorMsg);
        if (log.isDebugEnabled()) {
            log.debug(errorMsg, e);
        }
    }
}
Also used : HashMap(java.util.HashMap) Event(org.wso2.carbon.identity.event.event.Event) IdentityEventException(org.wso2.carbon.identity.event.IdentityEventException) UserStoreClientException(org.wso2.carbon.user.core.UserStoreClientException) LogoutFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) InvalidCredentialsException(org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException) SMSOTPException(org.wso2.carbon.identity.authenticator.smsotp.exception.SMSOTPException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException)

Example 25 with Notification

use of org.wso2.carbon.identity.mgt.mail.Notification in project identity-outbound-auth-sms-otp by wso2-extensions.

the class SMSOTPAuthenticator method proceedWithOTP.

/**
 * Proceed with One Time Password.
 *
 * @param response     the HttpServletResponse
 * @param context      the AuthenticationContext
 * @param errorPage    the errorPage
 * @param mobileNumber the mobile number
 * @param queryParams  the queryParams
 * @param username     the Username
 * @throws AuthenticationFailedException
 */
private void proceedWithOTP(HttpServletResponse response, AuthenticationContext context, String errorPage, String mobileNumber, String queryParams, String username) throws AuthenticationFailedException {
    String screenValue;
    Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
    boolean isEnableResendCode = SMSOTPUtils.isEnableResendCode(context);
    String loginPage = getLoginPage(context);
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
    UserRealm userRealm = SMSOTPUtils.getUserRealm(tenantDomain);
    int tokenLength = SMSOTPConstants.NUMBER_DIGIT;
    boolean isEnableAlphanumericToken = SMSOTPUtils.isEnableAlphanumericToken(context);
    try {
        // One time password is generated and stored in the context.
        OneTimePassword token = new OneTimePassword();
        String secret = OneTimePassword.getRandomNumber(SMSOTPConstants.SECRET_KEY_LENGTH);
        if ((SMSOTPUtils.getTokenLength(context)) != null) {
            tokenLength = Integer.parseInt(SMSOTPUtils.getTokenLength(context));
        }
        if ((SMSOTPUtils.getTokenExpiryTime(context)) != null) {
            long tokenExpiryTime = Integer.parseInt(SMSOTPUtils.getTokenExpiryTime(context));
            context.setProperty(SMSOTPConstants.TOKEN_VALIDITY_TIME, tokenExpiryTime);
        }
        String otpToken = token.generateToken(secret, String.valueOf(SMSOTPConstants.NUMBER_BASE), tokenLength, isEnableAlphanumericToken);
        context.setProperty(SMSOTPConstants.OTP_TOKEN, otpToken);
        if (log.isDebugEnabled()) {
            log.debug("Generated OTP successfully and set to the context.");
        }
        // Get the values of the sms provider related api parameters.
        String smsUrl = authenticatorProperties.get(SMSOTPConstants.SMS_URL);
        String httpMethod = authenticatorProperties.get(SMSOTPConstants.HTTP_METHOD);
        String headerString = authenticatorProperties.get(SMSOTPConstants.HEADERS);
        String payload = authenticatorProperties.get(SMSOTPConstants.PAYLOAD);
        String httpResponse = authenticatorProperties.get(SMSOTPConstants.HTTP_RESPONSE);
        boolean connectionResult = true;
        // Check the SMS URL configure in UI and give the first priority for that.
        if (StringUtils.isNotEmpty(smsUrl)) {
            connectionResult = sendRESTCall(context, smsUrl, httpMethod, headerString, payload, httpResponse, mobileNumber, otpToken);
        } else {
            // Use the default notification mechanism (CEP) to send SMS.
            AuthenticatedUser authenticatedUser = (AuthenticatedUser) context.getProperty(SMSOTPConstants.AUTHENTICATED_USER);
            triggerNotification(authenticatedUser.getUserName(), authenticatedUser.getTenantDomain(), authenticatedUser.getUserStoreDomain(), mobileNumber, otpToken);
        }
        if (!connectionResult) {
            String retryParam;
            if (context.getProperty(SMSOTPConstants.ERROR_CODE) != null) {
                String errorCode = context.getProperty(SMSOTPConstants.ERROR_CODE).toString();
                // to local error codes and passed as query param value for authfailure msg.
                if (SMSOTPUtils.useInternalErrorCodes(context)) {
                    String errorResponseCode = getHttpErrorResponseCode(errorCode);
                    if (StringUtils.isNotEmpty(errorResponseCode)) {
                        String internalErrorCode = SMSOTPConstants.ErrorMessage.getMappedInternalErrorCode(errorResponseCode).getCode();
                        errorCode = URLEncoder.encode(internalErrorCode, CHAR_SET_UTF_8);
                    }
                }
                retryParam = SMSOTPConstants.ERROR_MESSAGE + errorCode;
                String errorInfo = context.getProperty(SMSOTPConstants.ERROR_INFO).toString();
                if (Boolean.parseBoolean(authenticatorProperties.get(SMSOTPConstants.SHOW_ERROR_INFO)) && errorInfo != null) {
                    retryParam = retryParam + SMSOTPConstants.ERROR_MESSAGE_DETAILS + getEncoder().encodeToString(errorInfo.getBytes());
                }
            } else {
                retryParam = SMSOTPConstants.ERROR_MESSAGE + SMSOTPConstants.UNABLE_SEND_CODE_VALUE;
            }
            String redirectUrl = getURL(errorPage, queryParams);
            response.sendRedirect(redirectUrl + SMSOTPConstants.RESEND_CODE + isEnableResendCode + retryParam);
        } else {
            long sentOTPTokenTime = System.currentTimeMillis();
            context.setProperty(SMSOTPConstants.SENT_OTP_TOKEN_TIME, sentOTPTokenTime);
            String url = getURL(loginPage, queryParams);
            boolean isUserExists = FederatedAuthenticatorUtil.isUserExistInUserStore(username);
            if (isUserExists) {
                screenValue = getScreenAttribute(context, userRealm, tenantAwareUsername);
                if (screenValue != null) {
                    url = url + SMSOTPConstants.SCREEN_VALUE + screenValue;
                }
            }
            response.sendRedirect(url);
        }
    } catch (IOException e) {
        throw new AuthenticationFailedException("Error while sending the HTTP request. ", e);
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Failed to get the user from user store. ", e);
    }
}
Also used : UserRealm(org.wso2.carbon.user.api.UserRealm) AuthenticationFailedException(org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) IOException(java.io.IOException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

HashMap (java.util.HashMap)31 IdentityEventException (org.wso2.carbon.identity.event.IdentityEventException)25 UserRecoveryData (org.wso2.carbon.identity.recovery.model.UserRecoveryData)21 UserRecoveryDataStore (org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore)18 IdentityRecoveryException (org.wso2.carbon.identity.recovery.IdentityRecoveryException)17 UserStoreException (org.wso2.carbon.user.api.UserStoreException)17 Event (org.wso2.carbon.identity.event.event.Event)14 IdentityException (org.wso2.carbon.identity.base.IdentityException)13 User (org.wso2.carbon.identity.application.common.model.User)10 NotificationResponseBean (org.wso2.carbon.identity.recovery.bean.NotificationResponseBean)10 ArrayList (java.util.ArrayList)8 QName (javax.xml.namespace.QName)8 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)8 Map (java.util.Map)7 Test (org.testng.annotations.Test)7 Property (org.wso2.carbon.identity.recovery.model.Property)7 NotificationChannels (org.wso2.carbon.identity.governance.service.notification.NotificationChannels)6 UserStoreException (org.wso2.carbon.user.core.UserStoreException)6 NotificationException (org.wso2.carbon.apimgt.impl.notification.exception.NotificationException)5 NotificationDataDTO (org.wso2.carbon.identity.mgt.dto.NotificationDataDTO)5