Search in sources :

Example 1 with UserModel

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

the class UserCacheSession method getUserByUsername.

@Override
public UserModel getUserByUsername(RealmModel realm, String username) {
    logger.tracev("getUserByUsername: {0}", username);
    username = username.toLowerCase();
    if (realmInvalidations.contains(realm.getId())) {
        logger.tracev("realmInvalidations");
        return getDelegate().getUserByUsername(realm, username);
    }
    String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
    if (invalidations.contains(cacheKey)) {
        logger.tracev("invalidations");
        return getDelegate().getUserByUsername(realm, username);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);
    String userId = null;
    if (query == null) {
        logger.tracev("query null");
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getUserByUsername(realm, username);
        if (model == null) {
            logger.tracev("model from delegate null");
            return null;
        }
        userId = model.getId();
        if (invalidations.contains(userId))
            return model;
        if (managedUsers.containsKey(userId)) {
            logger.tracev("return managed user");
            return managedUsers.get(userId);
        }
        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) {
            // this was cached, so we can cache query too
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }
        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            logger.tracev("invalidated cache return delegate");
            return getDelegate().getUserByUsername(realm, username);
        }
        logger.trace("return getUserById");
        return getUserById(realm, userId);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserListQuery(org.keycloak.models.cache.infinispan.entities.UserListQuery)

Example 2 with UserModel

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

the class UserCacheSession method getUserByEmail.

@Override
public UserModel getUserByEmail(RealmModel realm, String email) {
    if (email == null)
        return null;
    email = email.toLowerCase();
    if (realmInvalidations.contains(realm.getId())) {
        return getDelegate().getUserByEmail(realm, email);
    }
    String cacheKey = getUserByEmailCacheKey(realm.getId(), email);
    if (invalidations.contains(cacheKey)) {
        return getDelegate().getUserByEmail(realm, email);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);
    String userId = null;
    if (query == null) {
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getUserByEmail(realm, email);
        if (model == null)
            return null;
        userId = model.getId();
        if (invalidations.contains(userId))
            return model;
        if (managedUsers.containsKey(userId))
            return managedUsers.get(userId);
        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) {
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }
        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            return getDelegate().getUserByEmail(realm, email);
        }
        return getUserById(realm, userId);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserListQuery(org.keycloak.models.cache.infinispan.entities.UserListQuery)

Example 3 with UserModel

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

the class UserCacheSession method getUserById.

@Override
public UserModel getUserById(RealmModel realm, String id) {
    logger.tracev("getuserById {0}", id);
    if (isRegisteredForInvalidation(realm, id)) {
        logger.trace("registered for invalidation return delegate");
        return getDelegate().getUserById(realm, id);
    }
    if (managedUsers.containsKey(id)) {
        logger.trace("return managedusers");
        return managedUsers.get(id);
    }
    CachedUser cached = cache.get(id, CachedUser.class);
    if (cached != null && !cached.getRealm().equals(realm.getId())) {
        cached = null;
    }
    UserModel adapter = null;
    if (cached == null) {
        logger.trace("not cached");
        Long loaded = cache.getCurrentRevision(id);
        UserModel delegate = getDelegate().getUserById(realm, id);
        if (delegate == null) {
            logger.trace("delegate returning null");
            return null;
        }
        adapter = cacheUser(realm, delegate, loaded);
    } else {
        adapter = validateCache(realm, cached);
    }
    managedUsers.put(id, adapter);
    return adapter;
}
Also used : UserModel(org.keycloak.models.UserModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) CachedUser(org.keycloak.models.cache.infinispan.entities.CachedUser)

Example 4 with UserModel

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

the class MapUserProvider method preRemove.

@Override
public void preRemove(RealmModel realm, ComponentModel component) {
    String componentId = component.getId();
    LOG.tracef("preRemove[ComponentModel](%s, %s)%s", realm, componentId, getShortStackTrace());
    if (component.getProviderType().equals(UserStorageProvider.class.getName())) {
        removeImportedUsers(realm, componentId);
    }
    if (component.getProviderType().equals(ClientStorageProvider.class.getName())) {
        DefaultModelCriteria<UserModel> mcb = criteria();
        mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()).compare(SearchableFields.CONSENT_CLIENT_FEDERATION_LINK, Operator.EQ, componentId);
        try (Stream<MapUserEntity> s = tx.read(withCriteria(mcb))) {
            String providerIdS = new StorageId(componentId, "").getId();
            s.forEach(removeConsentsForExternalClient(providerIdS));
        }
    }
}
Also used : UserModel(org.keycloak.models.UserModel) UserStorageProvider(org.keycloak.storage.UserStorageProvider) ClientStorageProvider(org.keycloak.storage.client.ClientStorageProvider) StorageId(org.keycloak.storage.StorageId)

Example 5 with UserModel

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

the class MapUserProvider method searchForUserStream.

