Search in sources :

Example 31 with RealmManager

use of org.keycloak.services.managers.RealmManager 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 32 with RealmManager

use of org.keycloak.services.managers.RealmManager 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);
        }
    });
}
Also used : FilenameFilter(java.io.FilenameFilter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) RealmManager(org.keycloak.services.managers.RealmManager) ExportImportSessionTask(org.keycloak.exportimport.util.ExportImportSessionTask) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 33 with RealmManager

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

the class ImportUtils method importRealms.

public static void importRealms(KeycloakSession session, Collection<RealmRepresentation> realms, Strategy strategy) {
    boolean masterImported = false;
    // Import admin realm first
    for (RealmRepresentation realm : realms) {
        if (Config.getAdminRealm().equals(realm.getRealm())) {
            if (importRealm(session, realm, strategy, false)) {
                masterImported = true;
            }
        }
    }
    for (RealmRepresentation realm : realms) {
        if (!Config.getAdminRealm().equals(realm.getRealm())) {
            importRealm(session, realm, strategy, false);
        }
    }
    // If master was imported, we may need to re-create realm management clients
    if (masterImported) {
        session.realms().getRealmsStream().filter(realm -> realm.getMasterAdminClient() == null).forEach(realm -> {
            logger.infof("Re-created management client in master realm for realm '%s'", realm.getName());
            new RealmManager(session).setupMasterAdminManagement(realm);
        });
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) JsonParser(com.fasterxml.jackson.core.JsonParser) RealmManager(org.keycloak.services.managers.RealmManager) Logger(org.jboss.logging.Logger) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) HashMap(java.util.HashMap) Config(org.keycloak.Config) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) ArrayList(java.util.ArrayList) List(java.util.List) JsonFactory(com.fasterxml.jackson.core.JsonFactory) ExportImportConfig(org.keycloak.exportimport.ExportImportConfig) Strategy(org.keycloak.exportimport.Strategy) RealmProvider(org.keycloak.models.RealmProvider) Map(java.util.Map) JsonToken(com.fasterxml.jackson.core.JsonToken) InputStream(java.io.InputStream) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) RealmManager(org.keycloak.services.managers.RealmManager)

Example 34 with RealmManager

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

the class RealmsAdminResource method importRealm.

/**
 * Import a realm
 *
 * Imports a realm from a full representation of that realm.  Realm name must be unique.
 *
 * @param rep JSON representation of the realm
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response importRealm(final RealmRepresentation rep) {
    RealmManager realmManager = new RealmManager(session);
    AdminPermissions.realms(session, auth).requireCreateRealm();
    logger.debugv("importRealm: {0}", rep.getRealm());
    try {
        RealmModel realm = realmManager.importRealm(rep);
        grantPermissionsToRealmCreator(realm);
        URI location = AdminRoot.realmsUrl(session.getContext().getUri()).path(realm.getName()).build();
        logger.debugv("imported realm success, sending back: {0}", location.toString());
        return Response.created(location).build();
    } catch (ModelDuplicateException e) {
        logger.error("Conflict detected", e);
        return ErrorResponse.exists("Conflict detected. See logs for details");
    } catch (PasswordPolicyNotMetException e) {
        logger.error("Password policy not met for user " + e.getUsername(), e);
        if (session.getTransactionManager().isActive())
            session.getTransactionManager().setRollbackOnly();
        return ErrorResponse.error("Password policy not met. See logs for details", Response.Status.BAD_REQUEST);
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) RealmManager(org.keycloak.services.managers.RealmManager) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 35 with RealmManager

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

the class RealmsAdminResource method getRealmAdmin.

/**
 * Base path for the admin REST API for one particular realm.
 *
 * @param headers
 * @param name realm name (not id!)
 * @return
 */
@Path("{realm}")
public RealmAdminResource getRealmAdmin(@Context final HttpHeaders headers, @PathParam("realm") final String name) {
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(name);
    if (realm == null)
        throw new NotFoundException("Realm not found.");
    if (!auth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm()) && !auth.getRealm().equals(realm)) {
        throw new ForbiddenException();
    }
    AdminPermissionEvaluator realmAuth = AdminPermissions.evaluator(session, realm, auth);
    AdminEventBuilder adminEvent = new AdminEventBuilder(realm, auth, session, clientConnection);
    session.getContext().setRealm(realm);
    RealmAdminResource adminResource = new RealmAdminResource(realmAuth, realm, tokenManager, adminEvent);
    ResteasyProviderFactory.getInstance().injectProperties(adminResource);
    // resourceContext.initResource(adminResource);
    return adminResource;
}
Also used : RealmModel(org.keycloak.models.RealmModel) ForbiddenException(org.keycloak.services.ForbiddenException) NotFoundException(javax.ws.rs.NotFoundException) RealmManager(org.keycloak.services.managers.RealmManager) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) Path(javax.ws.rs.Path)

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