use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.
the class LoginHandler method handleRequestWithUserContext.
@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, LoginRequest request, UserContext userContext) {
attachSessionIdToLogs(userContext.getSession().getSessionId());
LOG.info("Request received");
try {
var persistentSessionId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
Optional<UserProfile> userProfileMaybe = authenticationService.getUserProfileByEmailMaybe(request.getEmail());
if (userProfileMaybe.isEmpty()) {
auditService.submitAuditEvent(FrontendAuditableEvent.NO_ACCOUNT_WITH_EMAIL, context.getAwsRequestId(), userContext.getSession().getSessionId(), AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1010);
}
UserProfile userProfile = userProfileMaybe.get();
int incorrectPasswordCount = codeStorageService.getIncorrectPasswordCount(request.getEmail());
if (incorrectPasswordCount >= configurationService.getMaxPasswordRetries()) {
LOG.info("User has exceeded max password retries");
auditService.submitAuditEvent(FrontendAuditableEvent.ACCOUNT_TEMPORARILY_LOCKED, context.getAwsRequestId(), userContext.getSession().getSessionId(), AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), persistentSessionId);
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1028);
}
if (!credentialsAreValid(request, userProfile)) {
codeStorageService.increaseIncorrectPasswordCount(request.getEmail());
auditService.submitAuditEvent(FrontendAuditableEvent.INVALID_CREDENTIALS, context.getAwsRequestId(), userContext.getSession().getSessionId(), AuditService.UNKNOWN, AuditService.UNKNOWN, request.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
return generateApiGatewayProxyErrorResponse(401, ErrorResponse.ERROR_1008);
}
if (incorrectPasswordCount != 0) {
codeStorageService.deleteIncorrectPasswordCount(request.getEmail());
}
var isPhoneNumberVerified = userProfile.isPhoneNumberVerified();
String redactedPhoneNumber = null;
if (isPhoneNumberVerified) {
redactedPhoneNumber = RedactPhoneNumberHelper.redactPhoneNumber(userProfile.getPhoneNumber());
}
boolean termsAndConditionsAccepted = false;
if (Objects.nonNull(userProfile.getTermsAndConditions())) {
termsAndConditionsAccepted = TermsAndConditionsHelper.hasTermsAndConditionsBeenAccepted(userProfile.getTermsAndConditions(), configurationService.getTermsAndConditionsVersion());
}
sessionService.save(userContext.getSession().setNewAccount(EXISTING));
var isMfaRequired = MfaHelper.mfaRequired(userContext.getClientSession().getAuthRequestParams());
var consentRequired = ConsentHelper.userHasNotGivenConsent(userContext);
LOG.info("User has successfully logged in");
auditService.submitAuditEvent(LOG_IN_SUCCESS, context.getAwsRequestId(), userContext.getSession().getSessionId(), AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), persistentSessionId);
return generateApiGatewayProxyResponse(200, new LoginResponse(redactedPhoneNumber, isMfaRequired, isPhoneNumberVerified, termsAndConditionsAccepted, consentRequired));
} catch (JsonException e) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
}
}
use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.
the class NotifyCallbackHandler method notifyCallbackRequestHandler.
public APIGatewayProxyResponseEvent notifyCallbackRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
LOG.info("Received request");
validateBearerToken(input.getHeaders());
NotifyDeliveryReceipt deliveryReceipt;
try {
deliveryReceipt = objectMapper.readValue(input.getBody(), NotifyDeliveryReceipt.class);
if (deliveryReceipt.getNotificationType().equals("sms")) {
var countryCode = getCountryCodeFromNumber(deliveryReceipt.getTo());
var deliveryStatus = getDeliveryStatus(deliveryReceipt.getStatus());
LOG.info("SmsDeliveryStatus: {}, NotifyStatus: {}, CountryCode: {}", deliveryStatus, deliveryReceipt.getStatus(), countryCode);
cloudwatchMetricsService.incrementCounter(deliveryStatus, Map.of("CountryCode", String.valueOf(countryCode), "Environment", configurationService.getEnvironment(), "NotifyStatus", deliveryReceipt.getStatus()));
LOG.info("SMS callback request processed");
}
} catch (JsonException e) {
LOG.error("Unable to parse Notify Delivery Receipt");
throw new RuntimeException("Unable to parse Notify Delivery Receipt");
}
return generateEmptySuccessApiGatewayResponse();
}
use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.
the class UpdateEmailHandler method updateEmailRequestHandler.
public APIGatewayProxyResponseEvent updateEmailRequestHandler(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 = ValidationHelper.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 (JsonException | IllegalArgumentException e) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
}
});
}
use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.
the class UpdatePasswordHandler method updatePasswordRequestHandler.
public APIGatewayProxyResponseEvent updatePasswordRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
return isWarming(input).orElseGet(() -> {
String sessionId = RequestHeaderHelper.getHeaderValueOrElse(input.getHeaders(), SESSION_ID_HEADER, "");
attachSessionIdToLogs(sessionId);
LOG.info("UpdatePasswordHandler received request");
context.getClientContext();
try {
UpdatePasswordRequest updatePasswordRequest = objectMapper.readValue(input.getBody(), UpdatePasswordRequest.class);
UserProfile userProfile = dynamoService.getUserProfileByEmail(updatePasswordRequest.getEmail());
Map<String, Object> authorizerParams = input.getRequestContext().getAuthorizer();
RequestBodyHelper.validatePrincipal(new Subject(userProfile.getPublicSubjectID()), authorizerParams);
String currentPassword = dynamoService.getUserCredentialsFromEmail(updatePasswordRequest.getEmail()).getPassword();
if (verifyPassword(currentPassword, updatePasswordRequest.getNewPassword())) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1024);
}
dynamoService.updatePassword(updatePasswordRequest.getEmail(), updatePasswordRequest.getNewPassword());
LOG.info("User Password has successfully been updated. Adding confirmation message to SQS queue");
NotifyRequest notifyRequest = new NotifyRequest(updatePasswordRequest.getEmail(), NotificationType.PASSWORD_UPDATED);
sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
LOG.info("Message successfully added to queue. Generating successful gateway response");
auditService.submitAuditEvent(AccountManagementAuditableEvent.UPDATE_PASSWORD, context.getAwsRequestId(), sessionId, AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
return generateEmptySuccessApiGatewayResponse();
} catch (JsonException | IllegalArgumentException e) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
}
});
}
use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.
the class IPVAuthorisationHandler method handleRequestWithUserContext.
@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, IPVAuthorisationRequest request, UserContext userContext) {
try {
if (!configurationService.isIdentityEnabled()) {
LOG.error("Identity is not enabled");
throw new RuntimeException("Identity is not enabled");
}
var persistentId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
attachLogFieldToLogs(PERSISTENT_SESSION_ID, persistentId);
var clientId = userContext.getClient().map(ClientRegistry::getClientID);
attachLogFieldToLogs(CLIENT_ID, clientId.orElse(UNKNOWN));
LOG.info("IPVAuthorisationHandler received request");
var authRequest = AuthenticationRequest.parse(userContext.getClientSession().getAuthRequestParams());
var pairwiseSubject = ClientSubjectHelper.getSubjectWithSectorIdentifier(userContext.getUserProfile().orElseThrow(), configurationService.getIPVSector(), authenticationService);
var clientID = new ClientID(configurationService.getIPVAuthorisationClientId());
var state = new State();
var claimsSetRequest = buildIpvClaimsRequest(authRequest).map(ClaimsSetRequest::toJSONString).orElse(null);
var nonce = new Nonce(IdGenerator.generate());
var encryptedJWT = authorisationService.constructRequestJWT(state, nonce, authRequest.getScope(), pairwiseSubject, claimsSetRequest);
var authRequestBuilder = new AuthorizationRequest.Builder(new ResponseType(ResponseType.Value.CODE), clientID).endpointURI(configurationService.getIPVAuthorisationURI()).requestObject(encryptedJWT);
var ipvAuthorisationRequest = authRequestBuilder.build();
authorisationService.storeState(userContext.getSession().getSessionId(), state);
auditService.submitAuditEvent(IPVAuditableEvent.IPV_AUTHORISATION_REQUESTED, context.getAwsRequestId(), userContext.getSession().getSessionId(), clientId.orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, request.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentId);
LOG.info("IPVAuthorisationHandler successfully processed request, redirect URI {}", ipvAuthorisationRequest.toURI().toString());
return generateApiGatewayProxyResponse(200, new IPVAuthorisationResponse(ipvAuthorisationRequest.toURI().toString()));
} catch (ParseException | JsonException e) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
}
}
Aggregations