Search in sources :

Example 11 with UserManager

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

the class KerberosFederationProvider method findOrCreateAuthenticatedUser.

/**
 * Called after successful authentication
 *
 * @param realm realm
 * @param username username without realm prefix
 * @return user if found or successfully created. Null if user with same username already exists, but is not linked to this provider
 */
protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, String username) {
    UserModel user = session.userLocalStorage().getUserByUsername(realm, username);
    if (user != null) {
        // make sure we get a cached instance
        user = session.users().getUserById(realm, user.getId());
        logger.debug("Kerberos authenticated user " + username + " found in Keycloak storage");
        if (!model.getId().equals(user.getFederationLink())) {
            logger.warn("User with username " + username + " already exists, but is not linked to provider [" + model.getName() + "]");
            return null;
        } else {
            UserModel proxied = validate(realm, user);
            if (proxied != null) {
                return proxied;
            } else {
                logger.warn("User with username " + username + " already exists and is linked to provider [" + model.getName() + "] but kerberos principal is not correct. Kerberos principal on user is: " + user.getFirstAttribute(KERBEROS_PRINCIPAL));
                logger.warn("Will re-create user");
                new UserManager(session).removeUser(realm, user, session.userLocalStorage());
            }
        }
    }
    logger.debug("Kerberos authenticated user " + username + " not in Keycloak storage. Creating him");
    return importUserToKeycloak(realm, username);
}
Also used : UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager)

Example 12 with UserManager

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

the class LDAPStorageProvider method findOrCreateAuthenticatedUser.

/**
 * Called after successful kerberos authentication
 *
 * @param realm realm
 * @param username username without realm prefix
 * @return finded or newly created user
 */
protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, String username) {
    UserModel user = session.userLocalStorage().getUserByUsername(realm, username);
    if (user != null) {
        logger.debugf("Kerberos authenticated user [%s] found in Keycloak storage", username);
        if (!model.getId().equals(user.getFederationLink())) {
            logger.warnf("User with username [%s] already exists, but is not linked to provider [%s]", username, model.getName());
            return null;
        } else {
            LDAPObject ldapObject = loadAndValidateUser(realm, user);
            if (ldapObject != null) {
                return proxy(realm, user, ldapObject, false);
            } else {
                logger.warnf("User with username [%s] aready exists and is linked to provider [%s] but is not valid. Stale LDAP_ID on local user is: %s", username, model.getName(), user.getFirstAttribute(LDAPConstants.LDAP_ID));
                logger.warn("Will re-create user");
                UserCache userCache = session.userCache();
                if (userCache != null) {
                    userCache.evict(realm, user);
                }
                new UserManager(session).removeUser(realm, user, session.userLocalStorage());
            }
        }
    }
    // Creating user to local storage
    logger.debugf("Kerberos authenticated user [%s] not in Keycloak storage. Creating him", username);
    return getUserByUsername(realm, username);
}
Also used : CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) UserCache(org.keycloak.models.cache.UserCache)

Example 13 with UserManager

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

the class UserStorageManager method deleteInvalidUser.

protected void deleteInvalidUser(final RealmModel realm, final UserModel user) {
    String userId = user.getId();
    String userName = user.getUsername();
    UserCache userCache = session.userCache();
    if (userCache != null) {
        userCache.evict(realm, user);
    }
    // This needs to be running in separate transaction because removing the user may end up with throwing
    // PessimisticLockException which also rollbacks Jpa transaction, hence when it is running in current transaction
    // it will become not usable for all consequent jpa calls. It will end up with Transaction is in rolled back
    // state error
    runJobInTransaction(session.getKeycloakSessionFactory(), session -> {
        RealmModel realmModel = session.realms().getRealm(realm.getId());
        if (realmModel == null)
            return;
        UserModel deletedUser = session.userLocalStorage().getUserById(realmModel, userId);
        if (deletedUser != null) {
            try {
                new UserManager(session).removeUser(realmModel, deletedUser, session.userLocalStorage());
                logger.debugf("Removed invalid user '%s'", userName);
            } catch (ModelException ex) {
                // Ignore exception, possible cause may be concurrent deleteInvalidUser calls which means
                // ModelException exception may be ignored because users will be removed with next call or is
                // already removed
                logger.debugf(ex, "ModelException thrown during deleteInvalidUser with username '%s'", userName);
            }
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) ModelException(org.keycloak.models.ModelException) UserManager(org.keycloak.models.UserManager) OnUserCache(org.keycloak.models.cache.OnUserCache) UserCache(org.keycloak.models.cache.UserCache)

Example 14 with UserManager

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

the class UserSessionProviderTest method testOnUserRemoved.

public static void testOnUserRemoved(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    UserModel user1 = session.users().getUserByUsername(realm, "user1");
    UserModel user2 = session.users().getUserByUsername(realm, "user2");
    createSessions(session);
    assertEquals(2, session.sessions().getUserSessionsStream(realm, user1).count());
    assertEquals(1, session.sessions().getUserSessionsStream(realm, user2).count());
    // remove user1
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession kcSession) -> (new UserManager(kcSession)).removeUser(realm, user1));
    assertEquals(0, session.sessions().getUserSessionsStream(realm, user1).count());
    assertEquals(1, session.sessions().getUserSessionsStream(realm, user2).count());
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager) KeycloakSession(org.keycloak.models.KeycloakSession)

Example 15 with UserManager

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

the class UserSessionProviderTest method after.

@After
public void after() {
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        session.sessions().removeUserSessions(realm);
        UserModel user1 = session.users().getUserByUsername(realm, "user1");
        UserModel user2 = session.users().getUserByUsername(realm, "user2");
        UserManager um = new UserManager(session);
        if (user1 != null) {
            um.removeUser(realm, user1);
        }
        if (user2 != null) {
            um.removeUser(realm, user2);
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager) After(org.junit.After)

Aggregations

UserManager (org.keycloak.models.UserManager)26 UserModel (org.keycloak.models.UserModel)25 RealmModel (org.keycloak.models.RealmModel)20 After (org.junit.After)7 KeycloakSession (org.keycloak.models.KeycloakSession)7 Test (org.junit.Test)6 RealmManager (org.keycloak.services.managers.RealmManager)5 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)4 UserSessionModel (org.keycloak.models.UserSessionModel)3 ClientModel (org.keycloak.models.ClientModel)2 CachedUserModel (org.keycloak.models.cache.CachedUserModel)2 UserCache (org.keycloak.models.cache.UserCache)2 ClientManager (org.keycloak.services.managers.ClientManager)2 DELETE (javax.ws.rs.DELETE)1 NoCache (org.jboss.resteasy.annotations.cache.NoCache)1 EventBuilder (org.keycloak.events.EventBuilder)1 KeycloakContext (org.keycloak.models.KeycloakContext)1 ModelException (org.keycloak.models.ModelException)1