Search in sources :

Example 1 with NotifyRequest

use of uk.gov.di.accountmanagement.entity.NotifyRequest in project di-authentication-api by alphagov.

the class NotificationHandler method handleRequest.

@Override
public Void handleRequest(SQSEvent event, Context context) {
    for (SQSMessage msg : event.getRecords()) {
        try {
            LOG.info("Message received from SQS queue");
            NotifyRequest notifyRequest = objectMapper.readValue(msg.getBody(), NotifyRequest.class);
            try {
                switch(notifyRequest.getNotificationType()) {
                    case VERIFY_EMAIL:
                        Map<String, Object> emailPersonalisation = new HashMap<>();
                        emailPersonalisation.put("validation-code", notifyRequest.getCode());
                        emailPersonalisation.put("email-address", notifyRequest.getDestination());
                        emailPersonalisation.put("contact-us-link", buildContactUsUrl());
                        LOG.info("Sending VERIFY_EMAIL email using Notify");
                        notificationService.sendEmail(notifyRequest.getDestination(), emailPersonalisation, notificationService.getNotificationTemplateId(NotificationType.VERIFY_EMAIL));
                        LOG.info("VERIFY_EMAIL email has been sent using Notify");
                        break;
                    case VERIFY_PHONE_NUMBER:
                        Map<String, Object> phonePersonalisation = new HashMap<>();
                        phonePersonalisation.put("validation-code", notifyRequest.getCode());
                        LOG.info("Sending VERIFY_PHONE_NUMBER email using Notify");
                        notificationService.sendText(notifyRequest.getDestination(), phonePersonalisation, notificationService.getNotificationTemplateId(NotificationType.VERIFY_PHONE_NUMBER));
                        LOG.info("VERIFY_PHONE_NUMBER text has been sent using Notify");
                        break;
                    case EMAIL_UPDATED:
                        Map<String, Object> emailUpdatePersonalisation = new HashMap<>();
                        emailUpdatePersonalisation.put("email-address", notifyRequest.getDestination());
                        emailUpdatePersonalisation.put("customer-support-link", buildURI(configurationService.getFrontendBaseUrl(), configurationService.getCustomerSupportLinkRoute()).toString());
                        LOG.info("Sending EMAIL_UPDATED email using Notify");
                        notificationService.sendEmail(notifyRequest.getDestination(), emailUpdatePersonalisation, notificationService.getNotificationTemplateId(NotificationType.EMAIL_UPDATED));
                        LOG.info("EMAIL_UPDATED email has been sent using Notify");
                        break;
                    case DELETE_ACCOUNT:
                        LOG.info("Sending DELETE_ACCOUNT email using Notify");
                        Map<String, Object> accountDeletedPersonalisation = new HashMap<>();
                        accountDeletedPersonalisation.put("customer-support-link", buildURI(configurationService.getFrontendBaseUrl(), configurationService.getCustomerSupportLinkRoute()).toString());
                        notificationService.sendEmail(notifyRequest.getDestination(), accountDeletedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.DELETE_ACCOUNT));
                        LOG.info("DELETE_ACCOUNT email has been sent using Notify");
                        break;
                    case PHONE_NUMBER_UPDATED:
                        LOG.info("Sending PHONE_NUMBER_UPDATED email using Notify");
                        Map<String, Object> phoneNumberUpdatedPersonalisation = new HashMap<>();
                        phoneNumberUpdatedPersonalisation.put("customer-support-link", buildURI(configurationService.getFrontendBaseUrl(), configurationService.getCustomerSupportLinkRoute()).toString());
                        notificationService.sendEmail(notifyRequest.getDestination(), phoneNumberUpdatedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.PHONE_NUMBER_UPDATED));
                        LOG.info("PHONE_NUMBER_UPDATED email has been sent using Notify");
                        break;
                    case PASSWORD_UPDATED:
                        LOG.info("Sending PASSWORD_UPDATED email using Notify");
                        Map<String, Object> passwordUpdatedPersonalisation = new HashMap<>();
                        passwordUpdatedPersonalisation.put("customer-support-link", buildURI(configurationService.getFrontendBaseUrl(), configurationService.getCustomerSupportLinkRoute()).toString());
                        notificationService.sendEmail(notifyRequest.getDestination(), passwordUpdatedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.PASSWORD_UPDATED));
                        LOG.info("PASSWORD_UPDATED email has been sent using Notify");
                        break;
                }
            } catch (NotificationClientException e) {
                LOG.error("Error sending with Notify", e);
                throw new RuntimeException(String.format("Error sending with Notify using NotificationType: %s", notifyRequest.getNotificationType()), e);
            }
        } catch (JsonProcessingException e) {
            LOG.error("Error when mapping message from queue to a NotifyRequest");
            throw new RuntimeException("Error when mapping message from queue to a NotifyRequest");
        }
    }
    return null;
}
Also used : NotificationClientException(uk.gov.service.notify.NotificationClientException) HashMap(java.util.HashMap) SQSMessage(com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 2 with NotifyRequest

use of uk.gov.di.accountmanagement.entity.NotifyRequest in project di-authentication-api by alphagov.

the class UpdateEmailHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        String sessionId = RequestHeaderHelper.getHeaderValueOrElse(input.getHeaders(), SESSION_ID_HEADER, "");
        attachSessionIdToLogs(sessionId);
        LOG.info("UpdateEmailHandler received request");
        try {
            UpdateEmailRequest updateInfoRequest = objectMapper.readValue(input.getBody(), UpdateEmailRequest.class);
            boolean isValidOtpCode = codeStorageService.isValidOtpCode(updateInfoRequest.getReplacementEmailAddress(), updateInfoRequest.getOtp(), NotificationType.VERIFY_EMAIL);
            if (!isValidOtpCode) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1020);
            }
            Optional<ErrorResponse> emailValidationErrors = validationService.validateEmailAddressUpdate(updateInfoRequest.getExistingEmailAddress(), updateInfoRequest.getReplacementEmailAddress());
            if (emailValidationErrors.isPresent()) {
                return generateApiGatewayProxyErrorResponse(400, emailValidationErrors.get());
            }
            if (dynamoService.userExists(updateInfoRequest.getReplacementEmailAddress())) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1009);
            }
            UserProfile userProfile = dynamoService.getUserProfileByEmail(updateInfoRequest.getExistingEmailAddress());
            Map<String, Object> authorizerParams = input.getRequestContext().getAuthorizer();
            RequestBodyHelper.validatePrincipal(new Subject(userProfile.getPublicSubjectID()), authorizerParams);
            dynamoService.updateEmail(updateInfoRequest.getExistingEmailAddress(), updateInfoRequest.getReplacementEmailAddress());
            LOG.info("Email has successfully been updated. Adding message to SQS queue");
            NotifyRequest notifyRequest = new NotifyRequest(updateInfoRequest.getReplacementEmailAddress(), NotificationType.EMAIL_UPDATED);
            sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
            auditService.submitAuditEvent(AccountManagementAuditableEvent.UPDATE_EMAIL, context.getAwsRequestId(), sessionId, AuditService.UNKNOWN, userProfile.getSubjectID(), updateInfoRequest.getReplacementEmailAddress(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            LOG.info("Message successfully added to queue. Generating successful gateway response");
            return generateEmptySuccessApiGatewayResponse();
        } catch (JsonProcessingException | IllegalArgumentException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    });
}
Also used : UpdateEmailRequest(uk.gov.di.accountmanagement.entity.UpdateEmailRequest) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest) Subject(com.nimbusds.oauth2.sdk.id.Subject) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with NotifyRequest

