Search in sources :

Example 91 with KeycloakSession

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

the class LdapManyGroupsInitializerCommand method doRunCommand.

@Override
protected void doRunCommand(KeycloakSession session) {
    String realmName = getArg(0);
    String groupsDn = getArg(1);
    int startOffsetTopGroups = getIntArg(2);
    int topGroupsCount = getIntArg(3);
    int subgroupsInEveryGroup = getIntArg(4);
    RealmModel realm = session.realms().getRealmByName(realmName);
    List<ComponentModel> components = realm.getComponentsStream(realm.getId(), UserStorageProvider.class.getName()).collect(Collectors.toList());
    if (components.size() != 1) {
        log.errorf("Expected 1 LDAP Provider, but found: %d providers", components.size());
        throw new HandledException();
    }
    ComponentModel ldapModel = components.get(0);
    // Check that street mapper exists. It's required for now, so that "street" attribute is written to the LDAP
    ComponentModel groupMapperModel = getMapperModel(realm, ldapModel, "groupsMapper");
    // Create groups
    for (int i = startOffsetTopGroups; i < startOffsetTopGroups + topGroupsCount; i++) {
        final int iFinal = i;
        KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> {
            LDAPStorageProvider ldapProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, ldapModel);
            RealmModel appRealm = session.realms().getRealmByName(realmName);
            GroupLDAPStorageMapper groupMapper = (GroupLDAPStorageMapper) session.getProvider(LDAPStorageMapper.class, groupMapperModel);
            Set<String> childGroupDns = new HashSet<>();
            for (int j = 0; j < subgroupsInEveryGroup; j++) {
                String groupName = "group-" + iFinal + "-" + j;
                LDAPObject createdGroup = groupMapper.createLDAPGroup(groupName, new HashMap<>());
                childGroupDns.add(createdGroup.getDn().toString());
            }
            String topGroupName = "group-" + iFinal;
            Map<String, Set<String>> groupAttrs = new HashMap<>();
            groupAttrs.put("member", new HashSet<>(childGroupDns));
            groupMapper.createLDAPGroup(topGroupName, groupAttrs);
        });
    }
}
Also used : LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) GroupLDAPStorageMapper(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) RealmModel(org.keycloak.models.RealmModel) UserStorageProvider(org.keycloak.storage.UserStorageProvider) KeycloakSession(org.keycloak.models.KeycloakSession) ComponentModel(org.keycloak.component.ComponentModel) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) GroupLDAPStorageMapper(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper)

Example 92 with KeycloakSession

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

the class LdapManyObjectsInitializerCommand method doRunCommand.

