use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.
the class TokenService method generateAndStoreRefreshToken.
private RefreshToken generateAndStoreRefreshToken(String clientId, Subject internalSubject, List<String> scopes, Subject subject) {
LOG.info("Generating RefreshToken");
Date expiryDate = NowHelper.nowPlus(configService.getSessionExpiry(), ChronoUnit.SECONDS);
var jwtId = IdGenerator.generate();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("scope", scopes).issuer(configService.getOidcApiBaseURL().get()).expirationTime(expiryDate).issueTime(NowHelper.now()).claim("client_id", clientId).subject(subject.getValue()).jwtID(jwtId).build();
SignedJWT signedJWT = generateSignedJWT(claimsSet, Optional.empty());
RefreshToken refreshToken = new RefreshToken(signedJWT.serialize());
String redisKey = REFRESH_TOKEN_PREFIX + jwtId;
var store = new RefreshTokenStore(refreshToken.getValue(), internalSubject.toString());
try {
redisConnectionService.saveWithExpiry(redisKey, objectMapper.writeValueAsString(store), configService.getSessionExpiry());
} catch (JsonException e) {
throw new RuntimeException("Error serializing refresh token store", e);
}
return refreshToken;
}
use of uk.gov.di.authentication.shared.serialization.Json.JsonException 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();
}
use of uk.gov.di.authentication.shared.serialization.Json.JsonException 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);
}
}
use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.
the class SignUpHandler method handleRequestWithUserContext.
@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, SignupRequest request, UserContext userContext) {
attachSessionIdToLogs(userContext.getSession());
attachLogFieldToLogs(PERSISTENT_SESSION_ID, extractPersistentIdFromHeaders(input.getHeaders()));
attachLogFieldToLogs(CLIENT_ID, userContext.getClient().map(ClientRegistry::getClientID).orElse("unknown"));
LOG.info("Received request");
Optional<ErrorResponse> passwordValidationErrors = ValidationHelper.validatePassword(request.getPassword());
if (passwordValidationErrors.isEmpty()) {
if (authenticationService.userExists(request.getEmail())) {
auditService.submitAuditEvent(FrontendAuditableEvent.CREATE_ACCOUNT_EMAIL_ALREADY_EXISTS, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, request.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1009);
}
authenticationService.signUp(request.getEmail(), request.getPassword(), new Subject(), new TermsAndConditions(configurationService.getTermsAndConditionsVersion(), LocalDateTime.now(ZoneId.of("UTC")).toString()));
var consentRequired = ConsentHelper.userHasNotGivenConsent(userContext);
auditService.submitAuditEvent(FrontendAuditableEvent.CREATE_ACCOUNT, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, request.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
sessionService.save(userContext.getSession().setEmailAddress(request.getEmail()).setNewAccount(NEW));
LOG.info("Successfully processed request");
try {
return generateApiGatewayProxyResponse(200, new SignUpResponse(consentRequired));
} catch (JsonException e) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
}
} else {
return generateApiGatewayProxyErrorResponse(400, passwordValidationErrors.get());
}
}
use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.
the class CheckUserExistsHandler method handleRequestWithUserContext.
@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, CheckUserExistsRequest request, UserContext userContext) {
attachSessionIdToLogs(userContext.getSession());
attachLogFieldToLogs(PERSISTENT_SESSION_ID, extractPersistentIdFromHeaders(input.getHeaders()));
attachLogFieldToLogs(CLIENT_ID, userContext.getClient().map(ClientRegistry::getClientID).orElse("unknown"));
try {
LOG.info("Processing request");
String emailAddress = request.getEmail().toLowerCase();
Optional<ErrorResponse> errorResponse = ValidationHelper.validateEmailAddress(emailAddress);
String persistentSessionId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
if (errorResponse.isPresent()) {
auditService.submitAuditEvent(FrontendAuditableEvent.CHECK_USER_INVALID_EMAIL, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, emailAddress, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
return generateApiGatewayProxyErrorResponse(400, errorResponse.get());
}
boolean userExists = authenticationService.userExists(emailAddress);
userContext.getSession().setEmailAddress(emailAddress);
AuditableEvent auditableEvent;
if (userExists) {
auditableEvent = FrontendAuditableEvent.CHECK_USER_KNOWN_EMAIL;
} else {
auditableEvent = FrontendAuditableEvent.CHECK_USER_NO_ACCOUNT_WITH_EMAIL;
}
auditService.submitAuditEvent(auditableEvent, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, emailAddress, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
CheckUserExistsResponse checkUserExistsResponse = new CheckUserExistsResponse(emailAddress, userExists);
sessionService.save(userContext.getSession());
LOG.info("Successfully processed request");
return generateApiGatewayProxyResponse(200, checkUserExistsResponse);
} catch (JsonException e) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
}
}
Aggregations