Java Code Examples for org.keycloak.models.KeycloakSession#getTransactionManager()

The following examples show how to use org.keycloak.models.KeycloakSession#getTransactionManager() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeycloakModelUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Wrap given runnable job into KeycloakTransaction.
 *
 * @param factory
 * @param task
 */
public static void runJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task) {
    KeycloakSession session = factory.create();
    KeycloakTransaction tx = session.getTransactionManager();
    try {
        tx.begin();
        task.run(session);

        if (tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            } else {
                tx.commit();
            }
        }
    } catch (RuntimeException re) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw re;
    } finally {
        session.close();
    }
}
 
Example 2
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@ModelTest
public void testGetUserSessions(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);

    KeycloakTransaction transaction = session.getTransactionManager();
    if (!transaction.getRollbackOnly()) {
        transaction.commit();

    }


    assertSessions(session.sessions().getUserSessions(realm, session.users().getUserByUsername("user1", realm)), sessions[0], sessions[1]);
    assertSessions(session.sessions().getUserSessions(realm, session.users().getUserByUsername("user2", realm)), sessions[2]);
}
 
Example 3
Source File: QuarkusFilter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext) {
    KeycloakSessionFactory sessionFactory = keycloakApplication.getSessionFactory();
    KeycloakSession session = sessionFactory.create();

    Resteasy.pushContext(KeycloakSession.class, session);
    HttpServerRequest request = routingContext.request();

    session.getContext().setConnection(createConnection(request));
    Resteasy.pushContext(ClientConnection.class, session.getContext().getConnection());

    KeycloakTransaction tx = session.getTransactionManager();
    Resteasy.pushContext(KeycloakTransaction.class, tx);

    tx.begin();
}
 
Example 4
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void testGetByClient(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);

    KeycloakTransaction transaction = session.getTransactionManager();
    if (!transaction.getRollbackOnly()) {
        transaction.commit();
    }


    assertSessions(session.sessions().getUserSessions(realm, realm.getClientByClientId("test-app")), sessions[0], sessions[1], sessions[2]);
    assertSessions(session.sessions().getUserSessions(realm, realm.getClientByClientId("third-party")), sessions[0]);
}
 
Example 5
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void testGetByClientPaginated(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    try {
        for (int i = 0; i < 25; i++) {
            Time.setOffset(i);
            UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0." + i, "form", false, null, null);
            AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, realm.getClientByClientId("test-app"), userSession);
            assertNotNull(clientSession);
            clientSession.setRedirectUri("http://redirect");
            clientSession.setNote(OIDCLoginProtocol.STATE_PARAM, "state");
            clientSession.setTimestamp(userSession.getStarted());
            userSession.setLastSessionRefresh(userSession.getStarted());
        }
    } finally {
        Time.setOffset(0);
    }

    KeycloakTransaction transaction = session.getTransactionManager();
    if (!transaction.getRollbackOnly()) {
        transaction.commit();
    }

    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 0, 1, 1);
    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 0, 10, 10);
    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 10, 10, 10);
    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 20, 10, 5);
    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 30, 10, 0);
}
 
Example 6
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void testGetCountByClient(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    createSessions(session);

    KeycloakTransaction transaction = session.getTransactionManager();
    if (!transaction.getRollbackOnly()) {
        transaction.commit();
    }

    assertEquals(3, session.sessions().getActiveUserSessions(realm, realm.getClientByClientId("test-app")));
    assertEquals(1, session.sessions().getActiveUserSessions(realm, realm.getClientByClientId("third-party")));
}
 
Example 7
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void closeSession(KeycloakSession session) {
    // KeycloakTransactionCommitter is responsible for committing the transaction, but if an exception is thrown it's not invoked and transaction
    // should be rolled back
    if (session.getTransactionManager() != null && session.getTransactionManager().isActive()) {
        session.getTransactionManager().rollback();
    }

    session.close();
    Resteasy.clearContextData();
}
 
Example 8
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void closeSession(KeycloakSession session) {
    // KeycloakTransactionCommitter is responsible for committing the transaction, but if an exception is thrown it's not invoked and transaction
    // should be rolled back
    if (session.getTransactionManager() != null && session.getTransactionManager().isActive()) {
        session.getTransactionManager().rollback();
    }

    session.close();
    Resteasy.clearContextData();
}
 
