Search in sources :

Example 1 with ResetPasswordResponse

use of io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse in project gravitee-access-management by gravitee-io.

the class ResetPasswordSubmissionEndpoint method handle.

@Override
public void handle(RoutingContext context) {
    // retrieve the client in context
    Client client = context.get(ConstantKeys.CLIENT_CONTEXT_KEY);
    // retrieve the user in context
    User user = context.get(ConstantKeys.USER_CONTEXT_KEY);
    // set user password entered during reset password process
    String password = context.request().getParam(ConstantKeys.PASSWORD_PARAM_KEY);
    user.setPassword(password);
    // reset password
    resetPassword(client, user, getAuthenticatedUser(context), h -> {
        // prepare response
        MultiMap queryParams = RequestUtils.getCleanedQueryParams(context.request());
        // if failure, return to the reset password page with an error
        if (h.failed()) {
            logger.error("An error occurs while ending user reset password process", h.cause());
            queryParams.set(ConstantKeys.ERROR_PARAM_KEY, "reset_password_failed");
            redirectToPage(context, queryParams, h.cause());
            return;
        }
        // handle response
        ResetPasswordResponse resetPasswordResponse = h.result();
        // if auto login option is enabled add the user to the session
        if (resetPasswordResponse.isAutoLogin()) {
            context.setUser(io.vertx.reactivex.ext.auth.User.newInstance(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(resetPasswordResponse.getUser())));
        }
        // no redirect uri has been set, redirect to the default page
        if (resetPasswordResponse.getRedirectUri() == null || resetPasswordResponse.getRedirectUri().isEmpty()) {
            queryParams.set(ConstantKeys.SUCCESS_PARAM_KEY, "reset_password_completed");
            redirectToPage(context, queryParams);
            return;
        }
        // else, redirect to the custom redirect_uri
        context.response().putHeader(HttpHeaders.LOCATION, resetPasswordResponse.getRedirectUri()).setStatusCode(302).end();
    });
}
Also used : MultiMap(io.vertx.reactivex.core.MultiMap) User(io.gravitee.am.model.User) ResetPasswordResponse(io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse) Client(io.gravitee.am.model.oidc.Client)

Example 2 with ResetPasswordResponse

use of io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse in project gravitee-access-management by gravitee-io.

the class ResetPasswordSubmissionEndpointTest method shouldInvokeResetPasswordEndpoint.

@Test
public void shouldInvokeResetPasswordEndpoint() throws Exception {
    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");
    client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback"));
    User user = new User();
    router.route().order(-1).handler(routingContext -> {
        routingContext.put("client", client);
        routingContext.put("user", user);
        routingContext.next();
    });
    when(userService.resetPassword(eq(client), eq(user), any())).thenReturn(Single.just(new ResetPasswordResponse()));
    testRequest(HttpMethod.POST, "/resetPassword?client_id=client-id", this::postPassword, resp -> {
        String location = resp.headers().get("location");
        assertNotNull(location);
        assertTrue(location.endsWith("/resetPassword?client_id=client-id&success=reset_password_completed"));
    }, HttpStatusCode.FOUND_302, "Found", null);
}
Also used : User(io.gravitee.am.model.User) ResetPasswordResponse(io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse) Client(io.gravitee.am.model.oidc.Client) Test(org.junit.Test)

Example 3 with ResetPasswordResponse

use of io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse in project gravitee-access-management by gravitee-io.

the class ResetPasswordSubmissionEndpointTest method shouldInvokeResetPasswordEndpoint_redirectUri.

@Test
public void shouldInvokeResetPasswordEndpoint_redirectUri() throws Exception {
    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");
    client.setRedirectUris(Collections.singletonList("http://localhost:9999/callback"));
    User user = new User();
    ResetPasswordResponse resetPasswordResponse = new ResetPasswordResponse();
    resetPasswordResponse.setAutoLogin(true);
    resetPasswordResponse.setUser(user);
    resetPasswordResponse.setRedirectUri("http://custom_uri");
    router.route().order(-1).handler(routingContext -> {
        routingContext.put("client", client);
        routingContext.put("user", user);
        routingContext.next();
    });
    when(userService.resetPassword(eq(client), eq(user), any())).thenReturn(Single.just(resetPasswordResponse));
    testRequest(HttpMethod.POST, "/resetPassword?client_id=client-id", this::postPassword, resp -> {
        String location = resp.headers().get("location");
        assertNotNull(location);
        assertEquals("http://custom_uri", location);
    }, HttpStatusCode.FOUND_302, "Found", null);
}
Also used : User(io.gravitee.am.model.User) ResetPasswordResponse(io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse) Client(io.gravitee.am.model.oidc.Client) Test(org.junit.Test)

