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());
});
}
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);
});
}
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"));
});
}
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;
}
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;
}
Aggregations