Search in sources :

Example 1 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class InfinispanCacheInitializer method startLoading.

// Just coordinator will run this
@Override
protected void startLoading() {
    InitializerState state = getStateFromCache();
    SessionLoader.LoaderContext[] ctx = new SessionLoader.LoaderContext[1];
    if (state == null) {
        // Rather use separate transactions for update and counting
        KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

            @Override
            public void run(KeycloakSession session) {
                sessionLoader.init(session);
            }
        });
        KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

            @Override
            public void run(KeycloakSession session) {
                ctx[0] = sessionLoader.computeLoaderContext(session);
            }
        });
        state = new InitializerState(ctx[0].getSegmentsCount());
    } else {
        KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

            @Override
            public void run(KeycloakSession session) {
                ctx[0] = sessionLoader.computeLoaderContext(session);
            }
        });
    }
    log.debugf("Start loading with loader: '%s', ctx: '%s' , state: %s", sessionLoader.toString(), ctx[0].toString(), state.toString());
    startLoadingImpl(state, ctx[0]);
}
Also used : KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession)

Example 2 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class SessionInitializerWorker method apply.

@Override
public SessionLoader.WorkerResult apply(EmbeddedCacheManager embeddedCacheManager) {
    Cache<Object, Object> workCache = embeddedCacheManager.getCache(cacheName);
    if (log.isTraceEnabled()) {
        log.tracef("Running computation for segment %s with worker %s", workerCtx.getSegment(), workerCtx.getWorkerId());
    }
    KeycloakSessionFactory sessionFactory = workCache.getAdvancedCache().getComponentRegistry().getComponent(KeycloakSessionFactory.class);
    if (sessionFactory == null) {
        log.debugf("KeycloakSessionFactory not yet set in cache. Worker skipped");
        return sessionLoader.createFailedWorkerResult(loaderCtx, workerCtx);
    }
    SessionLoader.WorkerResult[] ref = new SessionLoader.WorkerResult[1];
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            ref[0] = sessionLoader.loadSessions(session, loaderCtx, workerCtx);
        }
    });
    return ref[0];
}
Also used : KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory)

Example 3 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class KeycloakApplication method bootstrap.

// Bootstrap master realm, import realms and create admin user.
protected ExportImportManager bootstrap() {
    ExportImportManager[] exportImportManager = new ExportImportManager[1];
    logger.debug("bootstrap");
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            // TODO what is the purpose of following piece of code? Leaving it as is for now.
            JtaTransactionManagerLookup lookup = (JtaTransactionManagerLookup) sessionFactory.getProviderFactory(JtaTransactionManagerLookup.class);
            if (lookup != null) {
                if (lookup.getTransactionManager() != null) {
                    try {
                        Transaction transaction = lookup.getTransactionManager().getTransaction();
                        logger.debugv("bootstrap current transaction? {0}", transaction != null);
                        if (transaction != null) {
                            logger.debugv("bootstrap current transaction status? {0}", transaction.getStatus());
                        }
                    } catch (SystemException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            // TODO up here ^^
            ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
            exportImportManager[0] = new ExportImportManager(session);
            boolean createMasterRealm = applianceBootstrap.isNewInstall();
            if (exportImportManager[0].isRunImport() && exportImportManager[0].isImportMasterIncluded()) {
                createMasterRealm = false;
            }
            if (createMasterRealm) {
                applianceBootstrap.createMasterRealm();
            }
        }
    });
    if (exportImportManager[0].isRunImport()) {
        exportImportManager[0].runImport();
    } else {
        importRealms();
    }
    importAddUser();
    return exportImportManager[0];
}
Also used : ApplianceBootstrap(org.keycloak.services.managers.ApplianceBootstrap) JtaTransactionManagerLookup(org.keycloak.transaction.JtaTransactionManagerLookup) Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) ExportImportManager(org.keycloak.exportimport.ExportImportManager)

Example 4 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class LDAPStorageProviderFactory method createQuery.

/**
 *  !! This function must be called from try-with-resources block, otherwise Vault secrets may be leaked !!
 * @param sessionFactory
 * @param realmId
 * @param model
 * @return
 */
