Search in sources :

Example 6 with ServiceException

use of com.nexblocks.authguard.service.exceptions.ServiceException in project AuthGuard by AuthGuard.

the class VerificationServiceImpl method verifyEmail.

@Override
public void verifyEmail(final String verificationToken) {
    final AccountTokenDO accountToken = accountTokensRepository.getByToken(verificationToken).join().orElseThrow(() -> new ServiceNotFoundException(ErrorCode.TOKEN_EXPIRED_OR_DOES_NOT_EXIST, "AccountDO token " + verificationToken + " does not exist"));
    if (accountToken.getExpiresAt().isBefore(OffsetDateTime.now())) {
        throw new ServiceException(ErrorCode.EXPIRED_TOKEN, "Token " + verificationToken + " has expired");
    }
    final String verifiedEmail = Optional.ofNullable(accountToken.getAdditionalInformation()).map(additional -> additional.get(TARGET_EMAIL_PROPERTY)).orElseThrow(() -> new ServiceException(ErrorCode.INVALID_TOKEN, "Invalid account token: no valid additional information"));
    final AccountBO account = accountsService.getById(accountToken.getAssociatedAccountId()).orElseThrow(() -> new ServiceNotFoundException(ErrorCode.ACCOUNT_DOES_NOT_EXIST, "AccountDO " + accountToken.getAssociatedAccountId() + " does not exist"));
    final AccountBO updated;
    if (verifiedEmail.equals(account.getEmail().getEmail())) {
        updated = account.withEmail(account.getEmail().withVerified(true));
    } else if (verifiedEmail.equals(account.getBackupEmail().getEmail())) {
        updated = account.withBackupEmail(account.getBackupEmail().withVerified(true));
    } else {
        throw new ServiceException(ErrorCode.INVALID_TOKEN, "Account " + account.getId() + " does not contain the " + "email associated with the verification token");
    }
    accountsService.update(updated);
}
Also used : ErrorCode(com.nexblocks.authguard.service.exceptions.codes.ErrorCode) OffsetDateTime(java.time.OffsetDateTime) AccountsService(com.nexblocks.authguard.service.AccountsService) AccountBO(com.nexblocks.authguard.service.model.AccountBO) Inject(com.google.inject.Inject) ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) Optional(java.util.Optional) AccountTokensRepository(com.nexblocks.authguard.dal.cache.AccountTokensRepository) ServiceNotFoundException(com.nexblocks.authguard.service.exceptions.ServiceNotFoundException) AccountTokenDO(com.nexblocks.authguard.dal.model.AccountTokenDO) VerificationService(com.nexblocks.authguard.service.VerificationService) AccountBO(com.nexblocks.authguard.service.model.AccountBO) ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) AccountTokenDO(com.nexblocks.authguard.dal.model.AccountTokenDO) ServiceNotFoundException(com.nexblocks.authguard.service.exceptions.ServiceNotFoundException)

Example 7 with ServiceException

use of com.nexblocks.authguard.service.exceptions.ServiceException in project AuthGuard by AuthGuard.

the class ActionTokensRoute method createToken.

@Override
public void createToken(final Context context) {
    final ActionTokenRequestDTO request = actionTokenRequestBodyHandler.getValidated(context);
    final Try<ActionTokenBO> result;
    if (request.getType() == ActionTokenRequestType.OTP) {
        result = actionTokenService.generateFromOtp(request.getOtp().getPasswordId(), request.getOtp().getPassword(), request.getAction());
    } else {
        final AuthRequestBO authRequest = restMapper.toBO(request.getBasic());
        result = actionTokenService.generateFromBasicAuth(authRequest, request.getAction());
    }
    if (result.isFailure()) {
        throw (ServiceException) result.getCause();
    }
    context.status(201).json(restMapper.toDTO(result.get()));
}
Also used : ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) ActionTokenRequestDTO(com.nexblocks.authguard.api.dto.requests.ActionTokenRequestDTO) ActionTokenBO(com.nexblocks.authguard.service.model.ActionTokenBO) AuthRequestBO(com.nexblocks.authguard.service.model.AuthRequestBO)

