Search in sources :

Example 1 with ErrorResponse

use of uk.gov.di.authentication.shared.entity.ErrorResponse in project di-authentication-api by alphagov.

the class ResetPasswordHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, ResetPasswordWithCodeRequest request, UserContext userContext) {
    LOG.info("Request received to ResetPasswordHandler");
    try {
        Optional<ErrorResponse> errorResponse = validationService.validatePassword(request.getPassword());
        if (errorResponse.isPresent()) {
            return generateApiGatewayProxyErrorResponse(400, errorResponse.get());
        }
        Optional<String> subject = codeStorageService.getSubjectWithPasswordResetCode(request.getCode());
        if (subject.isEmpty()) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1021);
        }
        UserCredentials userCredentials = authenticationService.getUserCredentialsFromSubject(subject.get());
        if (userCredentials.getPassword() != null) {
            if (verifyPassword(userCredentials.getPassword(), request.getPassword())) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1024);
            }
        } else {
            LOG.info("Resetting password for migrated user");
        }
        codeStorageService.deleteSubjectWithPasswordResetCode(request.getCode());
        authenticationService.updatePassword(userCredentials.getEmail(), request.getPassword());
        int incorrectPasswordCount = codeStorageService.getIncorrectPasswordCount(userCredentials.getEmail());
        if (incorrectPasswordCount != 0) {
            codeStorageService.deleteIncorrectPasswordCount(userCredentials.getEmail());
        }
        NotifyRequest notifyRequest = new NotifyRequest(userCredentials.getEmail(), NotificationType.PASSWORD_RESET_CONFIRMATION);
        LOG.info("Placing message on queue");
        sqsClient.send(serialiseRequest(notifyRequest));
        auditService.submitAuditEvent(FrontendAuditableEvent.PASSWORD_RESET_SUCCESSFUL, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, userCredentials.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
    } catch (JsonProcessingException | ConstraintViolationException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
    }
    LOG.info("Generating successful response");
    return generateEmptySuccessApiGatewayResponse();
}
Also used : ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) ConstraintViolationException(jakarta.validation.ConstraintViolationException) UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Example 2 with ErrorResponse

use of uk.gov.di.authentication.shared.entity.ErrorResponse in project di-authentication-api by alphagov.

the class SendOtpNotificationHandler 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("Request received in SendOtp Lambda");
        try {
            SendNotificationRequest sendNotificationRequest = objectMapper.readValue(input.getBody(), SendNotificationRequest.class);
            switch(sendNotificationRequest.getNotificationType()) {
                case VERIFY_EMAIL:
                    LOG.info("NotificationType is VERIFY_EMAIL");
                    Optional<ErrorResponse> emailErrorResponse = validationService.validateEmailAddress(sendNotificationRequest.getEmail());
                    if (emailErrorResponse.isPresent()) {
                        return generateApiGatewayProxyErrorResponse(400, emailErrorResponse.get());
                    }
                    if (dynamoService.userExists(sendNotificationRequest.getEmail())) {
                        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1009);
                    }
                    return handleNotificationRequest(sendNotificationRequest.getEmail(), sendNotificationRequest, input, context);
                case VERIFY_PHONE_NUMBER:
                    LOG.info("NotificationType is VERIFY_PHONE_NUMBER");
                    Optional<ErrorResponse> phoneNumberValidationError = validationService.validatePhoneNumber(sendNotificationRequest.getPhoneNumber());
                    if (phoneNumberValidationError.isPresent()) {
                        return generateApiGatewayProxyErrorResponse(400, phoneNumberValidationError.get());
                    }
                    return handleNotificationRequest(sendNotificationRequest.getPhoneNumber(), sendNotificationRequest, input, context);
            }
            return generateApiGatewayProxyErrorResponse(400, ERROR_1002);
        } catch (SdkClientException ex) {
            LOG.error("Error sending message to queue", ex);
            return generateApiGatewayProxyResponse(500, "Error sending message to queue");
        } catch (JsonProcessingException e) {
            return generateApiGatewayProxyErrorResponse(400, ERROR_1001);
        }
    });
}
Also used : SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) SendNotificationRequest(uk.gov.di.accountmanagement.entity.SendNotificationRequest) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Example 3 with ErrorResponse

use of uk.gov.di.authentication.shared.entity.ErrorResponse 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 4 with ErrorResponse

use of uk.gov.di.authentication.shared.entity.ErrorResponse in project di-authentication-api by alphagov.

