Search in sources :

Example 96 with UserModel

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

the class AuthenticationSessionProviderTest method testLoginSessionsCRUD.

@Test
@ModelTest
public void testLoginSessionsCRUD(KeycloakSession session) {
    AtomicReference<String> rootAuthSessionID = new AtomicReference<>();
    AtomicReference<String> tabID = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD1) -> {
        KeycloakSession currentSession = sessionCRUD1;
        RealmModel realm = currentSession.realms().getRealm("test");
        ClientModel client1 = realm.getClientByClientId("test-app");
        RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().createRootAuthenticationSession(realm);
        rootAuthSessionID.set(rootAuthSession.getId());
        AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client1);
        tabID.set(authSession.getTabId());
        authSession.setAction("foo");
        rootAuthSession.setTimestamp(100);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD2) -> {
        KeycloakSession currentSession = sessionCRUD2;
        RealmModel realm = currentSession.realms().getRealm("test");
        ClientModel client1 = realm.getClientByClientId("test-app");
        // Ensure currentSession is here
        RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, rootAuthSessionID.get());
        AuthenticationSessionModel authSession = rootAuthSession.getAuthenticationSession(client1, tabID.get());
        testAuthenticationSession(authSession, client1.getId(), null, "foo");
        assertThat(rootAuthSession.getTimestamp(), is(100));
        // Update and commit
        authSession.setAction("foo-updated");
        rootAuthSession.setTimestamp(200);
        authSession.setAuthenticatedUser(currentSession.users().getUserByUsername(realm, "user1"));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD3) -> {
        KeycloakSession currentSession = sessionCRUD3;
        RealmModel realm = currentSession.realms().getRealm("test");
        UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
        // Ensure currentSession was updated
        RootAuthenticationSessionModel rootAuthSession = currentSession.authenticationSessions().getRootAuthenticationSession(realm, rootAuthSessionID.get());
        ClientModel client1 = realm.getClientByClientId("test-app");
        AuthenticationSessionModel authSession = rootAuthSession.getAuthenticationSession(client1, tabID.get());
        testAuthenticationSession(authSession, client1.getId(), user1.getId(), "foo-updated");
        assertThat(rootAuthSession.getTimestamp(), is(200));
        // Remove and commit
        currentSession.authenticationSessions().removeRootAuthenticationSession(realm, rootAuthSession);
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionCRUD4) -> {
        KeycloakSession currentSession = sessionCRUD4;
        RealmModel realm = currentSession.realms().getRealm("test");
        // Ensure currentSession was removed
        assertThat(currentSession.authenticationSessions().getRootAuthenticationSession(realm, rootAuthSessionID.get()), nullValue());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) 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 97 with UserModel

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

the class CacheTest method testRoleMappingsInvalidatedWhenClientRemoved.

// KEYCLOAK-1842
@Test
public void testRoleMappingsInvalidatedWhenClientRemoved() {
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        UserModel user = session.users().addUser(realm, "joel");
        ClientModel client = realm.addClient("foo");
        RoleModel fooRole = client.addRole("foo-role");
        user.grantRole(fooRole);
    });
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        UserModel user = session.users().getUserByUsername(realm, "joel");
        long grantedRolesCount = user.getRoleMappingsStream().count();
        ClientModel client = realm.getClientByClientId("foo");
        realm.removeClient(client.getId());
        realm = session.realms().getRealmByName("test");
        user = session.users().getUserByUsername(realm, "joel");
        Set<RoleModel> roles = user.getRoleMappingsStream().collect(Collectors.toSet());
        for (RoleModel role : roles) {
            Assert.assertNotNull(role.getContainer());
        }
        Assert.assertEquals(roles.size(), grantedRolesCount - 1);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) RoleModel(org.keycloak.models.RoleModel) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 98 with UserModel

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

the class UserModelTest method persistUser.