private LDAPQuery createQuery(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel model) {
    class QueryHolder {

        LDAPQuery query;
    }
    final QueryHolder queryHolder = new QueryHolder();
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            session.getContext().setRealm(session.realms().getRealm(realmId));
            LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, model);
            RealmModel realm = session.realms().getRealm(realmId);
            queryHolder.query = LDAPUtils.createQueryForUserSearch(ldapFedProvider, realm);
        }
    });
    return queryHolder.query;
}
Also used : RealmModel(org.keycloak.models.RealmModel) LDAPQuery(org.keycloak.storage.ldap.idm.query.internal.LDAPQuery) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession)

Example 5 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class LDAPStorageProviderFactory method importLdapUsers.

protected SynchronizationResult importLdapUsers(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel fedModel, List<LDAPObject> ldapUsers) {
    final SynchronizationResult syncResult = new SynchronizationResult();
    class BooleanHolder {

        private boolean value = true;
    }
    final BooleanHolder exists = new BooleanHolder();
    for (final LDAPObject ldapUser : ldapUsers) {
        try {
            // Process each user in it's own transaction to avoid global fail
            KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

                @Override
                public void run(KeycloakSession session) {
                    LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, fedModel);
                    RealmModel currentRealm = session.realms().getRealm(realmId);
                    session.getContext().setRealm(currentRealm);
                    String username = LDAPUtils.getUsername(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
                    exists.value = true;
                    LDAPUtils.checkUuid(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
                    UserModel currentUserLocal = session.userLocalStorage().getUserByUsername(currentRealm, username);
                    Optional<UserModel> userModelOptional = session.userLocalStorage().searchForUserByUserAttributeStream(currentRealm, LDAPConstants.LDAP_ID, ldapUser.getUuid()).findFirst();
                    if (!userModelOptional.isPresent() && currentUserLocal == null) {
                        // Add new user to Keycloak
                        exists.value = false;
                        ldapFedProvider.importUserFromLDAP(session, currentRealm, ldapUser);
                        syncResult.increaseAdded();
                    } else {
                        UserModel currentUser = userModelOptional.isPresent() ? userModelOptional.get() : currentUserLocal;
                        if ((fedModel.getId().equals(currentUser.getFederationLink())) && (ldapUser.getUuid().equals(currentUser.getFirstAttribute(LDAPConstants.LDAP_ID)))) {
                            // Update keycloak user
                            LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(ldapFedProvider.getLdapIdentityStore().getConfig());
                            currentRealm.getComponentsStream(fedModel.getId(), LDAPStorageMapper.class.getName()).sorted(ldapMappersComparator.sortDesc()).forEachOrdered(mapperModel -> {
                                LDAPStorageMapper ldapMapper = ldapFedProvider.getMapperManager().getMapper(mapperModel);
                                ldapMapper.onImportUserFromLDAP(ldapUser, currentUser, currentRealm, false);
                            });
                            UserCache userCache = session.userCache();
                            if (userCache != null) {
                                userCache.evict(currentRealm, currentUser);
                            }
                            logger.debugf("Updated user from LDAP: %s", currentUser.getUsername());
                            syncResult.increaseUpdated();
                        } else {
                            logger.warnf("User with ID '%s' is not updated during sync as he already exists in Keycloak database but is not linked to federation provider '%s'", ldapUser.getUuid(), fedModel.getName());
                            syncResult.increaseFailed();
                        }
                    }
                }
            });
        } catch (ModelException me) {
            logger.error("Failed during import user from LDAP", me);
            syncResult.increaseFailed();
            // Remove user if we already added him during this transaction
            if (!exists.value) {
                KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

                    @Override
                    public void run(KeycloakSession session) {
                        LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, fedModel);
                        RealmModel currentRealm = session.realms().getRealm(realmId);
                        session.getContext().setRealm(currentRealm);
                        String username = null;
                        try {
                            username = LDAPUtils.getUsername(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
                        } catch (ModelException ignore) {
                        }
                        if (username != null) {
                            UserModel existing = session.userLocalStorage().getUserByUsername(currentRealm, username);
                            if (existing != null) {
                                UserCache userCache = session.userCache();
                                if (userCache != null) {
                                    userCache.evict(currentRealm, existing);
                                }
                                session.userLocalStorage().removeUser(currentRealm, existing);
                            }
                        }
                    }
                });
            }
        }
    }
    return syncResult;
}
Also used : SPNEGOAuthenticator(org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator) FullNameLDAPStorageMapperFactory(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapperFactory) Date(java.util.Date) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) Config(org.keycloak.Config) FullNameLDAPStorageMapper(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper) ProviderConfigurationBuilder(org.keycloak.provider.ProviderConfigurationBuilder) LDAPConstants(org.keycloak.models.LDAPConstants) Map(java.util.Map) ComponentModel(org.keycloak.component.ComponentModel) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel) UserAttributeLDAPStorageMapperFactory(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapperFactory) UserStorageProviderFactory(org.keycloak.storage.UserStorageProviderFactory) HardcodedLDAPAttributeMapper(org.keycloak.storage.ldap.mappers.HardcodedLDAPAttributeMapper) HardcodedLDAPAttributeMapperFactory(org.keycloak.storage.ldap.mappers.HardcodedLDAPAttributeMapperFactory) RealmModel(org.keycloak.models.RealmModel) LDAPConfigDecorator(org.keycloak.storage.ldap.mappers.LDAPConfigDecorator) CredentialHelper(org.keycloak.utils.CredentialHelper) CommonKerberosConfig(org.keycloak.federation.kerberos.CommonKerberosConfig) Collectors(java.util.stream.Collectors) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) ImportSynchronization(org.keycloak.storage.user.ImportSynchronization) List(java.util.List) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) KerberosUsernamePasswordAuthenticator(org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) Optional(java.util.Optional) Condition(org.keycloak.storage.ldap.idm.query.Condition) ComponentValidationException(org.keycloak.component.ComponentValidationException) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) Function(java.util.function.Function) LDAPIdentityStore(org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore) UserModel(org.keycloak.models.UserModel) AuthenticationExecutionModel(org.keycloak.models.AuthenticationExecutionModel) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) LDAPQueryConditionsBuilder(org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder) KerberosConstants(org.keycloak.common.constants.KerberosConstants) UserStorageProvider(org.keycloak.storage.UserStorageProvider) LDAPMappersComparator(org.keycloak.storage.ldap.mappers.LDAPMappersComparator) KerberosServerSubjectAuthenticator(org.keycloak.federation.kerberos.impl.KerberosServerSubjectAuthenticator) KeycloakSession(org.keycloak.models.KeycloakSession) LDAPQuery(org.keycloak.storage.ldap.idm.query.internal.LDAPQuery) UserCache(org.keycloak.models.cache.UserCache) MSADUserAccountControlStorageMapperFactory(org.keycloak.storage.ldap.mappers.msad.MSADUserAccountControlStorageMapperFactory) ModelException(org.keycloak.models.ModelException) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) FullNameLDAPStorageMapper(org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper) UserAttributeLDAPStorageMapper(org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper) Optional(java.util.Optional) LDAPMappersComparator(org.keycloak.storage.ldap.mappers.LDAPMappersComparator) ModelException(org.keycloak.models.ModelException) UserCache(org.keycloak.models.cache.UserCache) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserStorageProvider(org.keycloak.storage.UserStorageProvider) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult)

