Search in sources :

Example 1 with UserService

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

the class UserServiceImpl method confirmRegistration.

@Override
public Single<RegistrationResponse> confirmRegistration(Client client, User user, io.gravitee.am.identityprovider.api.User principal) {
    // user has completed his account, add it to the idp
    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 -> userProvider.update(idpUser.getId(), convert(user))).onErrorResumeNext(ex -> {
        if (ex instanceof UserNotFoundException) {
            // idp user not found, create its account
            return userProvider.create(convert(user));
        }
        return Single.error(ex);
    })).flatMap(idpUser -> {
        // update 'users' collection for management and audit purpose
        user.setPassword(null);
        user.setRegistrationCompleted(true);
        user.setEnabled(true);
        user.setExternalId(idpUser.getId());
        user.setUpdatedAt(new Date());
        // additional information
        extractAdditionalInformation(user, idpUser.getAdditionalInformation());
        // set login information
        AccountSettings accountSettings = AccountSettings.getInstance(domain, client);
        if (accountSettings != null && accountSettings.isAutoLoginAfterRegistration()) {
            user.setLoggedAt(new Date());
            user.setLoginsCount(1l);
        }
        return userService.update(user);
    }).flatMap(userService::enhance).map(user1 -> {
        AccountSettings accountSettings = AccountSettings.getInstance(domain, client);
        return new RegistrationResponse(user1, accountSettings != null ? accountSettings.getRedirectUriAfterRegistration() : null, accountSettings != null ? accountSettings.isAutoLoginAfterRegistration() : false);
    }).doOnSuccess(response -> auditService.report(AuditBuilder.builder(UserAuditBuilder.class).domain(domain.getId()).client(user.getClient()).principal(principal).type(EventType.REGISTRATION_CONFIRMATION))).doOnError(throwable -> auditService.report(AuditBuilder.builder(UserAuditBuilder.class).domain(domain.getId()).client(user.getClient()).principal(principal).type(EventType.REGISTRATION_CONFIRMATION).throwable(throwable)));
}
Also used : 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) AccountSettings(io.gravitee.am.model.account.AccountSettings) UserAuditBuilder(io.gravitee.am.service.reporter.builder.management.UserAuditBuilder) RegistrationResponse(io.gravitee.am.gateway.handler.root.service.response.RegistrationResponse)

Example 2 with UserService

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

the class EmailFactorProvider method generateCodeAndSendEmail.

private Completable generateCodeAndSendEmail(FactorContext context, EmailSenderProvider provider, EnrolledFactor enrolledFactor) {
    logger.debug("Generating factor code of {} digits", configuration.getReturnDigits());
    try {
        UserService userService = context.getComponent(UserService.class);
        EmailService emailService = context.getComponent(EmailService.class);
        // register mfa code to make it available into the TemplateEngine values
        Map<String, Object> params = context.getTemplateValues();
        params.put(FactorContext.KEY_CODE, generateOTP(enrolledFactor));
        final String recipient = enrolledFactor.getChannel().getTarget();
        EmailService.EmailWrapper emailWrapper = emailService.createEmail(Template.MFA_CHALLENGE, context.getClient(), asList(recipient), params);
        return provider.sendMessage(emailWrapper.getEmail()).andThen(Single.just(enrolledFactor).flatMap(ef -> {
            ef.setPrimary(true);
            ef.setStatus(FactorStatus.ACTIVATED);
            ef.getSecurity().putData(FactorDataKeys.KEY_EXPIRE_AT, emailWrapper.getExpireAt());
            return userService.addFactor(context.getUser().getId(), ef, new DefaultUser(context.getUser()));
        }).ignoreElement());
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        logger.error("Code generation fails", e);
        return Completable.error(new TechnicalException("Code can't be sent"));
    } catch (Exception e) {
        logger.error("Email templating fails", e);
        return Completable.error(new TechnicalException("Email can't be sent"));
    }
}
Also used : DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) TechnicalException(io.gravitee.am.repository.exceptions.TechnicalException) UserService(io.gravitee.am.gateway.handler.root.service.user.UserService) EmailService(io.gravitee.am.gateway.handler.common.email.EmailService) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) TechnicalException(io.gravitee.am.repository.exceptions.TechnicalException) AddressException(javax.mail.internet.AddressException) InvalidCodeException(io.gravitee.am.common.exception.mfa.InvalidCodeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 3 with UserService

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

the class RecoveryCodeFactorProvider method addRecoveryCodeFactor.

private Completable addRecoveryCodeFactor(FactorContext context, EnrolledFactor enrolledFactor) {
    try {
        final UserService userService = context.getComponent(UserService.class);
        enrolledFactor.setSecurity(createEnrolledFactorSecurity());
        return userService.addFactor(context.getUser().getId(), enrolledFactor, new DefaultUser(context.getUser())).ignoreElement();
    } catch (Exception ex) {
        return Completable.error(ex);
    }
}
Also used : DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) UserService(io.gravitee.am.gateway.handler.root.service.user.UserService) InvalidCodeException(io.gravitee.am.common.exception.mfa.InvalidCodeException)