@Test
@ModelTest
public void persistUser(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesPersistUser) -> {
        KeycloakSession currentSession = sesPersistUser;
        RealmModel realm = currentSession.realms().getRealmByName("original");
        UserModel user = currentSession.users().addUser(realm, "user");
        user.setFirstName("first-name");
        user.setLastName("last-name");
        user.setEmail("email");
        assertNotNull(user.getCreatedTimestamp());
        // test that timestamp is current with 10s tollerance
        Assert.assertTrue((System.currentTimeMillis() - user.getCreatedTimestamp()) < 10000);
        user.addRequiredAction(RequiredAction.CONFIGURE_TOTP);
        user.addRequiredAction(RequiredAction.UPDATE_PASSWORD);
        RealmModel searchRealm = currentSession.realms().getRealm(realm.getId());
        UserModel persisted = currentSession.users().getUserByUsername(searchRealm, "user");
        assertUserModel(user, persisted);
        searchRealm = currentSession.realms().getRealm(realm.getId());
        UserModel persisted2 = currentSession.users().getUserById(searchRealm, user.getId());
        assertUserModel(user, persisted2);
        Map<String, String> attributes = new HashMap<>();
        attributes.put(UserModel.LAST_NAME, "last-name");
        List<UserModel> search = currentSession.users().searchForUserStream(realm, attributes).collect(Collectors.toList());
        Assert.assertThat(search, hasSize(1));
        Assert.assertThat(search.get(0).getUsername(), equalTo("user"));
        attributes.clear();
        attributes.put(UserModel.EMAIL, "email");
        search = currentSession.users().searchForUserStream(realm, attributes).collect(Collectors.toList());
        Assert.assertThat(search, hasSize(1));
        Assert.assertThat(search.get(0).getUsername(), equalTo("user"));
        attributes.clear();
        attributes.put(UserModel.LAST_NAME, "last-name");
        attributes.put(UserModel.EMAIL, "email");
        search = currentSession.users().searchForUserStream(realm, attributes).collect(Collectors.toList());
        Assert.assertThat(search, hasSize(1));
        Assert.assertThat(search.get(0).getUsername(), equalTo("user"));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) HashMap(java.util.HashMap) KeycloakSession(org.keycloak.models.KeycloakSession) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 99 with UserModel

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

the class LDAPStorageProvider method importUserFromLDAP.

protected UserModel importUserFromLDAP(KeycloakSession session, RealmModel realm, LDAPObject ldapUser) {
    String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig());
    LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());
    UserModel imported = null;
    if (model.isImportEnabled()) {
        // Search if there is already an existing user, which means the username might have changed in LDAP without Keycloak knowing about it
        UserModel existingLocalUser = session.userLocalStorage().searchForUserByUserAttributeStream(realm, LDAPConstants.LDAP_ID, ldapUser.getUuid()).findFirst().orElse(null);
        if (existingLocalUser != null) {
            imported = existingLocalUser;
            // Need to evict the existing user from cache
            if (session.userCache() != null) {
                session.userCache().evict(realm, existingLocalUser);
            }
        } else {
            imported = session.userLocalStorage().addUser(realm, ldapUsername);
        }
    } else {
        InMemoryUserAdapter adapter = new InMemoryUserAdapter(session, realm, new StorageId(model.getId(), ldapUsername).getId());
        adapter.addDefaults();
        imported = adapter;
    }
    imported.setEnabled(true);
    UserModel finalImported = imported;
    realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName()).sorted(ldapMappersComparator.sortDesc()).forEachOrdered(mapperModel -> {
        if (logger.isTraceEnabled()) {
            logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
        }
        LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
        ldapMapper.onImportUserFromLDAP(ldapUser, finalImported, realm, true);
    });
    String userDN = ldapUser.getDn().toString();
    if (model.isImportEnabled())
        imported.setFederationLink(model.getId());
    imported.setSingleAttribute(LDAPConstants.LDAP_ID, ldapUser.getUuid());
    imported.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, userDN);
    if (getLdapIdentityStore().getConfig().isTrustEmail()) {
        imported.setEmailVerified(true);
    }
    logger.debugf("Imported new user from LDAP to Keycloak DB. Username: [%s], Email: [%s], LDAP_ID: [%s], LDAP Entry DN: [%s]", imported.getUsername(), imported.getEmail(), ldapUser.getUuid(), userDN);
    UserModel proxy = proxy(realm, imported, ldapUser, false);
    return proxy;
}
Also used : CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) InMemoryUserAdapter(org.keycloak.storage.adapter.InMemoryUserAdapter) StorageId(org.keycloak.storage.StorageId)

