Java Code Examples for org.keycloak.models.utils.KeycloakModelUtils

The following examples show how to use org.keycloak.models.utils.KeycloakModelUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: keycloak   Source File: JPAPermissionTicketStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
    PermissionTicketEntity entity = new PermissionTicketEntity();

    entity.setId(KeycloakModelUtils.generateId());
    entity.setResource(ResourceAdapter.toEntity(entityManager, provider.getStoreFactory().getResourceStore().findById(resourceId, resourceServer.getId())));
    entity.setRequester(requester);
    entity.setCreatedTimestamp(System.currentTimeMillis());

    if (scopeId != null) {
        entity.setScope(ScopeAdapter.toEntity(entityManager, provider.getStoreFactory().getScopeStore().findById(scopeId, resourceServer.getId())));
    }

    entity.setOwner(entity.getResource().getOwner());
    entity.setResourceServer(ResourceServerAdapter.toEntity(entityManager, resourceServer));

    this.entityManager.persist(entity);
    this.entityManager.flush();
    PermissionTicket model = new PermissionTicketAdapter(entity, entityManager, provider.getStoreFactory());
    return model;
}
 
Example 2
@Override
public void importModel(KeycloakSessionFactory factory, Strategy strategy) throws IOException {
    logger.infof("Full importing from file %s", this.file.getAbsolutePath());

    BetterRealmRepresentation masterRealm = getMasterRealm();
    KeycloakModelUtils.runJobInTransaction(factory, session -> {
        // Import master realm first, if exists
        if (masterRealm != null) {
            importRealm(session, masterRealm, strategy);
        }
        realmReps.stream().filter(r -> r != masterRealm).forEach(r -> importRealm(session, r, strategy));

        if (masterRealm != null) {
            // If master was imported, we may need to re-create realm management clients
            for (RealmModel realm : session.realms().getRealms()) {
                if (realm.getMasterAdminClient() == null) {
                    logger.infof("Re-created management client in master realm for realm '%s'", realm.getName());
                    new RealmManager(session).setupMasterAdminManagement(realm);
                }
            }
        }
    });
}
 
Example 3
Source Project: keycloak   Source File: MigrationUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void migrateOldOfflineToken(KeycloakSession session, RealmModel realm, ClientModel client, UserModel user) throws OAuthErrorException {
    ClientScopeModel offlineScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
    if (offlineScope == null) {
        throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Offline Access scope not found");
    }

    if (client.isConsentRequired()) {
        // Automatically add consents for client and for offline_access. We know that both were defacto approved by user already and offlineSession is still valid
        UserConsentModel consent = session.users().getConsentByClient(realm, user.getId(), client.getId());
        if (consent != null) {
            if (client.isDisplayOnConsentScreen()) {
                consent.addGrantedClientScope(client);
            }
            if (offlineScope.isDisplayOnConsentScreen()) {
                consent.addGrantedClientScope(offlineScope);
            }
            session.users().updateConsent(realm, user.getId(), consent);
        }
    }
}
 
Example 4
Source Project: keycloak   Source File: MigrateTo1_8_0.java    License: Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(RealmModel realm) {
    List<UserStorageProviderModel> federationProviders = realm.getUserStorageProviders();
    for (UserStorageProviderModel fedProvider : federationProviders) {

        if (fedProvider.getProviderId().equals(LDAPConstants.LDAP_PROVIDER)) {

            if (isActiveDirectory(fedProvider)) {
                // Create mapper for MSAD account controls
                if (getMapperByName(realm, fedProvider, "MSAD account controls") == null) {
                    ComponentModel mapperModel = KeycloakModelUtils.createComponentModel("MSAD account controls", fedProvider.getId(), LDAPConstants.MSAD_USER_ACCOUNT_CONTROL_MAPPER, "org.keycloak.storage.ldap.mappers.LDAPStorageMapper");
                    realm.addComponentModel(mapperModel);
                }
            }
        }
    }
}
 