Example 4 with UserService

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

the class MFARecoveryCodeEndpointTest method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    client = new Client();
    client.setClientId(UUID.randomUUID().toString());
    final User user = new User();
    setFactorsFor(user);
    mfaRecoveryCodeEndpoint = new MFARecoveryCodeEndpoint(templateEngine, domain, userService);
    router.route().handler(ctx -> {
        ctx.setUser(io.vertx.reactivex.ext.auth.User.newInstance(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(user)));
        ctx.put(ConstantKeys.CLIENT_CONTEXT_KEY, client);
        ctx.next();
    }).handler(BodyHandler.create());
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) java.util(java.util) Client(io.gravitee.am.model.oidc.Client) ThymeleafTemplateEngine(io.vertx.reactivex.ext.web.templ.thymeleaf.ThymeleafTemplateEngine) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) UserService(io.gravitee.am.gateway.handler.root.service.user.UserService) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) Domain(io.gravitee.am.model.Domain) Test(org.junit.Test) RoutingContext(io.vertx.reactivex.ext.web.RoutingContext) BodyHandler(io.vertx.reactivex.ext.web.handler.BodyHandler) EnrolledFactorSecurity(io.gravitee.am.model.factor.EnrolledFactorSecurity) Mockito(org.mockito.Mockito) RECOVERY_CODE(io.gravitee.am.common.factor.FactorSecurityType.RECOVERY_CODE) EnrolledFactor(io.gravitee.am.model.factor.EnrolledFactor) HttpMethod(io.vertx.core.http.HttpMethod) Mockito.doAnswer(org.mockito.Mockito.doAnswer) RxWebTestBase(io.gravitee.am.gateway.handler.common.vertx.RxWebTestBase) User(io.gravitee.am.model.User) Handler(io.vertx.core.Handler) Assert(org.junit.Assert) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) User(io.gravitee.am.model.User) Client(io.gravitee.am.model.oidc.Client)

Example 5 with UserService

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

the class EmailFactorProviderTest method shouldSendEmailAndGenerateCode.