use of uk.gov.di.accountmanagement.entity.NotifyRequest in project di-authentication-api by alphagov.

the class NotificationHandler method notificationRequestHandler.

public Void notificationRequestHandler(SQSEvent event, Context context) {
    for (SQSMessage msg : event.getRecords()) {
        try {
            LOG.info("Message received from SQS queue");
            NotifyRequest notifyRequest = objectMapper.readValue(msg.getBody(), NotifyRequest.class);
            try {
                switch(notifyRequest.getNotificationType()) {
                    case VERIFY_EMAIL:
                        Map<String, Object> emailPersonalisation = new HashMap<>();
                        emailPersonalisation.put("validation-code", notifyRequest.getCode());
                        emailPersonalisation.put("email-address", notifyRequest.getDestination());
                        emailPersonalisation.put("contact-us-link", buildContactUsUrl("confirmEmailAddressEmail"));
                        LOG.info("Sending VERIFY_EMAIL email using Notify");
                        notificationService.sendEmail(notifyRequest.getDestination(), emailPersonalisation, notificationService.getNotificationTemplateId(NotificationType.VERIFY_EMAIL));
                        LOG.info("VERIFY_EMAIL email has been sent using Notify");
                        break;
                    case VERIFY_PHONE_NUMBER:
                        Map<String, Object> phonePersonalisation = new HashMap<>();
                        phonePersonalisation.put("validation-code", notifyRequest.getCode());
                        LOG.info("Sending VERIFY_PHONE_NUMBER email using Notify");
                        notificationService.sendText(notifyRequest.getDestination(), phonePersonalisation, notificationService.getNotificationTemplateId(NotificationType.VERIFY_PHONE_NUMBER));
                        LOG.info("VERIFY_PHONE_NUMBER text has been sent using Notify");
                        break;
                    case EMAIL_UPDATED:
                        Map<String, Object> emailUpdatePersonalisation = new HashMap<>();
                        emailUpdatePersonalisation.put("email-address", notifyRequest.getDestination());
                        emailUpdatePersonalisation.put("contact-us-link", buildContactUsUrl("emailAddressUpdatedEmail"));
                        LOG.info("Sending EMAIL_UPDATED email using Notify");
                        notificationService.sendEmail(notifyRequest.getDestination(), emailUpdatePersonalisation, notificationService.getNotificationTemplateId(NotificationType.EMAIL_UPDATED));
                        LOG.info("EMAIL_UPDATED email has been sent using Notify");
                        break;
                    case DELETE_ACCOUNT:
                        LOG.info("Sending DELETE_ACCOUNT email using Notify");
                        Map<String, Object> accountDeletedPersonalisation = new HashMap<>();
                        accountDeletedPersonalisation.put("contact-us-link", buildContactUsUrl("accountDeletedEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), accountDeletedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.DELETE_ACCOUNT));
                        LOG.info("DELETE_ACCOUNT email has been sent using Notify");
                        break;
                    case PHONE_NUMBER_UPDATED:
                        LOG.info("Sending PHONE_NUMBER_UPDATED email using Notify");
                        Map<String, Object> phoneNumberUpdatedPersonalisation = new HashMap<>();
                        phoneNumberUpdatedPersonalisation.put("contact-us-link", buildContactUsUrl("phoneNumberUpdatedEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), phoneNumberUpdatedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.PHONE_NUMBER_UPDATED));
                        LOG.info("PHONE_NUMBER_UPDATED email has been sent using Notify");
                        break;
                    case PASSWORD_UPDATED:
                        LOG.info("Sending PASSWORD_UPDATED email using Notify");
                        Map<String, Object> passwordUpdatedPersonalisation = new HashMap<>();
                        passwordUpdatedPersonalisation.put("contact-us-link", buildContactUsUrl("passwordUpdatedEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), passwordUpdatedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.PASSWORD_UPDATED));
                        LOG.info("PASSWORD_UPDATED email has been sent using Notify");
                        break;
                }
            } catch (NotificationClientException e) {
                LOG.error("Error sending with Notify", e);
                throw new RuntimeException(String.format("Error sending with Notify using NotificationType: %s", notifyRequest.getNotificationType()), e);
            }
        } catch (JsonException e) {
            LOG.error("Error when mapping message from queue to a NotifyRequest");
            throw new RuntimeException("Error when mapping message from queue to a NotifyRequest");
        }
    }
    return null;
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) NotificationClientException(uk.gov.service.notify.NotificationClientException) HashMap(java.util.HashMap) SQSMessage(com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest)

Example 4 with NotifyRequest

use of uk.gov.di.accountmanagement.entity.NotifyRequest in project di-authentication-api by alphagov.

the class RemoveAccountHandler method removeAccountRequestHandler.

public APIGatewayProxyResponseEvent removeAccountRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        try {
            String sessionId = RequestHeaderHelper.getHeaderValueOrElse(input.getHeaders(), SESSION_ID_HEADER, "");
            attachSessionIdToLogs(sessionId);
            LOG.info("RemoveAccountHandler received request");
            RemoveAccountRequest removeAccountRequest = objectMapper.readValue(input.getBody(), RemoveAccountRequest.class);
            String email = removeAccountRequest.getEmail();
            UserProfile userProfile = authenticationService.getUserProfileByEmailMaybe(email).orElseThrow(() -> new RuntimeException("User not found"));
            Map<String, Object> authorizerParams = input.getRequestContext().getAuthorizer();
            RequestBodyHelper.validatePrincipal(new Subject(userProfile.getPublicSubjectID()), authorizerParams);
            authenticationService.removeAccount(email);
            LOG.info("User account removed. Adding message to SQS queue");
            NotifyRequest notifyRequest = new NotifyRequest(email, NotificationType.DELETE_ACCOUNT);
            sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
            LOG.info("Remove account message successfully added to queue. Generating successful gateway response");
            auditService.submitAuditEvent(AccountManagementAuditableEvent.DELETE_ACCOUNT, context.getAwsRequestId(), sessionId, AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            return generateEmptySuccessApiGatewayResponse();
        } catch (JsonException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    });
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) RemoveAccountRequest(uk.gov.di.accountmanagement.entity.RemoveAccountRequest) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest) Subject(com.nimbusds.oauth2.sdk.id.Subject)

Example 5 with NotifyRequest

use of uk.gov.di.accountmanagement.entity.NotifyRequest in project di-authentication-api by alphagov.

the class UpdatePhoneNumberHandler method updatePhoneNumberRequestHandler.

public APIGatewayProxyResponseEvent updatePhoneNumberRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        String sessionId = RequestHeaderHelper.getHeaderValueOrElse(input.getHeaders(), SESSION_ID_HEADER, "");
        attachSessionIdToLogs(sessionId);
        LOG.info("UpdatePhoneNumberHandler received request");
        try {
            UpdatePhoneNumberRequest updatePhoneNumberRequest = objectMapper.readValue(input.getBody(), UpdatePhoneNumberRequest.class);
            boolean isValidOtpCode = codeStorageService.isValidOtpCode(updatePhoneNumberRequest.getEmail(), updatePhoneNumberRequest.getOtp(), NotificationType.VERIFY_PHONE_NUMBER);
            if (!isValidOtpCode) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1020);
            }
            UserProfile userProfile = dynamoService.getUserProfileByEmail(updatePhoneNumberRequest.getEmail());
            Map<String, Object> authorizerParams = input.getRequestContext().getAuthorizer();
            RequestBodyHelper.validatePrincipal(new Subject(userProfile.getPublicSubjectID()), authorizerParams);
            dynamoService.updatePhoneNumber(updatePhoneNumberRequest.getEmail(), updatePhoneNumberRequest.getPhoneNumber());
            LOG.info("Phone Number has successfully been updated. Adding message to SQS queue");
            NotifyRequest notifyRequest = new NotifyRequest(updatePhoneNumberRequest.getEmail(), NotificationType.PHONE_NUMBER_UPDATED);
            sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
            auditService.submitAuditEvent(AccountManagementAuditableEvent.UPDATE_PHONE_NUMBER, context.getAwsRequestId(), sessionId, AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), updatePhoneNumberRequest.getPhoneNumber(), PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            LOG.info("Message successfully added to queue. Generating successful gateway response");
            return generateEmptySuccessApiGatewayResponse();
        } catch (JsonException | IllegalArgumentException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    });
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest) Subject(com.nimbusds.oauth2.sdk.id.Subject) UpdatePhoneNumberRequest(uk.gov.di.accountmanagement.entity.UpdatePhoneNumberRequest)

Aggregations

NotifyRequest (uk.gov.di.accountmanagement.entity.NotifyRequest)32 Test (org.junit.jupiter.api.Test)21 HashMap (java.util.HashMap)20 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)13 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)13 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)13 SQSEvent (com.amazonaws.services.lambda.runtime.events.SQSEvent)8 Subject (com.nimbusds.oauth2.sdk.id.Subject)8 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)5 JsonException (uk.gov.di.authentication.shared.serialization.Json.JsonException)5 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)3 ErrorResponse (uk.gov.di.authentication.shared.entity.ErrorResponse)3 ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse (uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)3 SQSMessage (com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage)2 RemoveAccountRequest (uk.gov.di.accountmanagement.entity.RemoveAccountRequest)2 UpdateEmailRequest (uk.gov.di.accountmanagement.entity.UpdateEmailRequest)2 UpdatePasswordRequest (uk.gov.di.accountmanagement.entity.UpdatePasswordRequest)2 UpdatePhoneNumberRequest (uk.gov.di.accountmanagement.entity.UpdatePhoneNumberRequest)2 UserCredentials (uk.gov.di.authentication.shared.entity.UserCredentials)2 NotificationClientException (uk.gov.service.notify.NotificationClientException)2