use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class KeycloakApplication method bootstrap.
// Bootstrap master realm, import realms and create admin user.
protected ExportImportManager bootstrap() {
ExportImportManager[] exportImportManager = new ExportImportManager[1];
logger.debug("bootstrap");
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
// TODO what is the purpose of following piece of code? Leaving it as is for now.
JtaTransactionManagerLookup lookup = (JtaTransactionManagerLookup) sessionFactory.getProviderFactory(JtaTransactionManagerLookup.class);
if (lookup != null) {
if (lookup.getTransactionManager() != null) {
try {
Transaction transaction = lookup.getTransactionManager().getTransaction();
logger.debugv("bootstrap current transaction? {0}", transaction != null);
if (transaction != null) {
logger.debugv("bootstrap current transaction status? {0}", transaction.getStatus());
}
} catch (SystemException e) {
throw new RuntimeException(e);
}
}
}
// TODO up here ^^
ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
exportImportManager[0] = new ExportImportManager(session);
boolean createMasterRealm = applianceBootstrap.isNewInstall();
if (exportImportManager[0].isRunImport() && exportImportManager[0].isImportMasterIncluded()) {
createMasterRealm = false;
}
if (createMasterRealm) {
applianceBootstrap.createMasterRealm();
}
}
});
if (exportImportManager[0].isRunImport()) {
exportImportManager[0].runImport();
} else {
importRealms();
}
importAddUser();
return exportImportManager[0];
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class KeycloakApplication method importAddUser.
public void importAddUser() {
String configDir = System.getProperty("jboss.server.config.dir");
if (configDir != null) {
File addUserFile = new File(configDir + File.separator + "keycloak-add-user.json");
if (addUserFile.isFile()) {
ServicesLogger.LOGGER.imprtingUsersFrom(addUserFile);
List<RealmRepresentation> realms;
try {
realms = JsonSerialization.readValue(new FileInputStream(addUserFile), new TypeReference<List<RealmRepresentation>>() {
});
} catch (IOException e) {
ServicesLogger.LOGGER.failedToLoadUsers(e);
return;
}
for (RealmRepresentation realmRep : realms) {
for (UserRepresentation userRep : realmRep.getUsers()) {
KeycloakSession session = sessionFactory.create();
try {
session.getTransactionManager().begin();
RealmModel realm = session.realms().getRealmByName(realmRep.getRealm());
if (realm == null) {
ServicesLogger.LOGGER.addUserFailedRealmNotFound(userRep.getUsername(), realmRep.getRealm());
}
UserProvider users = session.users();
if (users.getUserByUsername(realm, userRep.getUsername()) != null) {
ServicesLogger.LOGGER.notCreatingExistingUser(userRep.getUsername());
} else {
UserModel user = users.addUser(realm, userRep.getUsername());
user.setEnabled(userRep.isEnabled());
RepresentationToModel.createCredentials(userRep, session, realm, user, false);
RepresentationToModel.createRoleMappings(userRep, user, realm);
ServicesLogger.LOGGER.addUserSuccess(userRep.getUsername(), realmRep.getRealm());
}
session.getTransactionManager().commit();
} catch (ModelDuplicateException e) {
session.getTransactionManager().rollback();
ServicesLogger.LOGGER.addUserFailedUserExists(userRep.getUsername(), realmRep.getRealm());
} catch (Throwable t) {
session.getTransactionManager().rollback();
ServicesLogger.LOGGER.addUserFailed(t, userRep.getUsername(), realmRep.getRealm());
} finally {
session.close();
}
}
}
if (!addUserFile.delete()) {
ServicesLogger.LOGGER.failedToDeleteFile(addUserFile.getAbsolutePath());
}
}
}
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class KeycloakApplication method setupScheduledTasks.
public static void setupScheduledTasks(final KeycloakSessionFactory sessionFactory) {
long interval = Config.scope("scheduled").getLong("interval", 900L) * 1000;
KeycloakSession session = sessionFactory.create();
try {
TimerProvider timer = session.getProvider(TimerProvider.class);
timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredEvents(), interval), interval, "ClearExpiredEvents");
timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredClientInitialAccessTokens(), interval), interval, "ClearExpiredClientInitialAccessTokens");
timer.schedule(new ScheduledTaskRunner(sessionFactory, new ClearExpiredUserSessions()), interval, ClearExpiredUserSessions.TASK_NAME);
new UserStorageSyncManager().bootstrapPeriodic(sessionFactory, timer);
} finally {
session.close();
}
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class RestartCookieTest method testRestartCookieBackwardsCompatible_Keycloak25.
// KEYCLOAK-5440 -- migration from Keycloak 3.1.0
@Test
public void testRestartCookieBackwardsCompatible_Keycloak25() throws IOException {
String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
try {
String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
RealmModel realm = session.realms().getRealmByName("test");
KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);
String encodedToken = new JWSBuilder().kid(activeKey.getKid()).content(cookieVal.getBytes("UTF-8")).hmac256(activeKey.getSecretKey());
return encodedToken;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
});
oauth.openLoginForm();
driver.manage().deleteAllCookies();
driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));
loginPage.login("foo", "bar");
loginPage.assertCurrent();
Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails().detail(Details.RESTART_AFTER_TIMEOUT, "true").client((String) null).assertEvent();
}
use of org.keycloak.models.KeycloakSession in project keycloak by keycloak.
the class RestartCookieTest method testRestartCookieBackwardsCompatible_Keycloak19.
// KEYCLOAK-7158 -- migration from Keycloak 1.9.8
@Test
public void testRestartCookieBackwardsCompatible_Keycloak19() throws IOException {
String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
try {
String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
RealmModel realm = session.realms().getRealmByName("test");
KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);
// There was no KID in the token in Keycloak 1.9.8
String encodedToken = new JWSBuilder().content(cookieVal.getBytes("UTF-8")).hmac256(activeKey.getSecretKey());
return encodedToken;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
});
oauth.openLoginForm();
driver.manage().deleteAllCookies();
driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));
loginPage.login("foo", "bar");
loginPage.assertCurrent();
Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails().detail(Details.RESTART_AFTER_TIMEOUT, "true").client((String) null).assertEvent();
}
Aggregations