Example 5
Source Project: keycloak   Source File: UserStorageSyncManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check federationProviderModel of all realms and possibly start periodic sync for them
 *
 * @param sessionFactory
 * @param timer
 */
public void bootstrapPeriodic(final KeycloakSessionFactory sessionFactory, final TimerProvider timer) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            List<RealmModel> realms = session.realms().getRealmsWithProviderType(UserStorageProvider.class);
            for (final RealmModel realm : realms) {
                List<UserStorageProviderModel> providers = realm.getUserStorageProviders();
                for (final UserStorageProviderModel provider : providers) {
                    UserStorageProviderFactory factory = (UserStorageProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, provider.getProviderId());
                    if (factory instanceof ImportSynchronization && provider.isImportEnabled()) {
                        refreshPeriodicSyncForProvider(sessionFactory, timer, provider, realm.getId());
                    }
                }
            }

            ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
            clusterProvider.registerListener(USER_STORAGE_TASK_KEY, new UserStorageClusterListener(sessionFactory));
        }
    });
}
 
Example 6
Source Project: keycloak   Source File: LDAPTestUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void addOrUpdateGroupMapper(RealmModel realm, ComponentModel providerModel, LDAPGroupMapperMode mode, String descriptionAttrName, String... otherConfigOptions) {
    ComponentModel mapperModel = getSubcomponentByName(realm, providerModel, "groupsMapper");
    if (mapperModel != null) {
        mapperModel.getConfig().putSingle(GroupMapperConfig.MODE, mode.toString());
        updateGroupMapperConfigOptions(mapperModel, otherConfigOptions);
        realm.updateComponent(mapperModel);
    } else {
        String baseDn = providerModel.getConfig().getFirst(LDAPConstants.BASE_DN);
        mapperModel = KeycloakModelUtils.createComponentModel("groupsMapper", providerModel.getId(), GroupLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
                GroupMapperConfig.GROUPS_DN, "ou=Groups," + baseDn,
                GroupMapperConfig.MAPPED_GROUP_ATTRIBUTES, descriptionAttrName,
                GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, "true",
                GroupMapperConfig.MODE, mode.toString(),
                GroupMapperConfig.LDAP_GROUPS_PATH, "/");
        updateGroupMapperConfigOptions(mapperModel, otherConfigOptions);
        realm.addComponentModel(mapperModel);
    }
}
 
Example 7
/**
 * Generate a new certificate with new key pair
 *
 * @return
 */
@POST
@NoCache
@Path("generate")
@Produces(MediaType.APPLICATION_JSON)
public CertificateRepresentation generate() {
    auth.clients().requireConfigure(client);

    CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(client.getClientId());

    CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);

    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();

    return info;
}
 
Example 8
Source Project: keycloak   Source File: RealmAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IdentityProviderMapperModel addIdentityProviderMapper(IdentityProviderMapperModel model) {
    if (getIdentityProviderMapperByName(model.getIdentityProviderAlias(), model.getName()) != null) {
        throw new RuntimeException("identity provider mapper name must be unique per identity provider");
    }
    String id = KeycloakModelUtils.generateId();
    IdentityProviderMapperEntity entity = new IdentityProviderMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setIdentityProviderAlias(model.getIdentityProviderAlias());
    entity.setIdentityProviderMapper(model.getIdentityProviderMapper());
    entity.setRealm(this.realm);
    entity.setConfig(model.getConfig());

    em.persist(entity);
    this.realm.getIdentityProviderMappers().add(entity);
    return entityToModel(entity);
}
 
