Search in sources :

Example 11 with UserSessionPersisterProvider

use of org.keycloak.models.session.UserSessionPersisterProvider in project keycloak by keycloak.

the class UserSessionPersisterProviderTest method loadPersistedSessionsPaginated.

private List<UserSessionModel> loadPersistedSessionsPaginated(KeycloakSession session, boolean offline, int sessionsPerPage, int expectedPageCount, int expectedSessionsCount) {
    UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
    int count = persister.getUserSessionsCount(offline);
    int pageCount = 0;
    boolean next = true;
    List<UserSessionModel> result = new ArrayList<>();
    String lastSessionId = "00000000-0000-0000-0000-000000000000";
    while (next) {
        List<UserSessionModel> sess = persister.loadUserSessionsStream(0, sessionsPerPage, offline, lastSessionId).collect(Collectors.toList());
        if (sess.size() < sessionsPerPage) {
            next = false;
            // We had at least some session
            if (sess.size() > 0) {
                pageCount++;
            }
        } else {
            pageCount++;
            UserSessionModel lastSession = sess.get(sess.size() - 1);
            lastSessionId = lastSession.getId();
        }
        result.addAll(sess);
    }
    Assert.assertEquals(expectedPageCount, pageCount);
    Assert.assertEquals(expectedSessionsCount, result.size());
    return result;
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) ArrayList(java.util.ArrayList)

Example 12 with UserSessionPersisterProvider

use of org.keycloak.models.session.UserSessionPersisterProvider in project keycloak by keycloak.

the class UserSessionPersisterProviderTest method testUpdateAndRemove.

