Search in sources :

Example 1 with SignUpResponse

use of uk.gov.di.authentication.frontendapi.entity.SignUpResponse 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());
    }
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) SignUpResponse(uk.gov.di.authentication.frontendapi.entity.SignUpResponse) TermsAndConditions(uk.gov.di.authentication.shared.entity.TermsAndConditions) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) 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)

Example 2 with SignUpResponse

use of uk.gov.di.authentication.frontendapi.entity.SignUpResponse in project di-authentication-api by alphagov.

the class SignUpHandlerTest method shouldReturn200IfSignUpIsSuccessful.

@ParameterizedTest
@MethodSource("consentValues")
void shouldReturn200IfSignUpIsSuccessful(boolean consentRequired) throws JsonProcessingException, Json.JsonException {
    String email = "joe.bloggs@test.com";
    String password = "computer-1";
    String persistentId = "some-persistent-id-value";
    Map<String, String> headers = new HashMap<>();
    headers.put(PersistentIdHelper.PERSISTENT_ID_HEADER_NAME, persistentId);
    headers.put("Session-Id", session.getSessionId());
    when(authenticationService.userExists(eq("joe.bloggs@test.com"))).thenReturn(false);
    when(clientService.getClient(CLIENT_ID.getValue())).thenReturn(Optional.of(generateClientRegistry(consentRequired)));
    when(clientSessionService.getClientSessionFromRequestHeaders(anyMap())).thenReturn(Optional.of(clientSession));
    usingValidSession();
    usingValidClientSession();
    APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
    event.setRequestContext(contextWithSourceIp("123.123.123.123"));
    event.setHeaders(headers);
    event.setBody(format("{ \"password\": \"computer-1\", \"email\": \"%s\" }", email.toUpperCase()));
    APIGatewayProxyResponseEvent result = handler.handleRequest(event, context);
    verify(authenticationService).signUp(eq("joe.bloggs@test.com"), eq(password), any(Subject.class), any(TermsAndConditions.class));
    verify(sessionService).save(argThat((session) -> session.getEmailAddress().equals("joe.bloggs@test.com")));
    assertThat(result, hasStatus(200));
    SignUpResponse signUpResponse = objectMapper.readValue(result.getBody(), SignUpResponse.class);
    assertThat(signUpResponse.isConsentRequired(), equalTo(consentRequired));
    verify(authenticationService).signUp(eq(email), eq("computer-1"), any(Subject.class), any(TermsAndConditions.class));
    verify(auditService).submitAuditEvent(FrontendAuditableEvent.CREATE_ACCOUNT, context.getAwsRequestId(), session.getSessionId(), CLIENT_ID.getValue(), AuditService.UNKNOWN, "joe.bloggs@test.com", "123.123.123.123", AuditService.UNKNOWN, persistentId);
    verify(sessionService).save(argThat(session -> session.isNewAccount() == Session.AccountState.NEW));
}
Also used : ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) BeforeEach(org.junit.jupiter.api.BeforeEach) Json(uk.gov.di.authentication.shared.serialization.Json) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Matchers.not(org.hamcrest.Matchers.not) Context(com.amazonaws.services.lambda.runtime.Context) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) Session(uk.gov.di.authentication.shared.entity.Session) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) LogEventMatcher.withMessageContaining(uk.gov.di.authentication.sharedtest.logging.LogEventMatcher.withMessageContaining) Map(java.util.Map) URI(java.net.URI) MethodSource(org.junit.jupiter.params.provider.MethodSource) FrontendAuditableEvent(uk.gov.di.authentication.frontendapi.domain.FrontendAuditableEvent) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) AuditService(uk.gov.di.authentication.shared.services.AuditService) OIDCScopeValue(com.nimbusds.openid.connect.sdk.OIDCScopeValue) APIGatewayProxyResponseEventMatcher.hasJsonBody(uk.gov.di.authentication.sharedtest.matchers.APIGatewayProxyResponseEventMatcher.hasJsonBody) String.format(java.lang.String.format) ClientSessionService(uk.gov.di.authentication.shared.services.ClientSessionService) Test(org.junit.jupiter.api.Test) Stream(java.util.stream.Stream) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) Matchers.equalTo(org.hamcrest.Matchers.equalTo) SerializationService(uk.gov.di.authentication.shared.services.SerializationService) Optional(java.util.Optional) Nonce(com.nimbusds.openid.connect.sdk.Nonce) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IdGenerator(uk.gov.di.authentication.shared.helpers.IdGenerator) SessionService(uk.gov.di.authentication.shared.services.SessionService) ConfigurationService(uk.gov.di.authentication.shared.services.ConfigurationService) HashMap(java.util.HashMap) ArgumentMatchers.anyMap(org.mockito.ArgumentMatchers.anyMap) AuthenticationService(uk.gov.di.authentication.shared.services.AuthenticationService) SignUpResponse(uk.gov.di.authentication.frontendapi.entity.SignUpResponse) RequestEventHelper.contextWithSourceIp(uk.gov.di.authentication.sharedtest.helper.RequestEventHelper.contextWithSourceIp) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) ClientService(uk.gov.di.authentication.shared.services.ClientService) Subject(com.nimbusds.oauth2.sdk.id.Subject) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) Scope(com.nimbusds.oauth2.sdk.Scope) State(com.nimbusds.oauth2.sdk.id.State) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Mockito.when(org.mockito.Mockito.when) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) Mockito.verify(org.mockito.Mockito.verify) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) CaptureLoggingExtension(uk.gov.di.authentication.sharedtest.logging.CaptureLoggingExtension) Matchers.hasItem(org.hamcrest.Matchers.hasItem) APIGatewayProxyResponseEventMatcher.hasStatus(uk.gov.di.authentication.sharedtest.matchers.APIGatewayProxyResponseEventMatcher.hasStatus) PersistentIdHelper(uk.gov.di.authentication.shared.helpers.PersistentIdHelper) TermsAndConditions(uk.gov.di.authentication.shared.entity.TermsAndConditions) SignUpResponse(uk.gov.di.authentication.frontendapi.entity.SignUpResponse) TermsAndConditions(uk.gov.di.authentication.shared.entity.TermsAndConditions) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) HashMap(java.util.HashMap) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) Subject(com.nimbusds.oauth2.sdk.id.Subject) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 3 with SignUpResponse