Example 9
Source Project: keycloak   Source File: ImpersonationConstants.java    License: Apache License 2.0 6 votes vote down vote up
public static void setupMasterRealmRole(RealmProvider model, RealmModel realm) {
    RealmModel adminRealm;
    RoleModel adminRole;

    if (realm.getName().equals(Config.getAdminRealm())) {
        adminRealm = realm;
        adminRole = realm.getRole(AdminRoles.ADMIN);
    } else {
        adminRealm = model.getRealm(Config.getAdminRealm());
        adminRole = adminRealm.getRole(AdminRoles.ADMIN);
    }
    ClientModel realmAdminApp = adminRealm.getClientByClientId(KeycloakModelUtils.getMasterRealmAdminApplicationClientId(realm.getName()));
    if (realmAdminApp.getRole(IMPERSONATION_ROLE) != null) return;
    RoleModel impersonationRole = realmAdminApp.addRole(IMPERSONATION_ROLE);
    impersonationRole.setDescription("${role_" + IMPERSONATION_ROLE + "}");
    adminRole.addCompositeRole(impersonationRole);
}
 
Example 10
Source Project: keycloak   Source File: UserStorageSyncManager.java    License: Apache License 2.0 6 votes vote down vote up
private void updateLastSyncInterval(final KeycloakSessionFactory sessionFactory, UserStorageProviderModel provider, final String realmId) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            RealmModel persistentRealm = session.realms().getRealm(realmId);
            List<UserStorageProviderModel> persistentFedProviders = persistentRealm.getUserStorageProviders();
            for (UserStorageProviderModel persistentFedProvider : persistentFedProviders) {
                if (provider.getId().equals(persistentFedProvider.getId())) {
                    // Update persistent provider in DB
                    int lastSync = Time.currentTime();
                    persistentFedProvider.setLastSync(lastSync);
                    persistentRealm.updateComponent(persistentFedProvider);

                    // Update "cached" reference
                    provider.setLastSync(lastSync);
                }
            }
        }

    });
}
 
Example 11
Source Project: keycloak   Source File: AdminEventAuthDetailsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmBuilder realm = RealmBuilder.create().name("test").testEventListener();
    client1Uuid = KeycloakModelUtils.generateId();
    realm.client(ClientBuilder.create().id(client1Uuid).clientId("client1").publicClient().directAccessGrants());

    admin1Id =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(admin1Id).username("admin1").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN));

    admin2Id =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(admin2Id).username("admin2").password("password").role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN));

    appUserId =  KeycloakModelUtils.generateId();
    realm.user(UserBuilder.create().id(appUserId).username("app-user").password("password"));

    testRealms.add(realm.build());
}
 
Example 12
Source Project: keycloak   Source File: FineGrainAdminUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
public static void invokeDelete(KeycloakSession session)  {
    RealmModel realm = session.realms().getRealmByName(TEST);
    AdminPermissionManagement management = AdminPermissions.management(session, realm);
    List<Resource> byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(5, byResourceServer.size());
    RoleModel removedRole = realm.getRole("removedRole");
    realm.removeRole(removedRole);
    ClientModel client = realm.getClientByClientId("removedClient");
    RoleModel removedClientRole = client.getRole("removedClientRole");
    client.removeRole(removedClientRole);
    GroupModel group = KeycloakModelUtils.findGroupByPath(realm, "removedGroup");
    realm.removeGroup(group);
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(2, byResourceServer.size());
    realm.removeClient(client.getId());
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(1, byResourceServer.size());
    management.users().setPermissionsEnabled(false);
    Resource userResource = management.authz().getStoreFactory().getResourceStore().findByName("Users", management.realmResourceServer().getId());
    Assert.assertNull(userResource);
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(0, byResourceServer.size());
}
 
Example 13
Source Project: keycloak   Source File: ConditionalRoleAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchCondition(AuthenticationFlowContext context) {
    UserModel user = context.getUser();
    RealmModel realm = context.getRealm();
    AuthenticatorConfigModel authConfig = context.getAuthenticatorConfig();
    if (user != null && authConfig!=null && authConfig.getConfig()!=null) {
        String requiredRole = authConfig.getConfig().get(ConditionalRoleAuthenticatorFactory.CONDITIONAL_USER_ROLE);
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, requiredRole);
        if (role == null) {
            logger.errorv("Invalid role name submitted: {0}", requiredRole);
            return false;
        }
        return user.hasRole(role);
    }
    return false;
}
 