Example 9
Source File: QuarkusLifecycleObserver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void createAdminUser() {
    String adminUserName = System.getenv(KEYCLOAK_ADMIN_ENV_VAR);
    String adminPassword = System.getenv(KEYCLOAK_ADMIN_PASSWORD_ENV_VAR);

    if ((adminUserName == null || adminUserName.trim().length() == 0)
            || (adminPassword == null || adminPassword.trim().length() == 0)) {
        return;
    }

    KeycloakSessionFactory sessionFactory = application.getSessionFactory();
    KeycloakSession session = sessionFactory.create();
    KeycloakTransactionManager transaction = session.getTransactionManager();

    try {
        transaction.begin();

        new ApplianceBootstrap(session).createMasterRealmUser(adminUserName, adminPassword);
        ServicesLogger.LOGGER.addUserSuccess(adminUserName, Config.getAdminRealm());

        transaction.commit();
    } catch (IllegalStateException e) {
        session.getTransactionManager().rollback();
        ServicesLogger.LOGGER.addUserFailedUserExists(adminUserName, Config.getAdminRealm());
    } catch (Throwable t) {
        session.getTransactionManager().rollback();
        ServicesLogger.LOGGER.addUserFailed(t, adminUserName, Config.getAdminRealm());
    } finally {
        session.close();
    }
}
 
Example 10
Source File: QuarkusFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
    //End the session and clear context
    KeycloakSession session = Resteasy.getContextData(KeycloakSession.class);

    // KeycloakTransactionCommitter is responsible for committing the transaction, but if an exception is thrown it's not invoked and transaction
    // should be rolled back
    if (session.getTransactionManager() != null && session.getTransactionManager().isActive()) {
        session.getTransactionManager().rollback();
    }

    session.close();
    Resteasy.clearContextData();
}
 
Example 11
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    servletRequest.setCharacterEncoding("UTF-8");

    final HttpServletRequest request = (HttpServletRequest)servletRequest;

    KeycloakSessionFactory sessionFactory = (KeycloakSessionFactory) servletRequest.getServletContext().getAttribute(KeycloakSessionFactory.class.getName());
    KeycloakSession session = sessionFactory.create();
    Resteasy.pushContext(KeycloakSession.class, session);
    ClientConnection connection = new ClientConnection() {
        @Override
        public String getRemoteAddr() {
            return request.getRemoteAddr();
        }

        @Override
        public String getRemoteHost() {
            return request.getRemoteHost();
        }

        @Override
        public int getRemotePort() {
            return request.getRemotePort();
        }

        @Override
        public String getLocalAddr() {
            return request.getLocalAddr();
        }

        @Override
        public int getLocalPort() {
            return request.getLocalPort();
        }
    };
    session.getContext().setConnection(connection);
    Resteasy.pushContext(ClientConnection.class, connection);

    KeycloakTransaction tx = session.getTransactionManager();
    Resteasy.pushContext(KeycloakTransaction.class, tx);
    tx.begin();

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        if (servletRequest.isAsyncStarted()) {
            servletRequest.getAsyncContext().addListener(createAsyncLifeCycleListener(session));
        } else {
            closeSession(session);
        }
    }
}
 
Example 12
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    servletRequest.setCharacterEncoding("UTF-8");

    final HttpServletRequest request = (HttpServletRequest)servletRequest;

    KeycloakSessionFactory sessionFactory = (KeycloakSessionFactory) servletRequest.getServletContext().getAttribute(KeycloakSessionFactory.class.getName());
    KeycloakSession session = sessionFactory.create();
    Resteasy.pushContext(KeycloakSession.class, session);
    ClientConnection connection = new ClientConnection() {
        @Override
        public String getRemoteAddr() {
            return request.getRemoteAddr();
        }

        @Override
        public String getRemoteHost() {
            return request.getRemoteHost();
        }

        @Override
        public int getRemotePort() {
            return request.getRemotePort();
        }

        @Override
        public String getLocalAddr() {
            return request.getLocalAddr();
        }

        @Override
        public int getLocalPort() {
            return request.getLocalPort();
        }
    };
    session.getContext().setConnection(connection);
    Resteasy.pushContext(ClientConnection.class, connection);

    KeycloakTransaction tx = session.getTransactionManager();
    Resteasy.pushContext(KeycloakTransaction.class, tx);
    tx.begin();

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        if (servletRequest.isAsyncStarted()) {
            servletRequest.getAsyncContext().addListener(createAsyncLifeCycleListener(session));
        } else {
            closeSession(session);
        }
    }
}