@Test
public void shouldSendEmailAndGenerateCode() throws Exception {
    EmailSenderProvider smtpProvider = mock(EmailSenderProvider.class);
    when(resourceManager.getResourceProvider(any())).thenReturn(smtpProvider);
    Email template = new Email();
    template.setTemplate("mfa_challenge.html");
    template.setSubject("Some Subject");
    template.setExpiresAfter(600);
    io.gravitee.am.common.email.Email generatedEmail = new io.gravitee.am.common.email.Email();
    generatedEmail.setTo(new String[] { RECIPIENT });
    when(emailService.createEmail(any(), any(), any(), any())).thenReturn(new EmailService.EmailWrapper(generatedEmail));
    EnrolledFactor enrolled = new EnrolledFactor();
    enrolled.setUpdatedAt(new Date());
    Map<String, Object> additionalData = new Maps.MapBuilder(new HashMap()).put(FactorDataKeys.KEY_MOVING_FACTOR, 0).put(FactorDataKeys.KEY_EXPIRE_AT, System.currentTimeMillis() + 600).build();
    enrolled.setSecurity(new EnrolledFactorSecurity(FactorSecurityType.SHARED_SECRET, SHARED_SECRET, additionalData));
    enrolled.setChannel(new EnrolledFactorChannel(EnrolledFactorChannel.Type.EMAIL, RECIPIENT));
    when(factorContext.getData(FactorContext.KEY_ENROLLED_FACTOR, EnrolledFactor.class)).thenReturn(enrolled);
    when(factorContext.getTemplateValues()).thenReturn(new HashMap<>());
    User user = mock(User.class);
    when(user.getId()).thenReturn("id");
    when(factorContext.getUser()).thenReturn(user);
    when(userService.addFactor(any(), any(), any())).thenReturn(Single.just(user));
    when(smtpProvider.sendMessage(any())).thenReturn(Completable.complete());
    TestObserver<Void> test = cut.sendChallenge(factorContext).test();
    test.awaitTerminalEvent();
    test.assertNoValues();
    test.assertNoErrors();
    verify(smtpProvider).sendMessage(argThat(m -> m.getTo()[0].equals(RECIPIENT)));
    verify(userService).addFactor(any(), any(), any());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ResourceManager(io.gravitee.am.gateway.handler.manager.resource.ResourceManager) Mock(org.mockito.Mock) Date(java.util.Date) Completable(io.reactivex.Completable) RunWith(org.junit.runner.RunWith) UserService(io.gravitee.am.gateway.handler.root.service.user.UserService) HashMap(java.util.HashMap) EmailService(io.gravitee.am.gateway.handler.common.email.EmailService) Single(io.reactivex.Single) FactorSecurityType(io.gravitee.am.common.factor.FactorSecurityType) EnrolledFactorChannel(io.gravitee.am.model.factor.EnrolledFactorChannel) EnrolledFactor(io.gravitee.am.model.factor.EnrolledFactor) Map(java.util.Map) User(io.gravitee.am.model.User) Email(io.gravitee.am.model.Email) Before(org.junit.Before) InjectMocks(org.mockito.InjectMocks) TestObserver(io.reactivex.observers.TestObserver) Test(org.junit.Test) FactorDataKeys(io.gravitee.am.common.factor.FactorDataKeys) Maps(io.gravitee.common.util.Maps) EnrolledFactorSecurity(io.gravitee.am.model.factor.EnrolledFactorSecurity) Mockito(org.mockito.Mockito) InvalidCodeException(io.gravitee.am.common.exception.mfa.InvalidCodeException) EmailFactorConfiguration(io.gravitee.am.factor.email.EmailFactorConfiguration) FactorContext(io.gravitee.am.factor.api.FactorContext) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) EmailSenderProvider(io.gravitee.am.resource.api.email.EmailSenderProvider) Email(io.gravitee.am.model.Email) User(io.gravitee.am.model.User) HashMap(java.util.HashMap) EnrolledFactorChannel(io.gravitee.am.model.factor.EnrolledFactorChannel) Maps(io.gravitee.common.util.Maps) EmailSenderProvider(io.gravitee.am.resource.api.email.EmailSenderProvider) EnrolledFactor(io.gravitee.am.model.factor.EnrolledFactor) Date(java.util.Date) EmailService(io.gravitee.am.gateway.handler.common.email.EmailService) EnrolledFactorSecurity(io.gravitee.am.model.factor.EnrolledFactorSecurity) Test(org.junit.Test)

Aggregations

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