Search in sources :

Example 1 with UserNotFoundException

use of io.gravitee.am.service.exception.UserNotFoundException in project gravitee-access-management by gravitee-io.

the class LogoutCallbackEndpoint method restoreCurrentSession.

/**
 * Restore current session (user and application) to properly sign out the user.
 *
 * @param routingContext the routing context
 * @param handler handler holding the potential current session
 */
private void restoreCurrentSession(RoutingContext routingContext, Handler<AsyncResult<UserToken>> handler) {
    // The OP SHOULD accept ID Tokens when the RP identified by the ID Token's aud claim and/or sid claim has a current session
    // or had a recent session at the OP, even when the exp time has passed.
    final MultiMap originalLogoutQueryParams = routingContext.get(ConstantKeys.PARAM_CONTEXT_KEY);
    if (originalLogoutQueryParams != null && originalLogoutQueryParams.contains(ConstantKeys.ID_TOKEN_HINT_KEY)) {
        final String idToken = originalLogoutQueryParams.get(ConstantKeys.ID_TOKEN_HINT_KEY);
        userService.extractSessionFromIdToken(idToken).map(userToken -> {
            // check if the user ids match
            if (userToken.getUser() != null && routingContext.user() != null) {
                User endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) routingContext.user().getDelegate()).getUser();
                if (!userToken.getUser().getId().equals(endUser.getId())) {
                    throw new UserNotFoundException(userToken.getUser().getId());
                }
            }
            return userToken;
        }).subscribe(currentSession -> handler.handle(Future.succeededFuture(currentSession)), error -> handler.handle(Future.succeededFuture(new UserToken())));
        return;
    }
    if (routingContext.get(Parameters.CLIENT_ID) == null) {
        logger.error("Unable to restore client for logout callback");
        handler.handle(Future.failedFuture(new InvalidRequestException("Invalid state")));
        return;
    }
    final User endUser = routingContext.user() != null ? ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) routingContext.user().getDelegate()).getUser() : null;
    final String clientId = routingContext.get(Parameters.CLIENT_ID);
    clientSyncService.findByClientId(clientId).subscribe(client -> handler.handle(Future.succeededFuture(new UserToken(endUser, client))), ex -> {
        logger.error("An error has occurred when getting client {}", clientId, ex);
        handler.handle(Future.failedFuture(new BadClientCredentialsException()));
    }, () -> {
        logger.error("Unknown client {}", clientId);
        handler.handle(Future.failedFuture(new BadClientCredentialsException()));
    });
}
Also used : BadClientCredentialsException(io.gravitee.am.common.exception.oauth2.BadClientCredentialsException) AuthenticationFlowContextService(io.gravitee.am.service.AuthenticationFlowContextService) RequestUtils(io.gravitee.am.gateway.handler.common.vertx.utils.RequestUtils) Logger(org.slf4j.Logger) HttpServerRequest(io.vertx.reactivex.core.http.HttpServerRequest) Client(io.gravitee.am.model.oidc.Client) CertificateManager(io.gravitee.am.gateway.handler.common.certificate.CertificateManager) LoggerFactory(org.slf4j.LoggerFactory) UserService(io.gravitee.am.gateway.handler.root.service.user.UserService) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) Domain(io.gravitee.am.model.Domain) Future(io.vertx.core.Future) RoutingContext(io.vertx.reactivex.ext.web.RoutingContext) UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) MultiMap(io.vertx.reactivex.core.MultiMap) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) UserToken(io.gravitee.am.gateway.handler.root.service.user.model.UserToken) JWTService(io.gravitee.am.gateway.handler.common.jwt.JWTService) ClientSyncService(io.gravitee.am.gateway.handler.common.client.ClientSyncService) AsyncResult(io.vertx.core.AsyncResult) User(io.gravitee.am.model.User) Handler(io.vertx.core.Handler) Parameters(io.gravitee.am.common.oauth2.Parameters) StringUtils(org.springframework.util.StringUtils) UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) User(io.gravitee.am.model.User) MultiMap(io.vertx.reactivex.core.MultiMap) BadClientCredentialsException(io.gravitee.am.common.exception.oauth2.BadClientCredentialsException) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) UserToken(io.gravitee.am.gateway.handler.root.service.user.model.UserToken)

Example 2 with UserNotFoundException