@Override
protected void doRunCommand(KeycloakSession session) {
    String realmName = getArg(0);
    String groupsDn = getArg(1);
    int startOffsetUsers = getIntArg(2);
    int countUsers = getIntArg(3);
    int batchCount = 100;
    int startOffsetGroups = getIntArg(4);
    int countGroups = getIntArg(5);
    RealmModel realm = session.realms().getRealmByName(realmName);
    List<ComponentModel> components = realm.getComponentsStream(realm.getId(), UserStorageProvider.class.getName()).collect(Collectors.toList());
    if (components.size() != 1) {
        log.errorf("Expected 1 LDAP Provider, but found: %d providers", components.size());
        throw new HandledException();
    }
    ComponentModel ldapModel = components.get(0);
    // Check that street mapper exists. It's required for now, so that "street" attribute is written to the LDAP
    getMapperModel(realm, ldapModel, "streetMapper");
    ComponentModel groupMapperModel = getMapperModel(realm, ldapModel, "groupsMapper");
    // Create users
    Set<String> createdUserDNs = new HashSet<>();
    BatchTaskRunner.runInBatches(startOffsetUsers, countUsers, batchCount, session.getKeycloakSessionFactory(), (KeycloakSession kcSession, int firstIt, int countInIt) -> {
        LDAPStorageProvider ldapProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, ldapModel);
        RealmModel appRealm = session.realms().getRealmByName(realmName);
        for (int i = firstIt; i < firstIt + countInIt; i++) {
            String username = "user-" + i;
            String firstName = "John-" + i;
            String lastName = "Doe-" + i;
            String email = "user" + i + "@email.cz";
            LDAPObject createdUser = addLDAPUser(ldapProvider, appRealm, username, firstName, lastName, email, groupsDn, startOffsetGroups, countGroups);
            createdUserDNs.add(createdUser.getDn().toString());
        }
        log.infof("Created LDAP users from: %d to %d", firstIt, firstIt + countInIt - 1);
    });
    // Create groups
    BatchTaskRunner.runInBatches(startOffsetGroups, countGroups, batchCount, session.getKeycloakSessionFactory(), (KeycloakSession kcSession, int firstIt, int countInIt) -> {
        LDAPStorageProvider ldapProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, ldapModel);
        RealmModel appRealm = session.realms().getRealmByName(realmName);
        GroupLDAPStorageMapper groupMapper = (GroupLDAPStorageMapper) session.getProvider(LDAPStorageMapper.class, groupMapperModel);
        for (int i = firstIt; i < firstIt + countInIt; i++) {
            String groupName = "group" + i;
            Map<String, Set<String>> groupAttrs = new HashMap<>();
            groupAttrs.put("member", new HashSet<>(createdUserDNs));
            groupMapper.createLDAPGroup(groupName, groupAttrs);
        }
        log.infof("Created LDAP groups from: %d to %d", firstIt, firstIt + countInIt - 1);
    });
}
Also used : LDAPStorageMapper(org.keycloak.storage.ldap.mappers.LDAPStorageMapper) GroupLDAPStorageMapper(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) LDAPStorageProvider(org.keycloak.storage.ldap.LDAPStorageProvider) RealmModel(org.keycloak.models.RealmModel) UserStorageProvider(org.keycloak.storage.UserStorageProvider) KeycloakSession(org.keycloak.models.KeycloakSession) ComponentModel(org.keycloak.component.ComponentModel) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) GroupLDAPStorageMapper(org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper) HashSet(java.util.HashSet)

Example 93 with KeycloakSession

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

the class KeycloakServer method importRealm.

public void importRealm(RealmRepresentation rep) {
    KeycloakSession session = sessionFactory.create();
    ;
    session.getTransactionManager().begin();
    try {
        RealmManager manager = new RealmManager(session);
        if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
            info("Not importing realm " + rep.getRealm() + " realm already exists");
            return;
        }
        if (manager.getRealmByName(rep.getRealm()) != null) {
            info("Not importing realm " + rep.getRealm() + " realm already exists");
            return;
        }
        RealmModel realm = manager.importRealm(rep);
        info("Imported realm " + realm.getName());
        session.getTransactionManager().commit();
    } finally {
        session.close();
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) KeycloakSession(org.keycloak.models.KeycloakSession) RealmManager(org.keycloak.services.managers.RealmManager)

Example 94 with KeycloakSession

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

the class ClientPolicyProviderFactory method postInit.

@Override
public void postInit(KeycloakSessionFactory factory) {
    factory.register(event -> {
        if (event instanceof ClientRemovedEvent) {
            KeycloakSession keycloakSession = ((ClientRemovedEvent) event).getKeycloakSession();
            AuthorizationProvider provider = keycloakSession.getProvider(AuthorizationProvider.class);
            StoreFactory storeFactory = provider.getStoreFactory();
            PolicyStore policyStore = storeFactory.getPolicyStore();
            ClientModel removedClient = ((ClientRemovedEvent) event).getClient();
            ResourceServerStore resourceServerStore = storeFactory.getResourceServerStore();
            ResourceServer resourceServer = resourceServerStore.findByClient(removedClient);
            if (resourceServer != null) {
                policyStore.findByType(getId(), resourceServer.getId()).forEach(policy -> {
                    List<String> clients = new ArrayList<>();
                    for (String clientId : getClients(policy)) {
                        if (!clientId.equals(removedClient.getId())) {
                            clients.add(clientId);
                        }
                    }
                    try {
                        if (clients.isEmpty()) {
                            policyStore.delete(policy.getId());
                        } else {
                            policy.putConfig("clients", JsonSerialization.writeValueAsString(clients));
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("Error while synchronizing clients with policy [" + policy.getName() + "].", e);
                    }
                });
            }
        }
    });
}
Also used : ClientRemovedEvent(org.keycloak.models.ClientModel.ClientRemovedEvent) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ArrayList(java.util.ArrayList) IOException(java.io.IOException) StoreFactory(org.keycloak.authorization.store.StoreFactory) ClientModel(org.keycloak.models.ClientModel) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) KeycloakSession(org.keycloak.models.KeycloakSession) PolicyStore(org.keycloak.authorization.store.PolicyStore) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 95 with KeycloakSession

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