Example 14
Source Project: keycloak   Source File: ClientAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
    if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
        throw new ModelDuplicateException("Protocol mapper name must be unique per protocol");
    }
    String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
    ProtocolMapperEntity entity = new ProtocolMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setProtocol(model.getProtocol());
    entity.setProtocolMapper(model.getProtocolMapper());
    entity.setClient(this.entity);
    entity.setConfig(model.getConfig());

    em.persist(entity);
    this.entity.getProtocolMappers().add(entity);
    return entityToModel(entity);
}
 
Example 15
Source Project: keycloak   Source File: RealmAdapter.java    License: Apache License 2.0 6 votes vote down vote up
protected void setConfig(ComponentModel model, ComponentEntity c) {
    c.getComponentConfigs().clear();
    for (String key : model.getConfig().keySet()) {
        List<String> vals = model.getConfig().get(key);
        if (vals == null) {
            continue;
        }
        for (String val : vals) {
            ComponentConfigEntity config = new ComponentConfigEntity();
            config.setId(KeycloakModelUtils.generateId());
            config.setName(key);
            config.setValue(val);
            config.setComponent(c);
            c.getComponentConfigs().add(config);
        }
    }
}
 
Example 16
Source Project: keycloak   Source File: ClientScopeAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
    if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
        throw new ModelDuplicateException("Protocol mapper name must be unique per protocol");
    }
    String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
    ProtocolMapperEntity entity = new ProtocolMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setProtocol(model.getProtocol());
    entity.setProtocolMapper(model.getProtocolMapper());
    entity.setClientScope(this.entity);
    entity.setConfig(model.getConfig());

    em.persist(entity);
    this.entity.getProtocolMappers().add(entity);
    return entityToModel(entity);
}
 
Example 17
Source Project: keycloak   Source File: AuthenticationManager.java    License: Apache License 2.0 6 votes vote down vote up
private static List<ClientScopeModel> getClientScopesToApproveOnConsentScreen(RealmModel realm, UserConsentModel grantedConsent,
                                                                              AuthenticationSessionModel authSession) {
    // Client Scopes to be displayed on consent screen
    List<ClientScopeModel> clientScopesToDisplay = new LinkedList<>();

    for (String clientScopeId : authSession.getClientScopes()) {
        ClientScopeModel clientScope = KeycloakModelUtils.findClientScopeById(realm, authSession.getClient(), clientScopeId);

        if (clientScope == null || !clientScope.isDisplayOnConsentScreen()) {
            continue;
        }

        // Check if consent already granted by user
        if (grantedConsent == null || !grantedConsent.isClientScopeGranted(clientScope)) {
            clientScopesToDisplay.add(clientScope);
        }
    }

    return clientScopesToDisplay;
}
 
Example 18
Source Project: keycloak   Source File: RealmManager.java    License: Apache License 2.0 6 votes vote down vote up
private void setupRealmAdminManagement(RealmModel realm) {
    if (realm.getName().equals(Config.getAdminRealm())) { return; } // don't need to do this for master realm

    String realmAdminClientId = getRealmAdminClientId(realm);
    ClientModel realmAdminClient = realm.getClientByClientId(realmAdminClientId);
    if (realmAdminClient == null) {
        realmAdminClient = KeycloakModelUtils.createClient(realm, realmAdminClientId);
        realmAdminClient.setName("${client_" + realmAdminClientId + "}");
    }
    RoleModel adminRole = realmAdminClient.addRole(AdminRoles.REALM_ADMIN);
    adminRole.setDescription("${role_" + AdminRoles.REALM_ADMIN + "}");
    realmAdminClient.setBearerOnly(true);
    realmAdminClient.setFullScopeAllowed(false);
    realmAdminClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

    for (String r : AdminRoles.ALL_REALM_ROLES) {
        addAndSetAdminRole(r, realmAdminClient, adminRole);
    }
    addQueryCompositeRoles(realmAdminClient);
}
 