use of io.gravitee.am.service.exception.UserNotFoundException in project gravitee-access-management by gravitee-io.

the class LogoutEndpoint method restoreCurrentSession.

/**
 * Restore current session (user and application) to properly sign out the user.
 *
 * @param routingContext the routing context
 * @param handler handler holding the potential current session
 */
private void restoreCurrentSession(RoutingContext routingContext, Handler<AsyncResult<UserToken>> handler) {
    // The OP SHOULD accept ID Tokens when the RP identified by the ID Token's aud claim and/or sid claim has a current session
    // or had a recent session at the OP, even when the exp time has passed.
    final String idToken = routingContext.request().getParam(Parameters.ID_TOKEN_HINT);
    if (!StringUtils.isEmpty(idToken)) {
        userService.extractSessionFromIdToken(idToken).map(userToken -> {
            // check if the user ids match
            if (userToken.getUser() != null && routingContext.user() != null) {
                User endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) routingContext.user().getDelegate()).getUser();
                if (!userToken.getUser().getId().equals(endUser.getId())) {
                    throw new UserNotFoundException(userToken.getUser().getId());
                }
            }
            return userToken;
        }).subscribe(currentSession -> handler.handle(Future.succeededFuture(currentSession)), error -> handler.handle(Future.succeededFuture(new UserToken())));
        return;
    }
    // if no user, continue
    if (routingContext.user() == null) {
        handler.handle(Future.succeededFuture(new UserToken()));
        return;
    }
    // get client from the user's last application
    final io.gravitee.am.model.User endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) routingContext.user().getDelegate()).getUser();
    // whatever is the client search result, we have to return a UserToken with
    // at least the user to manage properly the user's logout information
    clientSyncService.findById(endUser.getClient()).switchIfEmpty(Maybe.defer(() -> clientSyncService.findByClientId(endUser.getClient()))).subscribe(client -> handler.handle(Future.succeededFuture(new UserToken(endUser, client, null))), error -> handler.handle(Future.succeededFuture(new UserToken(endUser, null, null))), () -> handler.handle(Future.succeededFuture(new UserToken(endUser, null, null))));
}
Also used : Client(io.gravitee.am.model.oidc.Client) Authentication(io.gravitee.am.identityprovider.api.Authentication) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) IdentityProviderManager(io.gravitee.am.gateway.handler.common.auth.idp.IdentityProviderManager) UserService(io.gravitee.am.gateway.handler.root.service.user.UserService) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) JWTService(io.gravitee.am.gateway.handler.common.jwt.JWTService) ClientSyncService(io.gravitee.am.gateway.handler.common.client.ClientSyncService) AsyncResult(io.vertx.core.AsyncResult) User(io.gravitee.am.model.User) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) SocialAuthenticationProvider(io.gravitee.am.identityprovider.api.social.SocialAuthenticationProvider) UriBuilder(io.gravitee.am.common.web.UriBuilder) AuthenticationFlowContextService(io.gravitee.am.service.AuthenticationFlowContextService) RequestUtils(io.gravitee.am.gateway.handler.common.vertx.utils.RequestUtils) Logger(org.slf4j.Logger) HttpServerRequest(io.vertx.reactivex.core.http.HttpServerRequest) JWT(io.gravitee.am.common.jwt.JWT) CertificateManager(io.gravitee.am.gateway.handler.common.certificate.CertificateManager) Request(io.gravitee.am.identityprovider.api.common.Request) Domain(io.gravitee.am.model.Domain) VertxHttpServerRequest(io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerRequest) Future(io.vertx.core.Future) RoutingContext(io.vertx.reactivex.ext.web.RoutingContext) WebClient(io.vertx.reactivex.ext.web.client.WebClient) UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) UriBuilderRequest(io.gravitee.am.gateway.handler.common.vertx.utils.UriBuilderRequest) MultiMap(io.vertx.reactivex.core.MultiMap) UserToken(io.gravitee.am.gateway.handler.root.service.user.model.UserToken) Parameters(io.gravitee.am.common.oidc.Parameters) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) CONTEXT_PATH(io.gravitee.am.gateway.handler.common.vertx.utils.UriBuilderRequest.CONTEXT_PATH) Handler(io.vertx.core.Handler) StringUtils(org.springframework.util.StringUtils) UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) User(io.gravitee.am.model.User) User(io.gravitee.am.model.User) UserToken(io.gravitee.am.gateway.handler.root.service.user.model.UserToken)