the class ClientScopePolicyProviderFactory method postInit.

@Override
public void postInit(KeycloakSessionFactory factory) {
    factory.register(event -> {
        if (event instanceof ClientScopeRemovedEvent) {
            KeycloakSession keycloakSession = ((ClientScopeRemovedEvent) event).getKeycloakSession();
            AuthorizationProvider provider = keycloakSession.getProvider(AuthorizationProvider.class);
            StoreFactory storeFactory = provider.getStoreFactory();
            PolicyStore policyStore = storeFactory.getPolicyStore();
            ClientScopeModel removedClientScope = ((ClientScopeRemovedEvent) event).getClientScope();
            Map<Policy.FilterOption, String[]> filters = new HashMap<>();
            filters.put(Policy.FilterOption.TYPE, new String[] { getId() });
            policyStore.findByResourceServer(filters, null, -1, -1).forEach(new Consumer<Policy>() {

                @Override
                public void accept(Policy policy) {
                    List<Map<String, Object>> clientScopes = new ArrayList<>();
                    for (Map<String, Object> clientScope : getClientScopes(policy)) {
                        if (!clientScope.get("id").equals(removedClientScope.getId())) {
                            Map<String, Object> updated = new HashMap<>();
                            updated.put("id", clientScope.get("id"));
                            Object required = clientScope.get("required");
                            if (required != null) {
                                updated.put("required", required);
                            }
                            clientScopes.add(updated);
                        }
                    }
                    if (clientScopes.isEmpty()) {
                        policyStore.delete(policy.getId());
                    } else {
                        try {
                            policy.putConfig("clientScopes", JsonSerialization.writeValueAsString(clientScopes));
                        } catch (IOException e) {
                            throw new RuntimeException("Error while synchronizing client scopes with policy [" + policy.getName() + "].", e);
                        }
                    }
                }
            });
        }
    });
}
Also used : Policy(org.keycloak.authorization.model.Policy) ClientScopeRemovedEvent(org.keycloak.models.ClientScopeModel.ClientScopeRemovedEvent) HashMap(java.util.HashMap) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ClientScopeModel(org.keycloak.models.ClientScopeModel) IOException(java.io.IOException) StoreFactory(org.keycloak.authorization.store.StoreFactory) KeycloakSession(org.keycloak.models.KeycloakSession) PolicyStore(org.keycloak.authorization.store.PolicyStore) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

KeycloakSession (org.keycloak.models.KeycloakSession)189 RealmModel (org.keycloak.models.RealmModel)136 UserModel (org.keycloak.models.UserModel)78 Test (org.junit.Test)76 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)61 ClientModel (org.keycloak.models.ClientModel)58 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)53 List (java.util.List)34 AtomicReference (java.util.concurrent.atomic.AtomicReference)22 Collectors (java.util.stream.Collectors)21 IOException (java.io.IOException)20 Map (java.util.Map)19 UserSessionModel (org.keycloak.models.UserSessionModel)19 ArrayList (java.util.ArrayList)18 ClientScopeModel (org.keycloak.models.ClientScopeModel)18 RoleModel (org.keycloak.models.RoleModel)18 Set (java.util.Set)16 RealmManager (org.keycloak.services.managers.RealmManager)16 HashMap (java.util.HashMap)14 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)14