the class ResetPasswordHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, ResetPasswordCompletionRequest request, UserContext userContext) {
    LOG.info("Request received to ResetPasswordHandler");
    try {
        Optional<ErrorResponse> errorResponse = ValidationHelper.validatePassword(request.getPassword());
        if (errorResponse.isPresent()) {
            return generateApiGatewayProxyErrorResponse(400, errorResponse.get());
        }
        UserCredentials userCredentials;
        if (nonNull(request.getCode())) {
            Optional<String> subject = codeStorageService.getSubjectWithPasswordResetCode(request.getCode());
            if (subject.isEmpty()) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1021);
            }
            userCredentials = authenticationService.getUserCredentialsFromSubject(subject.get());
        } else {
            userCredentials = authenticationService.getUserCredentialsFromEmail(userContext.getSession().getEmailAddress());
        }
        if (userCredentials.getPassword() != null) {
            if (verifyPassword(userCredentials.getPassword(), request.getPassword())) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1024);
            }
        } else {
            LOG.info("Resetting password for migrated user");
        }
        if (nonNull(request.getCode())) {
            codeStorageService.deleteSubjectWithPasswordResetCode(request.getCode());
        }
        authenticationService.updatePassword(userCredentials.getEmail(), request.getPassword());
        int incorrectPasswordCount = codeStorageService.getIncorrectPasswordCount(userCredentials.getEmail());
        if (incorrectPasswordCount != 0) {
            codeStorageService.deleteIncorrectPasswordCount(userCredentials.getEmail());
        }
        NotifyRequest notifyRequest = new NotifyRequest(userCredentials.getEmail(), NotificationType.PASSWORD_RESET_CONFIRMATION);
        LOG.info("Placing message on queue");
        sqsClient.send(serialiseRequest(notifyRequest));
        auditService.submitAuditEvent(FrontendAuditableEvent.PASSWORD_RESET_SUCCESSFUL, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, userCredentials.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
    } catch (JsonException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
    }
    LOG.info("Generating successful response");
    return generateEmptySuccessApiGatewayResponse();
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Example 5 with ErrorResponse

use of uk.gov.di.authentication.shared.entity.ErrorResponse in project di-authentication-api by alphagov.

the class SendNotificationHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, SendNotificationRequest request, UserContext userContext) {
    attachSessionIdToLogs(userContext.getSession());
    attachLogFieldToLogs(PERSISTENT_SESSION_ID, extractPersistentIdFromHeaders(input.getHeaders()));
    attachLogFieldToLogs(LogFieldName.CLIENT_ID, userContext.getClient().map(ClientRegistry::getClientID).orElse("unknown"));
    try {
        if (!userContext.getSession().validateSession(request.getEmail())) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1000);
        }
        if (request.getNotificationType().equals(ACCOUNT_CREATED_CONFIRMATION)) {
            LOG.info("Placing message on queue for AccountCreatedConfirmation");
            NotifyRequest notifyRequest = new NotifyRequest(request.getEmail(), ACCOUNT_CREATED_CONFIRMATION);
            if (notTestClientWithValidTestEmail(userContext, ACCOUNT_CREATED_CONFIRMATION)) {
                sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
                LOG.info("AccountCreatedConfirmation email placed on queue");
            }
            return generateEmptySuccessApiGatewayResponse();
        }
        Optional<ErrorResponse> codeRequestValid = isCodeRequestAttemptValid(request.getEmail(), userContext.getSession(), request.getNotificationType());
        if (codeRequestValid.isPresent()) {
            return generateApiGatewayProxyErrorResponse(400, codeRequestValid.get());
        }
        switch(request.getNotificationType()) {
            case VERIFY_EMAIL:
                return handleNotificationRequest(request.getEmail(), request.getNotificationType(), userContext.getSession(), userContext);
            case VERIFY_PHONE_NUMBER:
                if (request.getPhoneNumber() == null) {
                    return generateApiGatewayProxyResponse(400, ERROR_1011);
                }
                return handleNotificationRequest(PhoneNumberHelper.removeWhitespaceFromPhoneNumber(request.getPhoneNumber()), request.getNotificationType(), userContext.getSession(), userContext);
        }
        return generateApiGatewayProxyErrorResponse(400, ERROR_1002);
    } catch (SdkClientException ex) {
        LOG.error("Error sending message to queue");
        return generateApiGatewayProxyResponse(500, "Error sending message to queue");
    } catch (JsonException e) {
        return generateApiGatewayProxyErrorResponse(400, ERROR_1001);
    } catch (ClientNotFoundException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1015);
    }
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) ClientNotFoundException(uk.gov.di.authentication.shared.exceptions.ClientNotFoundException) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Aggregations

ErrorResponse (uk.gov.di.authentication.shared.entity.ErrorResponse)12 ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse (uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)12 ClientRegistry (uk.gov.di.authentication.shared.entity.ClientRegistry)7 JsonException (uk.gov.di.authentication.shared.serialization.Json.JsonException)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 Subject (com.nimbusds.oauth2.sdk.id.Subject)4 NotifyRequest (uk.gov.di.authentication.shared.entity.NotifyRequest)4 SdkClientException (software.amazon.awssdk.core.exception.SdkClientException)3 NotifyRequest (uk.gov.di.accountmanagement.entity.NotifyRequest)3 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)3 ClientNotFoundException (uk.gov.di.authentication.shared.exceptions.ClientNotFoundException)3 SendNotificationRequest (uk.gov.di.accountmanagement.entity.SendNotificationRequest)2 UpdateEmailRequest (uk.gov.di.accountmanagement.entity.UpdateEmailRequest)2 FrontendAuditableEvent (uk.gov.di.authentication.frontendapi.domain.FrontendAuditableEvent)2 AuditableEvent (uk.gov.di.authentication.shared.domain.AuditableEvent)2 UserCredentials (uk.gov.di.authentication.shared.entity.UserCredentials)2 ConstraintViolationException (jakarta.validation.ConstraintViolationException)1 UpdatePhoneNumberRequest (uk.gov.di.accountmanagement.entity.UpdatePhoneNumberRequest)1 CheckUserExistsResponse (uk.gov.di.authentication.frontendapi.entity.CheckUserExistsResponse)1 SignUpResponse (uk.gov.di.authentication.frontendapi.entity.SignUpResponse)1