Example 3 with UserNotFoundException

use of io.gravitee.am.service.exception.UserNotFoundException in project gravitee-access-management by gravitee-io.

the class ForgotPasswordSubmissionEndpoint method handle.

@Override
public void handle(RoutingContext context) {
    final String email = context.request().getParam(ConstantKeys.EMAIL_PARAM_KEY);
    final String username = context.request().getParam(ConstantKeys.USERNAME_PARAM_KEY);
    final Client client = context.get(ConstantKeys.CLIENT_CONTEXT_KEY);
    MultiMap queryParams = RequestUtils.getCleanedQueryParams(context.request());
    AccountSettings settings = AccountSettings.getInstance(domain, client);
    final ForgotPasswordParameters parameters = new ForgotPasswordParameters(email, username, settings != null && settings.isResetPasswordCustomForm(), settings != null && settings.isResetPasswordConfirmIdentity());
    userService.forgotPassword(parameters, client, getAuthenticatedUser(context)).subscribe(() -> {
        queryParams.set(ConstantKeys.SUCCESS_PARAM_KEY, "forgot_password_completed");
        redirectToPage(context, queryParams);
    }, error -> {
        // the actual error continue to be stored in the audit logs
        if (error instanceof UserNotFoundException || error instanceof AccountStatusException) {
            queryParams.set(ConstantKeys.SUCCESS_PARAM_KEY, "forgot_password_completed");
            redirectToPage(context, queryParams);
        } else if (error instanceof EnforceUserIdentityException) {
            if (settings.isResetPasswordConfirmIdentity()) {
                queryParams.set(ConstantKeys.WARNING_PARAM_KEY, FORGOT_PASSWORD_CONFIRM);
            } else {
                queryParams.set(ConstantKeys.SUCCESS_PARAM_KEY, "forgot_password_completed");
            }
            redirectToPage(context, queryParams);
        } else {
            queryParams.set(ConstantKeys.ERROR_PARAM_KEY, "forgot_password_failed");
            redirectToPage(context, queryParams, error);
        }
    });
}
Also used : AccountSettings(io.gravitee.am.model.account.AccountSettings) UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) AccountStatusException(io.gravitee.am.common.exception.authentication.AccountStatusException) MultiMap(io.vertx.reactivex.core.MultiMap) EnforceUserIdentityException(io.gravitee.am.service.exception.EnforceUserIdentityException) Client(io.gravitee.am.model.oidc.Client) ForgotPasswordParameters(io.gravitee.am.gateway.handler.root.service.user.model.ForgotPasswordParameters)

Example 4 with UserNotFoundException

use of io.gravitee.am.service.exception.UserNotFoundException in project gravitee-access-management by gravitee-io.

the class UserAuthenticationServiceImpl method loadPreAuthenticatedUser.

