Search in sources :

Example 1 with UserCredentials

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

the class UserMigrationService method processMigratedUser.

public boolean processMigratedUser(String email, String inputPassword) {
    Optional<String> passwordPepper = configurationService.getPasswordPepper();
    char[] passwordChar = passwordPepper.map(t -> inputPassword + t).orElse(inputPassword).toCharArray();
    byte[] passwordByteArray = BCrypt.passwordToByteArray(passwordChar);
    UserCredentials userCredentials = authenticationService.getUserCredentialsFromEmail(email);
    boolean hasValidCredentials = OpenBSDBCrypt.checkPassword(userCredentials.getMigratedPassword(), passwordByteArray);
    if (!hasValidCredentials) {
        LOG.info("Migrated user has invalid credentials");
        return hasValidCredentials;
    }
    LOG.info("Migrated user has valid credentials. About to migrate password");
    authenticationService.migrateLegacyPassword(email, inputPassword);
    return true;
}
Also used : UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials)

Example 2 with UserCredentials

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

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

the class DynamoService method signUp.

@Override
public void signUp(String email, String password, Subject subject, TermsAndConditions termsAndConditions) {
    String dateTime = LocalDateTime.now().toString();
    String hashedPassword = hashPassword(password);
    UserCredentials userCredentials = new UserCredentials().setEmail(email.toLowerCase(Locale.ROOT)).setSubjectID(subject.toString()).setPassword(hashedPassword).setCreated(dateTime).setUpdated(dateTime);
    UserProfile userProfile = new UserProfile().setEmail(email.toLowerCase(Locale.ROOT)).setSubjectID(subject.toString()).setEmailVerified(true).setCreated(dateTime).setUpdated(dateTime).setPublicSubjectID((new Subject()).toString()).setTermsAndConditions(termsAndConditions).setLegacySubjectID(null);
    userCredentialsMapper.save(userCredentials);
    userProfileMapper.save(userProfile);
}
Also used : UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials) Subject(com.nimbusds.oauth2.sdk.id.Subject)

Example 4 with UserCredentials

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

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

the class UpdatePasswordHandlerTest method shouldReturn204ForValidRequest.

@Test
public void shouldReturn204ForValidRequest() throws Json.JsonException {
    String persistentIdValue = "some-persistent-session-id";
    UserProfile userProfile = new UserProfile().setPublicSubjectID(SUBJECT.getValue());
    UserCredentials userCredentials = new UserCredentials().setPassword(CURRENT_PASSWORD);
    when(dynamoService.getUserProfileByEmail(EXISTING_EMAIL_ADDRESS)).thenReturn(userProfile);
    when(dynamoService.getUserCredentialsFromEmail(EXISTING_EMAIL_ADDRESS)).thenReturn(userCredentials);
    APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
    event.setBody(format("{ \"email\": \"%s\", \"newPassword\": \"%s\" }", EXISTING_EMAIL_ADDRESS, NEW_PASSWORD));
    event.setHeaders(Map.of(PersistentIdHelper.PERSISTENT_ID_HEADER_NAME, persistentIdValue));
    APIGatewayProxyRequestEvent.ProxyRequestContext proxyRequestContext = new APIGatewayProxyRequestEvent.ProxyRequestContext();
    Map<String, Object> authorizerParams = new HashMap<>();
    authorizerParams.put("principalId", SUBJECT.getValue());
    proxyRequestContext.setIdentity(identityWithSourceIp("123.123.123.123"));
    proxyRequestContext.setAuthorizer(authorizerParams);
    event.setRequestContext(proxyRequestContext);
    APIGatewayProxyResponseEvent result = handler.handleRequest(event, context);
    assertThat(result, hasStatus(204));
    verify(dynamoService).updatePassword(EXISTING_EMAIL_ADDRESS, NEW_PASSWORD);
    NotifyRequest notifyRequest = new NotifyRequest(EXISTING_EMAIL_ADDRESS, NotificationType.PASSWORD_UPDATED);
    verify(sqsClient).send(objectMapper.writeValueAsString(notifyRequest));
    verify(auditService).submitAuditEvent(AccountManagementAuditableEvent.UPDATE_PASSWORD, context.getAwsRequestId(), AuditService.UNKNOWN, AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), "123.123.123.123", userProfile.getPhoneNumber(), persistentIdValue);
}
Also used : UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) HashMap(java.util.HashMap) UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) Test(org.junit.jupiter.api.Test)

Aggregations

UserCredentials (uk.gov.di.authentication.shared.entity.UserCredentials)14 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)11 Test (org.junit.jupiter.api.Test)8 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)5 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)5 HashMap (java.util.HashMap)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 Subject (com.nimbusds.oauth2.sdk.id.Subject)4 Context (com.amazonaws.services.lambda.runtime.Context)3 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)3 Scope (com.nimbusds.oauth2.sdk.Scope)3 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)3 State (com.nimbusds.oauth2.sdk.id.State)3 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)3 Nonce (com.nimbusds.openid.connect.sdk.Nonce)3 OIDCScopeValue (com.nimbusds.openid.connect.sdk.OIDCScopeValue)3 String.format (java.lang.String.format)3 URI (java.net.URI)3 LocalDateTime (java.time.LocalDateTime)3 ZoneId (java.time.ZoneId)3