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);
}
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()));
}
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;
});
}
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"));
}
}
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());
}
Aggregations