Example 4 with ResetPasswordResponse

use of io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse in project gravitee-access-management by gravitee-io.

the class UserServiceImpl method resetPassword.

@Override
public Single<ResetPasswordResponse> resetPassword(Client client, User user, io.gravitee.am.identityprovider.api.User principal) {
    // get account settings
    final AccountSettings accountSettings = AccountSettings.getInstance(domain, client);
    // if user registration is not completed and force registration option is disabled throw invalid account exception
    if (user.isInactive() && !forceUserRegistration(domain, client)) {
        return Single.error(new AccountInactiveException("User needs to complete the activation process"));
    }
    // only idp manage password, find user idp and update its password
    return identityProviderManager.getUserProvider(user.getSource()).switchIfEmpty(Maybe.error(new UserProviderNotFoundException(user.getSource()))).flatMapSingle(userProvider -> userProvider.findByUsername(user.getUsername()).switchIfEmpty(Maybe.error(new UserNotFoundException(user.getUsername()))).flatMapSingle(idpUser -> {
        // set password
        ((DefaultUser) idpUser).setCredentials(user.getPassword());
        return userProvider.update(idpUser.getId(), idpUser);
    }).onErrorResumeNext(ex -> {
        if (ex instanceof UserNotFoundException) {
            // idp user not found, create its account
            return userProvider.create(convert(user));
        }
        return Single.error(ex);
    })).flatMap(idpUser -> {
        // if user was in pre-registration mode, end the registration process
        if (user.isPreRegistration()) {
            user.setRegistrationCompleted(true);
            user.setEnabled(true);
        }
        user.setAccountNonLocked(true);
        user.setAccountLockedAt(null);
        user.setAccountLockedUntil(null);
        user.setPassword(null);
        user.setExternalId(idpUser.getId());
        user.setLastPasswordReset(new Date());
        user.setUpdatedAt(new Date());
        // additional information
        extractAdditionalInformation(user, idpUser.getAdditionalInformation());
        // set login information
        if (accountSettings != null && accountSettings.isAutoLoginAfterResetPassword()) {
            user.setLoggedAt(new Date());
            user.setLoginsCount(user.getLoginsCount() + 1);
        }
        return userService.update(user);
    }).flatMap(user1 -> {
        LoginAttemptCriteria criteria = new LoginAttemptCriteria.Builder().domain(user1.getReferenceId()).client(user1.getClient()).username(user1.getUsername()).build();
        return loginAttemptService.reset(criteria).andThen(Single.just(user1));
    }).flatMap(user1 -> {
        if (accountSettings != null && accountSettings.isDeletePasswordlessDevicesAfterResetPassword()) {
            return credentialService.deleteByUserId(user1.getReferenceType(), user1.getReferenceId(), user1.getId()).andThen(Single.just(user1));
        }
        return Single.just(user1);
    }).flatMap(userService::enhance).map(user1 -> new ResetPasswordResponse(user1, accountSettings != null ? accountSettings.getRedirectUriAfterResetPassword() : null, accountSettings != null ? accountSettings.isAutoLoginAfterResetPassword() : false)).doOnSuccess(response -> auditService.report(AuditBuilder.builder(UserAuditBuilder.class).domain(domain.getId()).client(client).principal(principal).type(EventType.USER_PASSWORD_RESET).user(user))).doOnError(throwable -> auditService.report(AuditBuilder.builder(UserAuditBuilder.class).domain(domain.getId()).client(client).principal(principal).type(EventType.USER_PASSWORD_RESET).user(user).throwable(throwable)));
}
Also used : AccountSettings(io.gravitee.am.model.account.AccountSettings) java.util(java.util) Client(io.gravitee.am.model.oidc.Client) AccountInactiveException(io.gravitee.am.common.exception.authentication.AccountInactiveException) IdentityProviderManager(io.gravitee.am.gateway.handler.common.auth.idp.IdentityProviderManager) UserService(io.gravitee.am.gateway.handler.root.service.user.UserService) Autowired(org.springframework.beans.factory.annotation.Autowired) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) EmailService(io.gravitee.am.gateway.handler.common.email.EmailService) AuditService(io.gravitee.am.service.AuditService) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) ForgotPasswordParameters(io.gravitee.am.gateway.handler.root.service.user.model.ForgotPasswordParameters) io.gravitee.am.service.exception(io.gravitee.am.service.exception) Strings(com.google.common.base.Strings) EnrolledFactor(io.gravitee.am.model.factor.EnrolledFactor) AuditBuilder(io.gravitee.am.service.reporter.builder.AuditBuilder) JWTService(io.gravitee.am.gateway.handler.common.jwt.JWTService) Qualifier(org.springframework.beans.factory.annotation.Qualifier) CredentialService(io.gravitee.am.service.CredentialService) Observable(io.reactivex.Observable) Objects.isNull(java.util.Objects.isNull) ClientSyncService(io.gravitee.am.gateway.handler.common.client.ClientSyncService) Map.entry(java.util.Map.entry) io.reactivex(io.reactivex) LoginAttemptService(io.gravitee.am.service.LoginAttemptService) FALSE(java.lang.Boolean.FALSE) JWTParser(io.gravitee.am.jwt.JWTParser) StandardClaims(io.gravitee.am.common.oidc.StandardClaims) Optional.ofNullable(java.util.Optional.ofNullable) ResetPasswordResponse(io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse) EventType(io.gravitee.am.common.audit.EventType) Predicate(io.reactivex.functions.Predicate) RandomString(io.gravitee.am.common.utils.RandomString) io.gravitee.am.model(io.gravitee.am.model) TokenService(io.gravitee.am.service.TokenService) LoginAttemptCriteria(io.gravitee.am.repository.management.api.search.LoginAttemptCriteria) Collectors.toList(java.util.stream.Collectors.toList) UserToken(io.gravitee.am.gateway.handler.root.service.user.model.UserToken) UserAuditBuilder(io.gravitee.am.service.reporter.builder.management.UserAuditBuilder) EmailValidator(io.gravitee.am.service.validators.email.EmailValidator) ExpiredJWTException(io.gravitee.am.common.exception.jwt.ExpiredJWTException) UserValidator(io.gravitee.am.service.validators.user.UserValidator) Entry(java.util.Map.Entry) RegistrationResponse(io.gravitee.am.gateway.handler.root.service.response.RegistrationResponse) Objects.nonNull(java.util.Objects.nonNull) AccountSettings(io.gravitee.am.model.account.AccountSettings) StringUtils(org.springframework.util.StringUtils) ResetPasswordResponse(io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse) LoginAttemptCriteria(io.gravitee.am.repository.management.api.search.LoginAttemptCriteria) AccountInactiveException(io.gravitee.am.common.exception.authentication.AccountInactiveException)