Example 19
Source Project: keycloak   Source File: EntitlementAPITest.java    License: Apache License 2.0 6 votes vote down vote up
@NotNull
private JSPolicyRepresentation createOnlyOwnerPolicy() {
    JSPolicyRepresentation onlyOwnerPolicy = new JSPolicyRepresentation();

    onlyOwnerPolicy.setName(KeycloakModelUtils.generateId());
    onlyOwnerPolicy.setCode("var context = $evaluation.getContext();\n" +
            "var identity = context.getIdentity();\n" +
            "var permission = $evaluation.getPermission();\n" +
            "var resource = permission.getResource();\n" +
            "\n" +
            "if (resource) {\n" +
            "    if (resource.owner == identity.id) {\n" +
            "        $evaluation.grant();\n" +
            "    }\n" +
            "}");

    return onlyOwnerPolicy;
}
 
Example 20
Source Project: keycloak   Source File: MultipleStepsExportProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void exportModel(KeycloakSessionFactory factory) throws IOException {
    final RealmsHolder holder = new RealmsHolder();

    KeycloakModelUtils.runJobInTransaction(factory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            List<RealmModel> realms = session.realms().getRealms();
            holder.realms = realms;
        }

    });

    for (RealmModel realm : holder.realms) {
        exportRealmImpl(factory, realm.getName());
    }
}
 
Example 21
Source Project: keycloak   Source File: SingleFileExportProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void exportModel(KeycloakSessionFactory factory) throws IOException {
    logger.infof("Exporting model into file %s", this.file.getAbsolutePath());
    KeycloakModelUtils.runJobInTransaction(factory, new ExportImportSessionTask() {

        @Override
        protected void runExportImportTask(KeycloakSession session) throws IOException {
            List<RealmModel> realms = session.realms().getRealms();
            List<RealmRepresentation> reps = new ArrayList<>();
            for (RealmModel realm : realms) {
                reps.add(ExportUtils.exportRealm(session, realm, true, true));
            }

            writeToFile(reps);
        }

    });

}
 
Example 22
Source Project: keycloak   Source File: JPAScopeStore.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Scope create(String id, final String name, final ResourceServer resourceServer) {
    ScopeEntity entity = new ScopeEntity();

    if (id == null) {
        entity.setId(KeycloakModelUtils.generateId());
    } else {
        entity.setId(id);
    }

    entity.setName(name);
    entity.setResourceServer(ResourceServerAdapter.toEntity(entityManager, resourceServer));

    this.entityManager.persist(entity);
    this.entityManager.flush();

    return new ScopeAdapter(entity, entityManager, provider.getStoreFactory());
}
 
Example 23
Source Project: keycloak   Source File: AbstractCommand.java    License: Apache License 2.0 6 votes vote down vote up
public void runCommand() {
    try {
        KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

            @Override
            public void run(KeycloakSession session) {
                doRunCommand(session);
            }

        });
    } catch (HandledException handled) {
        // Fine to ignore. Was handled already
    } catch (RuntimeException e) {
        log.error("Error occured during command. ", e);
    }
}
 
Example 24
Source Project: keycloak   Source File: JpaUserFederatedStorageProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CredentialModel createCredential(RealmModel realm, String userId, CredentialModel cred) {
    createIndex(realm, userId);
    FederatedUserCredentialEntity entity = new FederatedUserCredentialEntity();
    String id = cred.getId() == null ? KeycloakModelUtils.generateId() : cred.getId();
    entity.setId(id);
    entity.setCreatedDate(cred.getCreatedDate());
    entity.setType(cred.getType());
    entity.setCredentialData(cred.getCredentialData());
    entity.setSecretData(cred.getSecretData());
    entity.setUserLabel(cred.getUserLabel());

    entity.setUserId(userId);
    entity.setRealmId(realm.getId());
    entity.setStorageProviderId(new StorageId(userId).getProviderId());

    //add in linkedlist to last position
    List<FederatedUserCredentialEntity> credentials = getStoredCredentialEntities(userId);
    int priority = credentials.isEmpty() ? JpaUserCredentialStore.PRIORITY_DIFFERENCE : credentials.get(credentials.size() - 1).getPriority() + JpaUserCredentialStore.PRIORITY_DIFFERENCE;
    entity.setPriority(priority);

    em.persist(entity);
    return toModel(entity);
}
 
