use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class RolePolicyProviderFactory method updateRoles.
private void updateRoles(Policy policy, AuthorizationProvider authorization, Set<RolePolicyRepresentation.RoleDefinition> roles) {
KeycloakSession session = authorization.getKeycloakSession();
RealmModel realm = authorization.getRealm();
Set<RolePolicyRepresentation.RoleDefinition> updatedRoles = new HashSet<>();
if (roles != null) {
for (RolePolicyRepresentation.RoleDefinition definition : roles) {
String roleName = definition.getId();
String clientId = null;
int clientIdSeparator = roleName.indexOf("/");
if (clientIdSeparator != -1) {
clientId = roleName.substring(0, clientIdSeparator);
roleName = roleName.substring(clientIdSeparator + 1);
}
RoleModel role;
if (clientId == null) {
role = realm.getRole(roleName);
if (role == null) {
role = realm.getRoleById(roleName);
}
} else {
ClientModel client = realm.getClientByClientId(clientId);
if (client == null) {
throw new RuntimeException("Client with id [" + clientId + "] not found.");
}
role = client.getRole(roleName);
}
if (role == null) {
throw new RuntimeException("Error while updating policy [" + policy.getName() + "]. Role [" + roleName + "] could not be found.");
}
definition.setId(role.getId());
updatedRoles.add(definition);
}
}
try {
policy.putConfig("roles", JsonSerialization.writeValueAsString(updatedRoles));
} catch (IOException cause) {
throw new RuntimeException("Failed to serialize roles", cause);
}
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class LDAPStorageProviderFactory method createQuery.
/**
* !! This function must be called from try-with-resources block, otherwise Vault secrets may be leaked !!
* @param sessionFactory
* @param realmId
* @param model
* @return
*/
private LDAPQuery createQuery(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel model) {
class QueryHolder {
LDAPQuery query;
}
final QueryHolder queryHolder = new QueryHolder();
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealm(realmId));
LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, model);
RealmModel realm = session.realms().getRealm(realmId);
queryHolder.query = LDAPUtils.createQueryForUserSearch(ldapFedProvider, realm);
}
});
return queryHolder.query;
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class LDAPStorageProviderFactory method importLdapUsers.
protected SynchronizationResult importLdapUsers(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel fedModel, List<LDAPObject> ldapUsers) {
final SynchronizationResult syncResult = new SynchronizationResult();
class BooleanHolder {
private boolean value = true;
}
final BooleanHolder exists = new BooleanHolder();
for (final LDAPObject ldapUser : ldapUsers) {
try {
// Process each user in it's own transaction to avoid global fail
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, fedModel);
RealmModel currentRealm = session.realms().getRealm(realmId);
session.getContext().setRealm(currentRealm);
String username = LDAPUtils.getUsername(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
exists.value = true;
LDAPUtils.checkUuid(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
UserModel currentUserLocal = session.userLocalStorage().getUserByUsername(currentRealm, username);
Optional<UserModel> userModelOptional = session.userLocalStorage().searchForUserByUserAttributeStream(currentRealm, LDAPConstants.LDAP_ID, ldapUser.getUuid()).findFirst();
if (!userModelOptional.isPresent() && currentUserLocal == null) {
// Add new user to Keycloak
exists.value = false;
ldapFedProvider.importUserFromLDAP(session, currentRealm, ldapUser);
syncResult.increaseAdded();
} else {
UserModel currentUser = userModelOptional.isPresent() ? userModelOptional.get() : currentUserLocal;
if ((fedModel.getId().equals(currentUser.getFederationLink())) && (ldapUser.getUuid().equals(currentUser.getFirstAttribute(LDAPConstants.LDAP_ID)))) {
// Update keycloak user
LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(ldapFedProvider.getLdapIdentityStore().getConfig());
currentRealm.getComponentsStream(fedModel.getId(), LDAPStorageMapper.class.getName()).sorted(ldapMappersComparator.sortDesc()).forEachOrdered(mapperModel -> {
LDAPStorageMapper ldapMapper = ldapFedProvider.getMapperManager().getMapper(mapperModel);
ldapMapper.onImportUserFromLDAP(ldapUser, currentUser, currentRealm, false);
});
UserCache userCache = session.userCache();
if (userCache != null) {
userCache.evict(currentRealm, currentUser);
}
logger.debugf("Updated user from LDAP: %s", currentUser.getUsername());
syncResult.increaseUpdated();
} else {
logger.warnf("User with ID '%s' is not updated during sync as he already exists in Keycloak database but is not linked to federation provider '%s'", ldapUser.getUuid(), fedModel.getName());
syncResult.increaseFailed();
}
}
}
});
} catch (ModelException me) {
logger.error("Failed during import user from LDAP", me);
syncResult.increaseFailed();
// Remove user if we already added him during this transaction
if (!exists.value) {
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, fedModel);
RealmModel currentRealm = session.realms().getRealm(realmId);
session.getContext().setRealm(currentRealm);
String username = null;
try {
username = LDAPUtils.getUsername(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
} catch (ModelException ignore) {
}
if (username != null) {
UserModel existing = session.userLocalStorage().getUserByUsername(currentRealm, username);
if (existing != null) {
UserCache userCache = session.userCache();
if (userCache != null) {
userCache.evict(currentRealm, existing);
}
session.userLocalStorage().removeUser(currentRealm, existing);
}
}
}
});
}
}
}
return syncResult;
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class DefaultEvaluation method createRealm.
private Realm createRealm() {
return new Realm() {
@Override
public boolean isUserInGroup(String id, String groupId, boolean checkParent) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
UserModel user = getUser(id, session);
if (Objects.isNull(user)) {
return false;
}
RealmModel realm = session.getContext().getRealm();
GroupModel group = KeycloakModelUtils.findGroupByPath(realm, groupId);
if (Objects.isNull(group)) {
return false;
}
if (checkParent) {
return RoleUtils.isMember(user.getGroupsStream(), group);
}
return user.isMemberOf(group);
}
private UserModel getUser(String id, KeycloakSession session) {
RealmModel realm = session.getContext().getRealm();
UserModel 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);
}
if (Objects.isNull(user)) {
user = session.users().getServiceAccount(realm.getClientById(id));
}
return user;
}
@Override
public boolean isUserInRealmRole(String id, String roleName) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
UserModel user = getUser(id, session);
if (Objects.isNull(user)) {
return false;
}
Stream<RoleModel> roleMappings = user.getRoleMappingsStream().filter(isNotClientRole);
return RoleUtils.hasRole(roleMappings, session.getContext().getRealm().getRole(roleName));
}
@Override
public boolean isUserInClientRole(String id, String clientId, String roleName) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
RealmModel realm = session.getContext().getRealm();
UserModel user = getUser(id, session);
if (Objects.isNull(user)) {
return false;
}
Set<RoleModel> roleMappings = user.getRoleMappingsStream().filter(RoleModel::isClientRole).filter(role -> Objects.equals(((ClientModel) role.getContainer()).getClientId(), clientId)).collect(Collectors.toSet());
if (roleMappings.isEmpty()) {
return false;
}
RoleModel role = realm.getClientById(roleMappings.iterator().next().getContainer().getId()).getRole(roleName);
if (Objects.isNull(role)) {
return false;
}
return RoleUtils.hasRole(roleMappings, role);
}
@Override
public boolean isGroupInRole(String id, String role) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
RealmModel realm = session.getContext().getRealm();
GroupModel group = KeycloakModelUtils.findGroupByPath(realm, id);
return RoleUtils.hasRoleFromGroup(group, realm.getRole(role), false);
}
@Override
public List<String> getUserRealmRoles(String id) {
return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(isNotClientRole).map(RoleModel::getName).collect(Collectors.toList());
}
@Override
public List<String> getUserClientRoles(String id, String clientId) {
return getUser(id, authorizationProvider.getKeycloakSession()).getRoleMappingsStream().filter(RoleModel::isClientRole).map(RoleModel::getName).collect(Collectors.toList());
}
@Override
public List<String> getUserGroups(String id) {
return getUser(id, authorizationProvider.getKeycloakSession()).getGroupsStream().map(ModelToRepresentation::buildGroupPath).collect(Collectors.toList());
}
@Override
public Map<String, List<String>> getUserAttributes(String id) {
return Collections.unmodifiableMap(getUser(id, authorizationProvider.getKeycloakSession()).getAttributes());
}
};
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class DirImportProvider method importRealm.
@Override
public void importRealm(KeycloakSessionFactory factory, final String realmName, final Strategy strategy) throws IOException {
File realmFile = new File(this.rootDirectory + File.separator + realmName + "-realm.json");
File[] userFiles = this.rootDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.matches(realmName + "-users-[0-9]+\\.json");
}
});
File[] federatedUserFiles = this.rootDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.matches(realmName + "-federated-users-[0-9]+\\.json");
}
});
// Import realm first
FileInputStream is = new FileInputStream(realmFile);
final RealmRepresentation realmRep = JsonSerialization.readValue(is, RealmRepresentation.class);
final AtomicBoolean realmImported = new AtomicBoolean();
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
public void runExportImportTask(KeycloakSession session) throws IOException {
boolean imported = ImportUtils.importRealm(session, realmRep, strategy, true);
realmImported.set(imported);
}
});
if (realmImported.get()) {
// Import users
for (final File userFile : userFiles) {
final FileInputStream fis = new FileInputStream(userFile);
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
protected void runExportImportTask(KeycloakSession session) throws IOException {
ImportUtils.importUsersFromStream(session, realmName, JsonSerialization.mapper, fis);
logger.infof("Imported users from %s", userFile.getAbsolutePath());
}
});
}
for (final File userFile : federatedUserFiles) {
final FileInputStream fis = new FileInputStream(userFile);
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
protected void runExportImportTask(KeycloakSession session) throws IOException {
ImportUtils.importFederatedUsersFromStream(session, realmName, JsonSerialization.mapper, fis);
logger.infof("Imported federated users from %s", userFile.getAbsolutePath());
}
});
}
}
// Import authorization and initialize service accounts last, as they require users already in DB
KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {
@Override
public void runExportImportTask(KeycloakSession session) throws IOException {
RealmManager realmManager = new RealmManager(session);
realmManager.setupClientServiceAccountsAndAuthorizationOnImport(realmRep, false);
}
});
}
Aggregations