@Override
public Stream<UserModel> searchForUserStream(RealmModel realm, Map<String, String> attributes, Integer firstResult, Integer maxResults) {
    LOG.tracef("searchForUserStream(%s, %s, %d, %d)%s", realm, attributes, firstResult, maxResults, getShortStackTrace());
    final DefaultModelCriteria<UserModel> mcb = criteria();
    DefaultModelCriteria<UserModel> criteria = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId());
    if (!session.getAttributeOrDefault(UserModel.INCLUDE_SERVICE_ACCOUNT, true)) {
        criteria = criteria.compare(SearchableFields.SERVICE_ACCOUNT_CLIENT, Operator.NOT_EXISTS);
    }
    final boolean exactSearch = Boolean.parseBoolean(attributes.getOrDefault(UserModel.EXACT, Boolean.FALSE.toString()));
    for (Map.Entry<String, String> entry : attributes.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (value == null) {
            continue;
        }
        value = value.trim();
        final String searchedString = exactSearch ? value : ("%" + value + "%");
        switch(key) {
            case UserModel.SEARCH:
                DefaultModelCriteria<UserModel> searchCriteria = null;
                for (String stringToSearch : value.split("\\s+")) {
                    if (searchCriteria == null) {
                        searchCriteria = addSearchToModelCriteria(stringToSearch, mcb);
                    } else {
                        searchCriteria = mcb.and(searchCriteria, addSearchToModelCriteria(stringToSearch, mcb));
                    }
                }
                criteria = mcb.and(criteria, searchCriteria);
                break;
            case USERNAME:
                criteria = criteria.compare(SearchableFields.USERNAME, Operator.ILIKE, searchedString);
                break;
            case FIRST_NAME:
                criteria = criteria.compare(SearchableFields.FIRST_NAME, Operator.ILIKE, searchedString);
                break;
            case LAST_NAME:
                criteria = criteria.compare(SearchableFields.LAST_NAME, Operator.ILIKE, searchedString);
                break;
            case EMAIL:
                criteria = criteria.compare(SearchableFields.EMAIL, Operator.ILIKE, searchedString);
                break;
            case EMAIL_VERIFIED:
                {
                    boolean booleanValue = Boolean.parseBoolean(value);
                    criteria = criteria.compare(SearchableFields.EMAIL_VERIFIED, Operator.EQ, booleanValue);
                    break;
                }
            case UserModel.ENABLED:
                {
                    boolean booleanValue = Boolean.parseBoolean(value);
                    criteria = criteria.compare(SearchableFields.ENABLED, Operator.EQ, booleanValue);
                    break;
                }
            case UserModel.IDP_ALIAS:
                {
                    if (!attributes.containsKey(UserModel.IDP_USER_ID)) {
                        criteria = criteria.compare(SearchableFields.IDP_AND_USER, Operator.EQ, value);
                    }
                    break;
                }
            case UserModel.IDP_USER_ID:
                {
                    criteria = criteria.compare(SearchableFields.IDP_AND_USER, Operator.EQ, attributes.get(UserModel.IDP_ALIAS), value);
                    break;
                }
            case UserModel.EXACT:
                break;
            default:
                criteria = criteria.compare(SearchableFields.ATTRIBUTE, Operator.EQ, key, value);
                break;
        }
    }
    // Only return those results that the current user is authorized to view,
    // i.e. there is an intersection of groups with view permission of the current
    // user (passed in via UserModel.GROUPS attribute), the groups for the returned
    // users, and the respective group resource available from the authorization provider
    @SuppressWarnings("unchecked") Set<String> userGroups = (Set<String>) session.getAttribute(UserModel.GROUPS);
    if (userGroups != null) {
        if (userGroups.isEmpty()) {
            return Stream.empty();
        }
        final ResourceStore resourceStore = session.getProvider(AuthorizationProvider.class).getStoreFactory().getResourceStore();
        HashSet<String> authorizedGroups = new HashSet<>(userGroups);
        authorizedGroups.removeIf(id -> {
            Map<Resource.FilterOption, String[]> values = new EnumMap<>(Resource.FilterOption.class);
            values.put(Resource.FilterOption.EXACT_NAME, new String[] { "group.resource." + id });
            return resourceStore.findByResourceServer(values, null, 0, 1).isEmpty();
        });
        criteria = criteria.compare(SearchableFields.ASSIGNED_GROUP, Operator.IN, authorizedGroups);
    }
    return tx.read(withCriteria(criteria).pagination(firstResult, maxResults, SearchableFields.USERNAME)).map(entityToAdapterFunc(realm)).filter(Objects::nonNull);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) UserModel(org.keycloak.models.UserModel) Objects(java.util.Objects) Map(java.util.Map) EnumMap(java.util.EnumMap) HashMap(java.util.HashMap) EnumMap(java.util.EnumMap) HashSet(java.util.HashSet)

Aggregations

UserModel (org.keycloak.models.UserModel)383 RealmModel (org.keycloak.models.RealmModel)220 Test (org.junit.Test)126 ClientModel (org.keycloak.models.ClientModel)86 KeycloakSession (org.keycloak.models.KeycloakSession)81 CachedUserModel (org.keycloak.models.cache.CachedUserModel)52 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)43 List (java.util.List)41 UserSessionModel (org.keycloak.models.UserSessionModel)40 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)40 RoleModel (org.keycloak.models.RoleModel)39 ComponentModel (org.keycloak.component.ComponentModel)31 HashMap (java.util.HashMap)30 Response (javax.ws.rs.core.Response)29 Path (javax.ws.rs.Path)28 UserManager (org.keycloak.models.UserManager)28 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)27 Map (java.util.Map)25 GroupModel (org.keycloak.models.GroupModel)24 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)24