@Override
public Maybe<User> loadPreAuthenticatedUser(String subject, Request request) {
    // find user by its technical id
    return userService.findById(subject).switchIfEmpty(Maybe.error(new UserNotFoundException(subject))).flatMap(user -> isIndefinitelyLocked(user) ? Maybe.error(new AccountLockedException("User " + user.getUsername() + " is locked")) : Maybe.just(user)).flatMap(user -> identityProviderManager.get(user.getSource()).flatMap(authenticationProvider -> {
        SimpleAuthenticationContext authenticationContext = new SimpleAuthenticationContext(request);
        final Authentication authentication = new EndUserAuthentication(user, null, authenticationContext);
        return authenticationProvider.loadPreAuthenticatedUser(authentication);
    }).flatMap(idpUser -> {
        // retrieve information from the idp user and update the user
        Map<String, Object> additionalInformation = idpUser.getAdditionalInformation() == null ? new HashMap<>() : new HashMap<>(idpUser.getAdditionalInformation());
        additionalInformation.put(SOURCE_FIELD, user.getSource());
        additionalInformation.put(Parameters.CLIENT_ID, user.getClient());
        ((DefaultUser) idpUser).setAdditionalInformation(additionalInformation);
        return update(user, idpUser, false).flatMap(userService::enhance).toMaybe();
    }).switchIfEmpty(Maybe.defer(() -> userService.enhance(user).toMaybe())));
}
Also used : UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) Claims(io.gravitee.am.common.oidc.idtoken.Claims) Client(io.gravitee.am.model.oidc.Client) Date(java.util.Date) Completable(io.reactivex.Completable) Authentication(io.gravitee.am.identityprovider.api.Authentication) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) IdentityProviderManager(io.gravitee.am.gateway.handler.common.auth.idp.IdentityProviderManager) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) EmailService(io.gravitee.am.gateway.handler.common.email.EmailService) AuditService(io.gravitee.am.service.AuditService) Single(io.reactivex.Single) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) UserAuthenticationService(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationService) Request(io.gravitee.gateway.api.Request) AuditBuilder(io.gravitee.am.service.reporter.builder.AuditBuilder) Map(java.util.Map) ReferenceType(io.gravitee.am.model.ReferenceType) User(io.gravitee.am.model.User) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) StandardClaims(io.gravitee.am.common.oidc.StandardClaims) Logger(org.slf4j.Logger) AccountDisabledException(io.gravitee.am.common.exception.authentication.AccountDisabledException) Optional.ofNullable(java.util.Optional.ofNullable) Domain(io.gravitee.am.model.Domain) EventType(io.gravitee.am.common.audit.EventType) OIDC_PROVIDER_ID_ACCESS_TOKEN_KEY(io.gravitee.am.common.utils.ConstantKeys.OIDC_PROVIDER_ID_ACCESS_TOKEN_KEY) UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) LoginAttemptCriteria(io.gravitee.am.repository.management.api.search.LoginAttemptCriteria) UserAuditBuilder(io.gravitee.am.service.reporter.builder.management.UserAuditBuilder) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) UserService(io.gravitee.am.gateway.handler.common.user.UserService) Template(io.gravitee.am.model.Template) AccountLockedException(io.gravitee.am.common.exception.authentication.AccountLockedException) OIDC_PROVIDER_ID_TOKEN_KEY(io.gravitee.am.common.utils.ConstantKeys.OIDC_PROVIDER_ID_TOKEN_KEY) Parameters(io.gravitee.am.common.oauth2.Parameters) AccountSettings(io.gravitee.am.model.account.AccountSettings) AccountLockedException(io.gravitee.am.common.exception.authentication.AccountLockedException) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) Authentication(io.gravitee.am.identityprovider.api.Authentication) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication)

Example 5 with UserNotFoundException

use of io.gravitee.am.service.exception.UserNotFoundException in project gravitee-access-management by gravitee-io.

the class AccountEndpointHandler method getUser.

public void getUser(RoutingContext routingContext) {
    JWT token = routingContext.get(ConstantKeys.TOKEN_CONTEXT_KEY);
    accountService.get(token.getSub()).subscribe(user -> {
        routingContext.put(ConstantKeys.USER_CONTEXT_KEY, user);
        routingContext.next();
    }, error -> {
        LOGGER.error("Unable to retrieve user for Id {}", token.getSub());
        routingContext.fail(error);
    }, () -> routingContext.fail(new UserNotFoundException(token.getSub())));
}
Also used : UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) JWT(io.gravitee.am.common.jwt.JWT)

Aggregations

UserNotFoundException (io.gravitee.am.service.exception.UserNotFoundException)12 Maybe (io.reactivex.Maybe)6 ReferenceType (io.gravitee.am.model.ReferenceType)5 User (io.gravitee.am.model.User)5 Completable (io.reactivex.Completable)5 Single (io.reactivex.Single)5 Autowired (org.springframework.beans.factory.annotation.Autowired)5 Client (io.gravitee.am.model.oidc.Client)4 AuditService (io.gravitee.am.service.AuditService)4 AuditBuilder (io.gravitee.am.service.reporter.builder.AuditBuilder)4 EventType (io.gravitee.am.common.audit.EventType)3 UserService (io.gravitee.am.gateway.handler.root.service.user.UserService)3 DefaultUser (io.gravitee.am.identityprovider.api.DefaultUser)3 SimpleAuthenticationContext (io.gravitee.am.identityprovider.api.SimpleAuthenticationContext)3 Domain (io.gravitee.am.model.Domain)3 EnrolledFactor (io.gravitee.am.model.factor.EnrolledFactor)3 MultiMap (io.vertx.reactivex.core.MultiMap)3 Collectors (java.util.stream.Collectors)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3