Aggregations

KeycloakSession (org.keycloak.models.KeycloakSession)15 KeycloakSessionTask (org.keycloak.models.KeycloakSessionTask)15 RealmModel (org.keycloak.models.RealmModel)5 SynchronizationResult (org.keycloak.storage.user.SynchronizationResult)4 UserModel (org.keycloak.models.UserModel)3 UserStorageProvider (org.keycloak.storage.UserStorageProvider)3 UserStorageProviderFactory (org.keycloak.storage.UserStorageProviderFactory)3 ImportSynchronization (org.keycloak.storage.user.ImportSynchronization)3 List (java.util.List)2 Cache (org.infinispan.Cache)2 RemoteCache (org.infinispan.client.hotrod.RemoteCache)2 ClusterProvider (org.keycloak.cluster.ClusterProvider)2 InfinispanConnectionProvider (org.keycloak.connections.infinispan.InfinispanConnectionProvider)2 ExportImportManager (org.keycloak.exportimport.ExportImportManager)2 KeycloakSessionFactory (org.keycloak.models.KeycloakSessionFactory)2 UserSessionPersisterProvider (org.keycloak.models.session.UserSessionPersisterProvider)2 InfinispanCacheInitializer (org.keycloak.models.sessions.infinispan.initializer.InfinispanCacheInitializer)2 RemoteCacheSessionsLoader (org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheSessionsLoader)2 LDAPQuery (org.keycloak.storage.ldap.idm.query.internal.LDAPQuery)2 Date (java.util.Date)1