@Test
public void testUpdateAndRemove() {
    int started = Time.currentTime();
    AtomicReference<UserSessionModel[]> origSessionsAt = new AtomicReference<>();
    AtomicReference<List<UserSessionModel>> loadedSessionsAt = new AtomicReference<>();
    AtomicReference<UserSessionModel> userSessionAt = new AtomicReference<>();
    AtomicReference<UserSessionModel> persistedSessionAt = new AtomicReference<>();
    inComittedTransaction(session -> {
        // Create some sessions in infinispan
        UserSessionModel[] origSessions = createSessions(session, realmId);
        origSessionsAt.set(origSessions);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionModel[] origSessions = origSessionsAt.get();
        // Persist 1 offline session
        UserSessionModel userSession = session.sessions().getUserSession(realm, origSessions[1].getId());
        userSessionAt.set(userSession);
        persistUserSession(session, userSession, true);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        // Load offline session
        List<UserSessionModel> loadedSessions = loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        loadedSessionsAt.set(loadedSessions);
        UserSessionModel persistedSession = loadedSessions.get(0);
        persistedSessionAt.set(persistedSession);
        assertSession(persistedSession, session.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app");
        // create new clientSession
        AuthenticatedClientSessionModel clientSession = createClientSession(session, realmId, realm.getClientByClientId("third-party"), session.sessions().getUserSession(realm, persistedSession.getId()), "http://redirect", "state");
        persister.createClientSession(clientSession, true);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        UserSessionModel userSession = userSessionAt.get();
        // Remove clientSession
        persister.removeClientSession(userSession.getId(), realm.getClientByClientId("third-party").getId(), true);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        // Assert clientSession removed
        List<UserSessionModel> loadedSessions = loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        UserSessionModel persistedSession = loadedSessions.get(0);
        assertSession(persistedSession, session.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app");
        // Remove userSession
        persister.removeUserSession(persistedSession.getId(), true);
    });
    inComittedTransaction(session -> {
        // Assert nothing found
        loadPersistedSessionsPaginated(session, true, 10, 0, 0);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 13 with UserSessionPersisterProvider

use of org.keycloak.models.session.UserSessionPersisterProvider in project keycloak by keycloak.

the class UserSessionPersisterProviderTest method testOnUserRemoved.

@Test
public void testOnUserRemoved() {
    int started = Time.currentTime();
    AtomicReference<UserSessionModel[]> origSessionsAt = new AtomicReference<>();
    inComittedTransaction(session -> {
        // Create some sessions in infinispan
        UserSessionModel[] origSessions = createSessions(session, realmId);
        origSessionsAt.set(origSessions);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionModel[] origSessions = origSessionsAt.get();
        // Persist 2 offline sessions of 2 users
        UserSessionModel userSession1 = session.sessions().getUserSession(realm, origSessions[1].getId());
        UserSessionModel userSession2 = session.sessions().getUserSession(realm, origSessions[2].getId());
        persistUserSession(session, userSession1, true);
        persistUserSession(session, userSession2, true);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        // Load offline sessions
        loadPersistedSessionsPaginated(session, true, 10, 1, 2);
        // Properly delete user and assert his offlineSession removed
        UserModel user1 = session.users().getUserByUsername(realm, "user1");
        new UserManager(session).removeUser(realm, user1);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        Assert.assertEquals(1, persister.getUserSessionsCount(true));
        List<UserSessionModel> loadedSessions = loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        UserSessionModel persistedSession = loadedSessions.get(0);
        assertSession(persistedSession, session.users().getUserByUsername(realm, "user2"), "127.0.0.3", started, started, "test-app");
        // KEYCLOAK-2431 Assert that userSessionPersister is resistent even to situation, when users are deleted "directly".
        // No exception will happen. However session will be still there
        UserModel user2 = session.users().getUserByUsername(realm, "user2");
        session.users().removeUser(realm, user2);
        loadedSessions = loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        // Cleanup
        UserSessionModel userSession = loadedSessions.get(0);
        session.sessions().removeUserSession(realm, userSession);
        persister.removeUserSession(userSession.getId(), userSession.isOffline());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) UserManager(org.keycloak.models.UserManager) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 14 with UserSessionPersisterProvider

use of org.keycloak.models.session.UserSessionPersisterProvider in project keycloak by keycloak.

the class OfflinePersistentUserSessionLoader method loadSessions.

@Override
public OfflinePersistentWorkerResult loadSessions(KeycloakSession session, OfflinePersistentLoaderContext loaderContext, OfflinePersistentWorkerContext ctx) {
    int first = ctx.getWorkerId() * sessionsPerSegment;
    log.tracef("Loading sessions for segment=%d lastSessionId=%s", ctx.getSegment(), ctx.getLastSessionId());
    UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
    List<UserSessionModel> sessions = persister.loadUserSessionsStream(first, sessionsPerSegment, true, ctx.getLastSessionId()).collect(Collectors.toList());
    log.tracef("Sessions loaded from DB - segment=%d lastSessionId=%s", ctx.getSegment(), ctx.getLastSessionId());
    UserSessionModel lastSession = null;
    if (!sessions.isEmpty()) {
        lastSession = sessions.get(sessions.size() - 1);
        // Save to memory/infinispan
        session.sessions().importUserSessions(sessions, true);
    }
    String lastSessionId = lastSession == null ? FIRST_SESSION_ID : lastSession.getId();
    log.tracef("Sessions imported to infinispan - segment: %d, lastSessionId: %s", ctx.getSegment(), lastSessionId);
    return new OfflinePersistentWorkerResult(true, ctx.getSegment(), ctx.getWorkerId(), lastSessionId);
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider)

Example 15 with UserSessionPersisterProvider

use of org.keycloak.models.session.UserSessionPersisterProvider in project keycloak by keycloak.

the class PersistSessionsCommand method createSessionsBatch.

private void createSessionsBatch(final int countInThisBatch) {
    final List<String> userSessionIds = new LinkedList<>();
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            RealmModel realm = session.realms().getRealmByName("master");
            ClientModel testApp = realm.getClientByClientId("security-admin-console");
            UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
            for (int i = 0; i < countInThisBatch; i++) {
                String username = "john-" + userCounter.incrementAndGet();
                UserModel john = session.users().getUserByUsername(realm, username);
                if (john == null) {
                    john = session.users().addUser(realm, username);
                }
                UserSessionModel userSession = session.sessions().createUserSession(realm, john, username, "127.0.0.2", "form", true, null, null);
                AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, testApp, userSession);
                clientSession.setRedirectUri("http://redirect");
                clientSession.setNote("foo", "bar-" + i);
                userSessionIds.add(userSession.getId());
            }
        }
    });
    log.infof("%d sessions created in infinispan storage", countInThisBatch);
    // Persist them now
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            RealmModel realm = session.realms().getRealmByName("master");
            ClientModel testApp = realm.getClientByClientId("security-admin-console");
            UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
            int counter = 0;
            for (String userSessionId : userSessionIds) {
                counter++;
                UserSessionModel userSession = session.sessions().getUserSession(realm, userSessionId);
                persister.createUserSession(userSession, true);
                AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessions().get(testApp.getId());
                persister.createClientSession(clientSession, true);
            }
            log.infof("%d user sessions persisted. Continue", counter);
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) LinkedList(java.util.LinkedList)

Aggregations

UserSessionPersisterProvider (org.keycloak.models.session.UserSessionPersisterProvider)20 UserSessionModel (org.keycloak.models.UserSessionModel)10 RealmModel (org.keycloak.models.RealmModel)7 Test (org.junit.Test)6 KeycloakModelTest (org.keycloak.testsuite.model.KeycloakModelTest)6 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)4 KeycloakSession (org.keycloak.models.KeycloakSession)4 UserModel (org.keycloak.models.UserModel)4 LinkedList (java.util.LinkedList)3 Set (java.util.Set)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 SessionEntityWrapper (org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)3 ResetTimeOffsetEvent (org.keycloak.models.utils.ResetTimeOffsetEvent)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 Time (org.keycloak.common.util.Time)2 ClientModel (org.keycloak.models.ClientModel)2