Caches the id-to-user mapping for the evaluation in the current session (#31794)

Closes #31519

Signed-off-by: Alexander Schwartz <aschwart@redhat.com>
This commit is contained in:
Alexander Schwartz 2024-08-01 10:38:46 +02:00 committed by GitHub
parent 5284641b9d
commit aa91f60278
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -168,12 +168,23 @@ public class DefaultEvaluation implements Evaluation {
return user.isMemberOf(group);
}
private final String USER_CACHE_SESSION_ATTRIBUTE = DefaultEvaluation.class.getName() + ".userCache";
private UserModel getUser(String id, KeycloakSession session) {
RealmModel realm = session.getContext().getRealm();
UserModel user = session.users().getUserById(realm, id);
@SuppressWarnings("unchecked") HashMap<String, UserModel> cache = (HashMap<String, UserModel>) session.getAttribute(USER_CACHE_SESSION_ATTRIBUTE);
if (cache == null) {
cache = new HashMap<>();
session.setAttribute(USER_CACHE_SESSION_ATTRIBUTE, cache);
}
UserModel user = cache.get(id);
if (Objects.isNull(user)) {
user = session.users().getUserByUsername(realm ,id);
if (cache.containsKey(id)) {
return null;
}
RealmModel realm = session.getContext().getRealm();
user = session.users().getUserById(realm, id);
if (Objects.isNull(user)) {
user = session.users().getUserByUsername(realm, id);
}
if (Objects.isNull(user)) {
user = session.users().getUserByEmail(realm, id);
@ -181,6 +192,9 @@ public class DefaultEvaluation implements Evaluation {
if (Objects.isNull(user)) {
user = session.users().getServiceAccount(realm.getClientById(id));
}
}
cache.put(id, user);
return user;
}