Example 8 with ServiceException

use of com.nexblocks.authguard.service.exceptions.ServiceException in project AuthGuard by AuthGuard.

the class OAuthService method exchangeAuthorizationCode.

/**
 * Exchanges an authorization code with OAuth tokens. It'll verify that
 * a session containing that state exists before performing the exchange.
 * If the state has expired or no record of it existed then the future
 * will complete with {@link ServiceAuthorizationException}.
 *
 * @param provider The name of a provider as stated in the configuration.
 * @param state The state the identity provider returned.
 * @param authorizationCode The authorization code generated by the identity provider.
 */
public CompletableFuture<TokensResponse> exchangeAuthorizationCode(final String provider, final String state, final String authorizationCode) {
    final OAuthServiceClient client = Optional.ofNullable(providersClients.get(provider)).orElseThrow(() -> new ServiceException(ErrorCode.GENERIC_AUTH_FAILURE, "Invalid identity provider"));
    return CompletableFuture.supplyAsync(() -> sessionsService.getByToken(state)).thenCompose(sessionOptional -> sessionOptional.map(session -> doExchange(client, authorizationCode, session)).orElseThrow(() -> new ServiceAuthorizationException(ErrorCode.TOKEN_EXPIRED_OR_DOES_NOT_EXIST, "The provided state is either invalid or has expired"))).thenApply(tokensResponse -> {
        if (client.getConfiguration().isAccountProvider()) {
            if (tokensResponse.getIdToken() == null) {
                LOG.warn("Provider {} was set as an account provider but no ID was found in the response", provider);
            } else {
                final AccountBO account = getOrCreateAccount(client, authorizationCode, tokensResponse.getIdToken());
                tokensResponse.setAccountId(account.getId());
            }
        }
        return tokensResponse;
    });
}
Also used : JWT(com.auth0.jwt.JWT) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) RequestContextBO(com.nexblocks.authguard.service.model.RequestContextBO) ImmutableOAuthConfiguration(com.nexblocks.authguard.jwt.oauth.config.ImmutableOAuthConfiguration) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) CompletableFuture(java.util.concurrent.CompletableFuture) SessionBO(com.nexblocks.authguard.service.model.SessionBO) AccountsService(com.nexblocks.authguard.service.AccountsService) Duration(java.time.Duration) Map(java.util.Map) ResponseType(com.nexblocks.authguard.jwt.oauth.ResponseType) Claim(com.auth0.jwt.interfaces.Claim) SessionsService(com.nexblocks.authguard.service.SessionsService) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) ErrorCode(com.nexblocks.authguard.service.exceptions.codes.ErrorCode) Logger(org.slf4j.Logger) AccountBO(com.nexblocks.authguard.service.model.AccountBO) ImmutableOAuthClientConfiguration(com.nexblocks.authguard.jwt.oauth.config.ImmutableOAuthClientConfiguration) TokensResponse(com.nexblocks.authguard.jwt.oauth.TokensResponse) AccountEmailBO(com.nexblocks.authguard.service.model.AccountEmailBO) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) Try(io.vavr.control.Try) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) OAuthServiceClient(com.nexblocks.authguard.jwt.oauth.OAuthServiceClient) Optional(java.util.Optional) ConfigContext(com.nexblocks.authguard.config.ConfigContext) Named(com.google.inject.name.Named) AccountBO(com.nexblocks.authguard.service.model.AccountBO) ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) OAuthServiceClient(com.nexblocks.authguard.jwt.oauth.OAuthServiceClient) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)

Example 9 with ServiceException

use of com.nexblocks.authguard.service.exceptions.ServiceException in project AuthGuard by AuthGuard.

the class ExceptionHandlers method completionException.

