Search in sources :

Example 1 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class QuarkusJpaConnectionProviderFactory method importRealm.

private void importRealm(RealmRepresentation rep, String from) {
    KeycloakSession session = factory.create();
    boolean exists = false;
    try {
        session.getTransactionManager().begin();
        try {
            RealmManager manager = new RealmManager(session);
            if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }
            if (manager.getRealmByName(rep.getRealm()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }
            if (!exists) {
                RealmModel realm = manager.importRealm(rep);
                ServicesLogger.LOGGER.importedRealm(realm.getName(), from);
            }
            session.getTransactionManager().commit();
        } catch (Throwable t) {
            session.getTransactionManager().rollback();
            if (!exists) {
                ServicesLogger.LOGGER.unableToImportRealm(t, rep.getRealm(), from);
            }
        }
    } finally {
        session.close();
    }
}
Also used : RealmManager(org.keycloak.services.managers.RealmManager)

Example 2 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class ImportUtils method importRealm.

/**
 * Fully import realm from representation, save it to model and return model of newly created realm
 *
 * @param session
 * @param rep
 * @param strategy specifies whether to overwrite or ignore existing realm or user entries
 * @param skipUserDependent If true, then import of any models, which needs users already imported in DB, will be skipped. For example authorization
 * @return newly imported realm (or existing realm if ignoreExisting is true and realm of this name already exists)
 */
public static boolean importRealm(KeycloakSession session, RealmRepresentation rep, Strategy strategy, boolean skipUserDependent) {
    String realmName = rep.getRealm();
    RealmProvider model = session.realms();
    RealmModel realm = model.getRealmByName(realmName);
    if (realm != null) {
        if (strategy == Strategy.IGNORE_EXISTING) {
            logger.infof("Realm '%s' already exists. Import skipped", realmName);
            return false;
        } else {
            logger.infof("Realm '%s' already exists. Removing it before import", realmName);
            if (Config.getAdminRealm().equals(realm.getId())) {
                // Delete all masterAdmin apps due to foreign key constraints
                model.getRealmsStream().forEach(r -> r.setMasterAdminClient(null));
            }
            // TODO: For migration between versions, it should be possible to delete just realm but keep it's users
            model.removeRealm(realm.getId());
        }
    }
    RealmManager realmManager = new RealmManager(session);
    realmManager.importRealm(rep, skipUserDependent);
    if (System.getProperty(ExportImportConfig.ACTION) != null) {
        logger.infof("Realm '%s' imported", realmName);
    }
    return true;
}
Also used : RealmModel(org.keycloak.models.RealmModel) RealmProvider(org.keycloak.models.RealmProvider) RealmManager(org.keycloak.services.managers.RealmManager)

Example 3 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class KeycloakErrorHandler method resolveRealm.

private RealmModel resolveRealm(KeycloakSession session) {
    String path = session.getContext().getUri().getPath();
    Matcher m = realmNamePattern.matcher(path);
    String realmName;
    if (m.matches()) {
        realmName = m.group(1);
    } else {
        realmName = Config.getAdminRealm();
    }
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        realm = realmManager.getRealmByName(Config.getAdminRealm());
    }
    session.getContext().setRealm(realm);
    return realm;
}
Also used : RealmModel(org.keycloak.models.RealmModel) Matcher(java.util.regex.Matcher) MediaTypeMatcher(org.keycloak.utils.MediaTypeMatcher) RealmManager(org.keycloak.services.managers.RealmManager)

Example 4 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class AdapterInstallationClientRegistrationProvider method get.

@GET
@Path("{clientId}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("clientId") String clientId) {
    event.event(EventType.CLIENT_INFO);
    ClientModel client = session.getContext().getRealm().getClientByClientId(clientId);
    auth.requireView(client, true);
    ClientManager clientManager = new ClientManager(new RealmManager(session));
    Object rep = clientManager.toInstallationRepresentation(session.getContext().getRealm(), client, session.getContext().getUri().getBaseUri());
    event.client(client.getClientId()).success();
    return Response.ok(rep).build();
}
Also used : ClientModel(org.keycloak.models.ClientModel) ClientManager(org.keycloak.services.managers.ClientManager) RealmManager(org.keycloak.services.managers.RealmManager) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 5 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class AbstractClientRegistrationProvider method create.

public ClientRepresentation create(ClientRegistrationContext context) {
    ClientRepresentation client = context.getClient();
    event.event(EventType.CLIENT_REGISTER);
    RegistrationAuth registrationAuth = auth.requireCreate(context);
    try {
        RealmModel realm = session.getContext().getRealm();
        ClientModel clientModel = ClientManager.createClient(session, realm, client);
        if (client.getDefaultRoles() != null) {
            for (String name : client.getDefaultRoles()) {
                clientModel.addDefaultRole(name);
            }
        }
        if (clientModel.isServiceAccountsEnabled()) {
            new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
        }
        if (Boolean.TRUE.equals(client.getAuthorizationServicesEnabled())) {
            RepresentationToModel.createResourceServer(clientModel, session, true);
        }
        session.clientPolicy().triggerOnEvent(new DynamicClientRegisteredContext(context, clientModel, auth.getJwt(), realm));
        ClientRegistrationPolicyManager.triggerAfterRegister(context, registrationAuth, clientModel);
        client = ModelToRepresentation.toRepresentation(clientModel, session);
        client.setSecret(clientModel.getSecret());
        String registrationAccessToken = ClientRegistrationTokenUtils.updateRegistrationAccessToken(session, clientModel, registrationAuth);
        client.setRegistrationAccessToken(registrationAccessToken);
        if (auth.isInitialAccessToken()) {
            ClientInitialAccessModel initialAccessModel = auth.getInitialAccessModel();
            session.realms().decreaseRemainingCount(realm, initialAccessModel);
        }
        client.setDirectAccessGrantsEnabled(false);
        Stream<String> defaultRolesNames = clientModel.getDefaultRolesStream();
        if (defaultRolesNames != null) {
            client.setDefaultRoles(defaultRolesNames.toArray(String[]::new));
        }
        event.client(client.getClientId()).success();
        return client;
    } catch (ModelDuplicateException e) {
        throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client Identifier in use", Response.Status.BAD_REQUEST);
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
}
Also used : ClientInitialAccessModel(org.keycloak.models.ClientInitialAccessModel) RegistrationAuth(org.keycloak.services.clientregistration.policy.RegistrationAuth) DynamicClientRegisteredContext(org.keycloak.services.clientpolicy.context.DynamicClientRegisteredContext) RealmManager(org.keycloak.services.managers.RealmManager) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) ClientManager(org.keycloak.services.managers.ClientManager) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Aggregations

RealmManager (org.keycloak.services.managers.RealmManager)47 RealmModel (org.keycloak.models.RealmModel)34 Test (org.junit.Test)19 UserModel (org.keycloak.models.UserModel)17 KeycloakSession (org.keycloak.models.KeycloakSession)16 ClientModel (org.keycloak.models.ClientModel)13 ClientManager (org.keycloak.services.managers.ClientManager)11 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)8 Path (javax.ws.rs.Path)6 UserSessionModel (org.keycloak.models.UserSessionModel)6 UserManager (org.keycloak.models.UserManager)5 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)4 LinkedList (java.util.LinkedList)3 GET (javax.ws.rs.GET)3 NotFoundException (javax.ws.rs.NotFoundException)3 Produces (javax.ws.rs.Produces)3 UserConsentModel (org.keycloak.models.UserConsentModel)3 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)3