Example 100 with UserModel

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

the class LDAPStorageProvider method proxy.

protected UserModel proxy(RealmModel realm, UserModel local, LDAPObject ldapObject, boolean newUser) {
    UserModel existing = userManager.getManagedProxiedUser(local.getId());
    if (existing != null) {
        return existing;
    }
    // We need to avoid having CachedUserModel as cache is upper-layer then LDAP. Hence having CachedUserModel here may cause StackOverflowError
    if (local instanceof CachedUserModel) {
        local = session.userStorageManager().getUserById(realm, local.getId());
        existing = userManager.getManagedProxiedUser(local.getId());
        if (existing != null) {
            return existing;
        }
    }
    UserModel proxied = local;
    checkDNChanged(realm, local, ldapObject);
    switch(editMode) {
        case READ_ONLY:
            if (model.isImportEnabled()) {
                proxied = new ReadonlyLDAPUserModelDelegate(local);
            } else {
                proxied = new ReadOnlyUserModelDelegate(local);
            }
            break;
        case WRITABLE:
        case UNSYNCED:
            // This check is skipped when register new user as there are many "generic" attributes always written (EG. enabled, emailVerified) and those are usually unsupported by LDAP schema
            if (!model.isImportEnabled() && !newUser) {
                UserModel readOnlyDelegate = new ReadOnlyUserModelDelegate(local, ModelException::new);
                proxied = new LDAPWritesOnlyUserModelDelegate(readOnlyDelegate, this);
            }
            break;
    }
    AtomicReference<UserModel> proxy = new AtomicReference<>(proxied);
    realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName()).sorted(ldapMappersComparator.sortAsc()).forEachOrdered(mapperModel -> {
        LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
        proxy.set(ldapMapper.proxy(ldapObject, proxy.get(), realm));
    });
    proxied = proxy.get();
    if (!model.isImportEnabled()) {
        proxied = new UpdateOnlyChangeUserModelDelegate(proxied);
    }
    userManager.setManagedProxiedUser(proxied, ldapObject);
    return proxied;
}
Also used : CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) ReadOnlyUserModelDelegate(org.keycloak.models.utils.ReadOnlyUserModelDelegate) LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) ModelException(org.keycloak.models.ModelException) CachedUserModel(org.keycloak.models.cache.CachedUserModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) UpdateOnlyChangeUserModelDelegate(org.keycloak.storage.adapter.UpdateOnlyChangeUserModelDelegate)

Aggregations

UserModel (org.keycloak.models.UserModel)383 RealmModel (org.keycloak.models.RealmModel)220 Test (org.junit.Test)126 ClientModel (org.keycloak.models.ClientModel)86 KeycloakSession (org.keycloak.models.KeycloakSession)81 CachedUserModel (org.keycloak.models.cache.CachedUserModel)52 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)43 List (java.util.List)41 UserSessionModel (org.keycloak.models.UserSessionModel)40 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)40 RoleModel (org.keycloak.models.RoleModel)39 ComponentModel (org.keycloak.component.ComponentModel)31 HashMap (java.util.HashMap)30 Response (javax.ws.rs.core.Response)29 Path (javax.ws.rs.Path)28 UserManager (org.keycloak.models.UserManager)28 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)27 Map (java.util.Map)25 GroupModel (org.keycloak.models.GroupModel)24 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)24