Search in sources :

Example 21 with UserManager

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

the class DeleteAccount method processAction.

@Override
public void processAction(RequiredActionContext context) {
    KeycloakSession session = context.getSession();
    EventBuilder eventBuilder = context.getEvent();
    KeycloakContext keycloakContext = session.getContext();
    RealmModel realm = keycloakContext.getRealm();
    UserModel user = keycloakContext.getAuthenticationSession().getAuthenticatedUser();
    try {
        if (!clientHasDeleteAccountRole(context)) {
            throw new ForbiddenException();
        }
        boolean removed = new UserManager(session).removeUser(realm, user);
        if (removed) {
            eventBuilder.event(EventType.DELETE_ACCOUNT).client(keycloakContext.getClient()).user(user).detail(Details.USERNAME, user.getUsername()).success();
            cleanSession(context, RequiredActionContext.KcActionStatus.SUCCESS);
            context.challenge(context.form().setAttribute("messageHeader", "").setInfo("userDeletedSuccessfully").createForm("info.ftl"));
        } else {
            eventBuilder.event(EventType.DELETE_ACCOUNT).client(keycloakContext.getClient()).user(user).detail(Details.USERNAME, user.getUsername()).error("User could not be deleted");
            cleanSession(context, RequiredActionContext.KcActionStatus.ERROR);
            context.failure();
        }
    } catch (ForbiddenException forbidden) {
        logger.error("account client does not have the required roles for user deletion");
        eventBuilder.event(EventType.DELETE_ACCOUNT_ERROR).client(keycloakContext.getClient()).user(keycloakContext.getAuthenticationSession().getAuthenticatedUser()).detail(Details.REASON, "does not have the required roles for user deletion").error(Errors.USER_DELETE_ERROR);
        // deletingAccountForbidden
        context.challenge(context.form().setAttribute(TRIGGERED_FROM_AIA, isCurrentActionTriggeredFromAIA(context)).setError(Messages.DELETE_ACCOUNT_LACK_PRIVILEDGES).createForm("delete-account-confirm.ftl"));
    } catch (Exception exception) {
        logger.error("unexpected error happened during account deletion", exception);
        eventBuilder.event(EventType.DELETE_ACCOUNT_ERROR).client(keycloakContext.getClient()).user(keycloakContext.getAuthenticationSession().getAuthenticatedUser()).detail(Details.REASON, exception.getMessage()).error(Errors.USER_DELETE_ERROR);
        context.challenge(context.form().setError(Messages.DELETE_ACCOUNT_ERROR).createForm("delete-account-confirm.ftl"));
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ForbiddenException(org.keycloak.services.ForbiddenException) EventBuilder(org.keycloak.events.EventBuilder) KeycloakContext(org.keycloak.models.KeycloakContext) UserManager(org.keycloak.models.UserManager) KeycloakSession(org.keycloak.models.KeycloakSession) ForbiddenException(org.keycloak.services.ForbiddenException)

Example 22 with UserManager

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

the class SessionTimeoutValidationTest method after.

@After
public void after() {
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        session.sessions().removeUserSessions(realm);
        UserModel user1 = session.users().getUserByUsername(realm, "user1");
        UserManager um = new UserManager(session);
        if (user1 != null) {
            um.removeUser(realm, user1);
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager) After(org.junit.After)

Example 23 with UserManager

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

the class UserSessionProviderOfflineTest method testOnUserRemoved.

@Test
@ModelTest
public void testOnUserRemoved(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionUR) -> {
        try {
            int started = Time.currentTime();
            AtomicReference<String> userSessionID = new AtomicReference<>();
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionUR1) -> {
                currentSession = sessionUR1;
                RealmModel fooRealm = currentSession.realms().createRealm("foo", "foo");
                fooRealm.setDefaultRole(currentSession.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + fooRealm.getName()));
                fooRealm.setSsoSessionIdleTimeout(1800);
                fooRealm.setSsoSessionMaxLifespan(36000);
                fooRealm.setOfflineSessionIdleTimeout(2592000);
                fooRealm.setOfflineSessionMaxLifespan(5184000);
                fooRealm.addClient("foo-app");
                currentSession.users().addUser(fooRealm, "user3");
                UserSessionModel userSession = currentSession.sessions().createUserSession(fooRealm, currentSession.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
                userSessionID.set(userSession.getId());
                createClientSession(currentSession, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionUR2) -> {
                currentSession = sessionUR2;
                // Create offline session
                RealmModel fooRealm = currentSession.realms().getRealm("foo");
                UserSessionModel userSession = currentSession.sessions().getUserSession(fooRealm, userSessionID.get());
                createOfflineSessionIncludeClientSessions(currentSession, userSession);
            });
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionUR3) -> {
                currentSession = sessionUR3;
                RealmManager realmMgr = new RealmManager(currentSession);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
                // Assert session was persisted with both clientSessions
                UserSessionModel offlineSession = currentSession.sessions().getOfflineUserSession(fooRealm, userSessionID.get());
                assertSession(offlineSession, user3, "127.0.0.1", started, started, "foo-app");
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTearDown) -> {
                currentSession = sessionTearDown;
                RealmManager realmMgr = new RealmManager(currentSession);
                RealmModel fooRealm = realmMgr.getRealm("foo");
                UserModel user3 = currentSession.users().getUserByUsername(fooRealm, "user3");
                // Remove user3
                new UserManager(currentSession).removeUser(fooRealm, user3);
                // Cleanup
                realmMgr = new RealmManager(currentSession);
                realmMgr.removeRealm(realmMgr.getRealm("foo"));
            });
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserSessionModel(org.keycloak.models.UserSessionModel) UserManager(org.keycloak.models.UserManager) KeycloakSession(org.keycloak.models.KeycloakSession) AtomicReference(java.util.concurrent.atomic.AtomicReference) RealmManager(org.keycloak.services.managers.RealmManager) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 24 with UserManager

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

the class MultipleRealmsTest method testUsers.

@Test
@ModelTest
public void testUsers(KeycloakSession session) {
    AtomicReference<UserModel> r1user1Atomic = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTestUser1) -> {
        KeycloakSession currentSession = sessionTestUser1;
        RealmModel realm1 = currentSession.realms().createRealm("id1", "realm1");
        RealmModel realm2 = currentSession.realms().createRealm("id2", "realm2");
        realm1.setDefaultRole(currentSession.roles().addRealmRole(realm1, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm1.getName()));
        realm2.setDefaultRole(currentSession.roles().addRealmRole(realm2, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm2.getName()));
        createObjects(currentSession, realm1);
        createObjects(currentSession, realm2);
        UserModel r1user1 = currentSession.users().getUserByUsername(realm1, "user1");
        UserModel r2user1 = currentSession.users().getUserByUsername(realm2, "user1");
        r1user1Atomic.set(r1user1);
        Assert.assertEquals(r1user1.getUsername(), r2user1.getUsername());
        Assert.assertNotEquals(r1user1.getId(), r2user1.getId());
        // Test password
        currentSession.userCredentialManager().updateCredential(realm1, r1user1, UserCredentialModel.password("pass1"));
        currentSession.userCredentialManager().updateCredential(realm2, r2user1, UserCredentialModel.password("pass2"));
        Assert.assertTrue(currentSession.userCredentialManager().isValid(realm1, r1user1, UserCredentialModel.password("pass1")));
        Assert.assertFalse(currentSession.userCredentialManager().isValid(realm1, r1user1, UserCredentialModel.password("pass2")));
        Assert.assertFalse(currentSession.userCredentialManager().isValid(realm2, r2user1, UserCredentialModel.password("pass1")));
        Assert.assertTrue(currentSession.userCredentialManager().isValid(realm2, r2user1, UserCredentialModel.password("pass2")));
        // Test searching
        Assert.assertEquals(2, currentSession.users().searchForUserStream(realm1, "user").count());
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTestUser2) -> {
        KeycloakSession currentSession = sessionTestUser2;
        RealmModel realm1 = currentSession.realms().getRealm("id1");
        RealmModel realm2 = currentSession.realms().getRealm("id2");
        UserModel r1user1 = r1user1Atomic.get();
        currentSession.users().removeUser(realm1, r1user1);
        UserModel user2 = currentSession.users().getUserByUsername(realm1, "user2");
        currentSession.users().removeUser(realm1, user2);
        Assert.assertEquals(0, currentSession.users().searchForUserStream(realm1, "user").count());
        Assert.assertEquals(2, currentSession.users().searchForUserStream(realm2, "user").count());
        UserModel user1 = currentSession.users().getUserByUsername(realm1, "user1");
        UserModel user1a = currentSession.users().getUserByUsername(realm2, "user1");
        UserManager um = new UserManager(currentSession);
        if (user1 != null) {
            um.removeUser(realm1, user1);
        }
        if (user1a != null) {
            um.removeUser(realm2, user1a);
        }
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionTestUser3) -> {
        KeycloakSession currentSession = sessionTestUser3;
        currentSession.realms().removeRealm("id1");
        currentSession.realms().removeRealm("id2");
    });
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) UserManager(org.keycloak.models.UserManager) KeycloakSession(org.keycloak.models.KeycloakSession) AtomicReference(java.util.concurrent.atomic.AtomicReference) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 25 with UserManager

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