use of uk.gov.di.authentication.frontendapi.entity.SignUpResponse in project di-authentication-api by alphagov.

the class SignupIntegrationTest method shouldReturn200WhenValidSignUpRequest.

@ParameterizedTest
@MethodSource("consentValues")
void shouldReturn200WhenValidSignUpRequest(boolean consentRequired) throws IOException, Json.JsonException {
    String sessionId = redis.createSession();
    Map<String, String> headers = new HashMap<>();
    headers.put("Session-Id", sessionId);
    headers.put("Client-Session-Id", CLIENT_SESSION_ID);
    headers.put("X-API-Key", FRONTEND_API_KEY);
    Scope scope = new Scope();
    scope.add(OIDCScopeValue.OPENID);
    AuthenticationRequest authRequest = new AuthenticationRequest.Builder(ResponseType.CODE, scope, new ClientID(CLIENT_ID), URI.create(REDIRECT_URI)).nonce(new Nonce()).build();
    redis.createClientSession(CLIENT_SESSION_ID, authRequest.toParameters());
    clientStore.registerClient(CLIENT_ID, "The test client", singletonList(REDIRECT_URI), singletonList("test-client@test.com"), singletonList(scope.toString()), Base64.getMimeEncoder().encodeToString(GENERATE_RSA_KEY_PAIR().getPublic().getEncoded()), singletonList("http://localhost/post-redirect-logout"), "http://example.com", String.valueOf(ServiceType.MANDATORY), "https://test.com", "public", consentRequired);
    var response = makeRequest(Optional.of(new SignupRequest("joe.bloggs+5@digital.cabinet-office.gov.uk", "password-1")), headers, Map.of());
    assertThat(response, hasStatus(200));
    SignUpResponse signUpResponse = objectMapper.readValue(response.getBody(), SignUpResponse.class);
    assertThat(signUpResponse.isConsentRequired(), equalTo(consentRequired));
    assertTrue(userStore.userExists("joe.bloggs+5@digital.cabinet-office.gov.uk"));
    assertEventTypesReceived(auditTopic, List.of(CREATE_ACCOUNT));
}
Also used : Nonce(com.nimbusds.openid.connect.sdk.Nonce) SignUpResponse(uk.gov.di.authentication.frontendapi.entity.SignUpResponse) Scope(com.nimbusds.oauth2.sdk.Scope) HashMap(java.util.HashMap) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) SignupRequest(uk.gov.di.authentication.frontendapi.entity.SignupRequest) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Aggregations

SignUpResponse (uk.gov.di.authentication.frontendapi.entity.SignUpResponse)3 Scope (com.nimbusds.oauth2.sdk.Scope)2 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)2 Subject (com.nimbusds.oauth2.sdk.id.Subject)2 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)2 Nonce (com.nimbusds.openid.connect.sdk.Nonce)2 HashMap (java.util.HashMap)2 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)2 MethodSource (org.junit.jupiter.params.provider.MethodSource)2 ClientRegistry (uk.gov.di.authentication.shared.entity.ClientRegistry)2 Context (com.amazonaws.services.lambda.runtime.Context)1 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)1 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)1 State (com.nimbusds.oauth2.sdk.id.State)1 OIDCScopeValue (com.nimbusds.openid.connect.sdk.OIDCScopeValue)1 String.format (java.lang.String.format)1 URI (java.net.URI)1 Map (java.util.Map)1