Aggregations

ResetPasswordResponse (io.gravitee.am.gateway.handler.root.service.response.ResetPasswordResponse)4 Client (io.gravitee.am.model.oidc.Client)4 User (io.gravitee.am.model.User)3 Test (org.junit.Test)2 Strings (com.google.common.base.Strings)1 EventType (io.gravitee.am.common.audit.EventType)1 AccountInactiveException (io.gravitee.am.common.exception.authentication.AccountInactiveException)1 ExpiredJWTException (io.gravitee.am.common.exception.jwt.ExpiredJWTException)1 StandardClaims (io.gravitee.am.common.oidc.StandardClaims)1 ConstantKeys (io.gravitee.am.common.utils.ConstantKeys)1 RandomString (io.gravitee.am.common.utils.RandomString)1 IdentityProviderManager (io.gravitee.am.gateway.handler.common.auth.idp.IdentityProviderManager)1 ClientSyncService (io.gravitee.am.gateway.handler.common.client.ClientSyncService)1 EmailService (io.gravitee.am.gateway.handler.common.email.EmailService)1 JWTService (io.gravitee.am.gateway.handler.common.jwt.JWTService)1 RegistrationResponse (io.gravitee.am.gateway.handler.root.service.response.RegistrationResponse)1 UserService (io.gravitee.am.gateway.handler.root.service.user.UserService)1 ForgotPasswordParameters (io.gravitee.am.gateway.handler.root.service.user.model.ForgotPasswordParameters)1 UserToken (io.gravitee.am.gateway.handler.root.service.user.model.UserToken)1 DefaultUser (io.gravitee.am.identityprovider.api.DefaultUser)1