Search in sources :

Example 36 with AccountBO

use of com.nexblocks.authguard.service.model.AccountBO in project AuthGuard by AuthGuard.

the class SmsPasswordlessSubscriberTest method onValidMessageNoPhoneNumber.

@Test
void onValidMessageNoPhoneNumber() {
    final AccountTokenDO accountToken = AccountTokenDO.builder().token("token").build();
    final AccountBO account = AccountBO.builder().build();
    final PasswordlessMessageBody messageBody = new PasswordlessMessageBody(accountToken, account);
    final Message message = Messages.passwordlessGenerated(messageBody);
    smsPasswordlessSubscriber.onMessage(message);
    Mockito.verify(smsProvider, Mockito.never()).send(Mockito.any());
}
Also used : AccountBO(com.nexblocks.authguard.service.model.AccountBO) ImmutableTextMessage(com.nexblocks.authguard.external.sms.ImmutableTextMessage) Message(com.nexblocks.authguard.emb.model.Message) AccountTokenDO(com.nexblocks.authguard.dal.model.AccountTokenDO) PasswordlessMessageBody(com.nexblocks.authguard.basic.passwordless.PasswordlessMessageBody) Test(org.junit.jupiter.api.Test)

Example 37 with AccountBO

use of com.nexblocks.authguard.service.model.AccountBO 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 38 with AccountBO

use of com.nexblocks.authguard.service.model.AccountBO in project AuthGuard by AuthGuard.

the class OAuthService method getOrCreateAccount.

private AccountBO getOrCreateAccount(final OAuthServiceClient serviceClient, final String authorizationCode, final String idToken) {
    final ImmutableOAuthClientConfiguration configuration = serviceClient.getConfiguration();
    final DecodedJWT decoded = JWT.decode(idToken);
    final String externalId = decoded.getSubject();
    final Optional<AccountBO> account = accountsService.getByExternalId(externalId);
    if (account.isPresent()) {
        return account.get();
    }
    final AccountBO.Builder newAccount = AccountBO.builder().externalId(externalId).social(true).identityProvider(configuration.getProvider());
    if (configuration.getEmailField() != null) {
        final Claim emailClaim = decoded.getClaim(configuration.getEmailField());
        if (!emailClaim.isNull()) {
            newAccount.email(AccountEmailBO.builder().email(emailClaim.asString()).build());
        }
    }
    final RequestContextBO requestContext = RequestContextBO.builder().source(configuration.getProvider()).idempotentKey(authorizationCode).build();
    return accountsService.create(newAccount.build(), requestContext);
}
Also used : AccountBO(com.nexblocks.authguard.service.model.AccountBO) RequestContextBO(com.nexblocks.authguard.service.model.RequestContextBO) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim) ImmutableOAuthClientConfiguration(com.nexblocks.authguard.jwt.oauth.config.ImmutableOAuthClientConfiguration)

Example 39 with AccountBO

use of com.nexblocks.authguard.service.model.AccountBO in project AuthGuard by AuthGuard.

the class IdTokenProviderTest method generateEncrypted.

@Test
void generateEncrypted() {
    final IdTokenProvider idTokenProvider = newProviderInstance(jwtConfigWithEncryption());
    Mockito.when(tokenEncryptor.encryptAndEncode(Mockito.any())).thenAnswer(invocation -> Either.right("encrypted"));
    final AccountBO account = RANDOM.nextObject(AccountBO.class).withActive(true);
    final AuthResponseBO tokens = idTokenProvider.generateToken(account);
    assertThat(tokens).isNotNull();
    assertThat(tokens.getToken()).isEqualTo("encrypted");
    assertThat(tokens.getRefreshToken()).isNotNull();
    assertThat(tokens.getToken()).isNotEqualTo(tokens.getRefreshToken());
}
Also used : AccountBO(com.nexblocks.authguard.service.model.AccountBO) AuthResponseBO(com.nexblocks.authguard.service.model.AuthResponseBO) Test(org.junit.jupiter.api.Test)

Example 40 with AccountBO

use of com.nexblocks.authguard.service.model.AccountBO in project AuthGuard by AuthGuard.

the class JwtPermissionsMapperTest method map.

@Test
void map() {
    final AccountBO account = AccountBO.builder().permissions(Arrays.asList(PermissionBO.builder().group("test").name("read").build(), PermissionBO.builder().group("test").name("write").build(), PermissionBO.builder().group("test").name("nothing").build())).build();
    final TokenRestrictionsBO restrictions = TokenRestrictionsBO.builder().addPermissions("test:read", "test:nothing").build();
    final String[] expected = new String[] { "test:read", "test:nothing" };
    final String[] actual = JwtPermissionsMapper.map(account, restrictions);
    assertThat(Arrays.asList(actual)).isEqualTo(Arrays.asList(expected));
}
Also used : AccountBO(com.nexblocks.authguard.service.model.AccountBO) TokenRestrictionsBO(com.nexblocks.authguard.service.model.TokenRestrictionsBO) Test(org.junit.jupiter.api.Test)

Aggregations

AccountBO (com.nexblocks.authguard.service.model.AccountBO)55 Test (org.junit.jupiter.api.Test)43 AccountTokenDO (com.nexblocks.authguard.dal.model.AccountTokenDO)21 Message (com.nexblocks.authguard.emb.model.Message)15 AuthResponseBO (com.nexblocks.authguard.service.model.AuthResponseBO)15 OtpMessageBody (com.nexblocks.authguard.basic.otp.OtpMessageBody)8 PasswordlessMessageBody (com.nexblocks.authguard.basic.passwordless.PasswordlessMessageBody)8 OneTimePasswordBO (com.nexblocks.authguard.service.model.OneTimePasswordBO)8 ServiceAuthorizationException (com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)7 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)6 ImmutableTextMessage (com.nexblocks.authguard.external.sms.ImmutableTextMessage)6 RequestContextBO (com.nexblocks.authguard.service.model.RequestContextBO)6 ImmutableEmail (com.nexblocks.authguard.external.email.ImmutableEmail)5 JwtConfig (com.nexblocks.authguard.service.config.JwtConfig)5 StrategyConfig (com.nexblocks.authguard.service.config.StrategyConfig)5 ServiceException (com.nexblocks.authguard.service.exceptions.ServiceException)5 AuthRequestBO (com.nexblocks.authguard.service.model.AuthRequestBO)5 CreateAccountRequestDTO (com.nexblocks.authguard.api.dto.requests.CreateAccountRequestDTO)4 OtpConfig (com.nexblocks.authguard.basic.config.OtpConfig)4 CreateCompleteAccountRequestDTO (com.nexblocks.authguard.api.dto.requests.CreateCompleteAccountRequestDTO)3