the class MultipleRealmsTest method testGetById.

@Test
@ModelTest
public void testGetById(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionById) -> {
        KeycloakSession currentSession = sessionById;
        RealmModel realm1 = currentSession.realms().createRealm("id1", "realm1");
        RealmModel realm2 = currentSession.realms().createRealm("id2", "realm2");
        realm1.setDefaultRole(currentSession.roles().addRealmRole(realm1, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm1.getName()));
        realm2.setDefaultRole(currentSession.roles().addRealmRole(realm2, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realm2.getName()));
        createObjects(currentSession, realm1);
        createObjects(currentSession, realm2);
        Assert.assertEquals(realm1, currentSession.realms().getRealm("id1"));
        Assert.assertEquals(realm1, currentSession.realms().getRealmByName("realm1"));
        Assert.assertEquals(realm2, currentSession.realms().getRealm("id2"));
        Assert.assertEquals(realm2, currentSession.realms().getRealmByName("realm2"));
        ClientModel r1app1 = realm1.getClientByClientId("app1");
        Assert.assertNotNull(realm1.getClientByClientId("app2"));
        Assert.assertNotNull(realm2.getClientByClientId("app1"));
        Assert.assertNotNull(realm2.getClientByClientId("app2"));
        Assert.assertEquals(r1app1, realm1.getClientById(r1app1.getId()));
        Assert.assertNull(realm2.getClientById(r1app1.getId()));
        ClientModel r2cl1 = realm2.getClientByClientId("cl1");
        Assert.assertEquals(r2cl1.getId(), realm2.getClientById(r2cl1.getId()).getId());
        Assert.assertNull(realm1.getClientByClientId(r2cl1.getId()));
        RoleModel r1App1Role = r1app1.getRole("app1Role1");
        Assert.assertEquals(r1App1Role, realm1.getRoleById(r1App1Role.getId()));
        Assert.assertNull(realm2.getRoleById(r1App1Role.getId()));
        RoleModel r2Role1 = realm2.getRole("role2");
        Assert.assertNull(realm1.getRoleById(r2Role1.getId()));
        Assert.assertEquals(r2Role1, realm2.getRoleById(r2Role1.getId()));
        UserModel user1 = currentSession.users().getUserByUsername(realm1, "user1");
        UserModel user1a = currentSession.users().getUserByUsername(realm2, "user1");
        UserManager um = new UserManager(currentSession);
        if (user1 != null) {
            um.removeUser(realm1, user1);
        }
        if (user1a != null) {
            um.removeUser(realm2, user1a);
        }
        currentSession.realms().removeRealm("id1");
        currentSession.realms().removeRealm("id2");
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) UserManager(org.keycloak.models.UserManager) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

UserManager (org.keycloak.models.UserManager)26 UserModel (org.keycloak.models.UserModel)25 RealmModel (org.keycloak.models.RealmModel)20 After (org.junit.After)7 KeycloakSession (org.keycloak.models.KeycloakSession)7 Test (org.junit.Test)6 RealmManager (org.keycloak.services.managers.RealmManager)5 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)4 UserSessionModel (org.keycloak.models.UserSessionModel)3 ClientModel (org.keycloak.models.ClientModel)2 CachedUserModel (org.keycloak.models.cache.CachedUserModel)2 UserCache (org.keycloak.models.cache.UserCache)2 ClientManager (org.keycloak.services.managers.ClientManager)2 DELETE (javax.ws.rs.DELETE)1 NoCache (org.jboss.resteasy.annotations.cache.NoCache)1 EventBuilder (org.keycloak.events.EventBuilder)1 KeycloakContext (org.keycloak.models.KeycloakContext)1 ModelException (org.keycloak.models.ModelException)1