// NOTE: this will go away when we move to async services
public static void completionException(final CompletionException e, final Context context) {
    final Throwable cause = e.getCause();
    if (cause == null) {
        LOG.error("A CompletionException was thrown without a cause", e);
        context.status(500).json(new Error("UNKNOWN", "An unknown error occurred"));
    } else if (cause instanceof ServiceAuthorizationException) {
        serviceAuthorizationException((ServiceAuthorizationException) cause, context);
    } else if (cause instanceof ServiceConflictException) {
        serviceConflictException((ServiceConflictException) cause, context);
    } else if (cause instanceof ServiceException) {
        serviceException((ServiceException) cause, context);
    } else if (cause instanceof RuntimeJsonException) {
        jsonMappingException((RuntimeJsonException) cause, context);
    } else if (cause instanceof RequestValidationException) {
        requestValidationException((RequestValidationException) cause, context);
    } else if (cause instanceof IdempotencyException) {
        idempotencyException((IdempotencyException) cause, context);
    } else if (cause instanceof TimeoutException) {
        timeoutException((TimeoutException) cause, context);
    } else {
        LOG.error("An unexpected exception was thrown", cause);
        context.status(500).json(new Error("UNKNOWN", "An unknown error occurred"));
    }
}
Also used : ServiceConflictException(com.nexblocks.authguard.service.exceptions.ServiceConflictException) ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) IdempotencyException(com.nexblocks.authguard.service.exceptions.IdempotencyException) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) Error(com.nexblocks.authguard.api.dto.entities.Error) RequestValidationError(com.nexblocks.authguard.api.dto.entities.RequestValidationError) TimeoutException(java.util.concurrent.TimeoutException)

Example 10 with ServiceException

use of com.nexblocks.authguard.service.exceptions.ServiceException in project AuthGuard by AuthGuard.

the class ActionTokenServiceImplTest method verifyTokenExpired.

@Test
void verifyTokenExpired() {
    final AccountTokenDO accountToken = AccountTokenDO.builder().expiresAt(OffsetDateTime.now().minusMinutes(1)).additionalInformation(ImmutableMap.of("action", "something")).build();
    Mockito.when(accountTokensRepository.getByToken("action-token")).thenReturn(CompletableFuture.completedFuture(Optional.of(accountToken)));
    final Try<ActionTokenBO> actual = actionTokenService.verifyToken("action-token", "something");
    assertThat(actual.isFailure());
    assertThat(((ServiceException) actual.getCause()).getErrorCode()).isEqualTo(ErrorCode.EXPIRED_TOKEN.getCode());
}
Also used : ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) AccountTokenDO(com.nexblocks.authguard.dal.model.AccountTokenDO) ActionTokenBO(com.nexblocks.authguard.service.model.ActionTokenBO) Test(org.junit.jupiter.api.Test)

Aggregations

ServiceException (com.nexblocks.authguard.service.exceptions.ServiceException)17 AccountTokenDO (com.nexblocks.authguard.dal.model.AccountTokenDO)8 ServiceNotFoundException (com.nexblocks.authguard.service.exceptions.ServiceNotFoundException)6 OffsetDateTime (java.time.OffsetDateTime)6 Inject (com.google.inject.Inject)5 AccountsService (com.nexblocks.authguard.service.AccountsService)5 ErrorCode (com.nexblocks.authguard.service.exceptions.codes.ErrorCode)5 Optional (java.util.Optional)5 Collectors (java.util.stream.Collectors)4 AccountTokensRepository (com.nexblocks.authguard.dal.cache.AccountTokensRepository)3 MessageBus (com.nexblocks.authguard.emb.MessageBus)3 Messages (com.nexblocks.authguard.emb.Messages)3 IdempotencyService (com.nexblocks.authguard.service.IdempotencyService)3 ServiceAuthorizationException (com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)3 ServiceConflictException (com.nexblocks.authguard.service.exceptions.ServiceConflictException)3 ActionTokenBO (com.nexblocks.authguard.service.model.ActionTokenBO)3 Duration (java.time.Duration)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 Named (com.google.inject.name.Named)2 com.nexblocks.authguard.basic.passwords (com.nexblocks.authguard.basic.passwords)2