Example 25
@Override
public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel config) throws ComponentValidationException {
    String roleName = config.getConfig().getFirst(HardcodedLDAPRoleStorageMapper.ROLE);
    if (roleName == null) {
        throw new ComponentValidationException("Role can't be null");
    }
    RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName);
    if (role == null) {
        throw new ComponentValidationException("There is no role corresponding to configured value");
    }
}
 
Example 26
Source Project: keycloak   Source File: RealmAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean removeClientScope(String id) {
    if (id == null) return false;
    ClientScopeModel clientScope = getClientScopeById(id);
    if (clientScope == null) return false;
    if (KeycloakModelUtils.isClientScopeUsed(this, clientScope)) {
        throw new ModelException("Cannot remove client scope, it is currently in use");
    }

    ClientScopeEntity clientScopeEntity = null;
    Iterator<ClientScopeEntity> it = realm.getClientScopes().iterator();
    while (it.hasNext()) {
        ClientScopeEntity ae = it.next();
        if (ae.getId().equals(id)) {
            clientScopeEntity = ae;
            it.remove();
            break;
        }
    }
    if (clientScope == null) {
        return false;
    }

    session.users().preRemove(clientScope);

    em.createNamedQuery("deleteClientScopeRoleMappingByClientScope").setParameter("clientScope", clientScopeEntity).executeUpdate();
    em.flush();
    em.remove(clientScopeEntity);
    em.flush();


    return true;
}
 
Example 27
@Test
public void test_convert() throws Exception {
    AAGUIDConverter converter = new AAGUIDConverter();
    byte[] aaguidBytes = converter.convertToDatabaseColumn(new AAGUID(KeycloakModelUtils.generateSecret(16)));
    AAGUID aaguidEntity = converter.convertToEntityAttribute(aaguidBytes);
    Assert.assertArrayEquals(aaguidBytes, converter.convertToDatabaseColumn(aaguidEntity));
}
 
Example 28
protected void update(Connection connection, String schema, KeycloakSession session, JpaUpdaterProvider updater) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), new KeycloakSessionTask() {
        @Override
        public void run(KeycloakSession lockSession) {
            DBLockManager dbLockManager = new DBLockManager(lockSession);
            DBLockProvider dbLock2 = dbLockManager.getDBLock();
            dbLock2.waitForLock(DBLockProvider.Namespace.DATABASE);
            try {
                updater.update(connection, schema);
            } finally {
                dbLock2.releaseLock();
            }
        }
    });
}
 
Example 29
Source Project: keycloak   Source File: LDAPTestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ComponentModel addUserAttributeMapper(RealmModel realm, ComponentModel providerModel, String mapperName, String userModelAttributeName, String ldapAttributeName) {
    ComponentModel mapperModel = KeycloakModelUtils.createComponentModel(mapperName, providerModel.getId(), UserAttributeLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
            UserAttributeLDAPStorageMapper.USER_MODEL_ATTRIBUTE, userModelAttributeName,
            UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, ldapAttributeName,
            UserAttributeLDAPStorageMapper.READ_ONLY, "false",
            UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, "false",
            UserAttributeLDAPStorageMapper.IS_MANDATORY_IN_LDAP, "false");
    return realm.addComponentModel(mapperModel);
}
 
Example 30
Source Project: keycloak   Source File: ExampleServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CompanyRepresentation addCompany(CompanyRepresentation company) {
    Company entity = new Company();
    String id = company.getId()==null ?  KeycloakModelUtils.generateId() : company.getId();
    entity.setId(id);
    entity.setName(company.getName());
    entity.setRealmId(getRealm().getId());
    getEntityManager().persist(entity);

    company.setId(id);
    return company;
}