Search in sources :

Example 26 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 27 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 28 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)

Example 29 with UserModel

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

the class ApplicationsBean method getApplications.

private Stream<ClientModel> getApplications(KeycloakSession session, RealmModel realm, UserModel user) {
    Predicate<ClientModel> bearerOnly = ClientModel::isBearerOnly;
    Stream<ClientModel> clients = realm.getClientsStream().filter(bearerOnly.negate());
    Predicate<ClientModel> isLocal = client -> new StorageId(client.getId()).isLocal();
    return Stream.concat(clients, session.users().getConsentsStream(realm, user.getId()).map(UserConsentModel::getClient).filter(isLocal.negate())).distinct();
}
Also used : ClientModel(org.keycloak.models.ClientModel) AdminPermissions(org.keycloak.services.resources.admin.permissions.AdminPermissions) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) Predicate(java.util.function.Predicate) Constants(org.keycloak.models.Constants) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) RoleModel(org.keycloak.models.RoleModel) TokenManager(org.keycloak.protocol.oidc.TokenManager) Collectors(java.util.stream.Collectors) StorageId(org.keycloak.storage.StorageId) ResolveRelative(org.keycloak.services.util.ResolveRelative) ArrayList(java.util.ArrayList) OrderedModel(org.keycloak.models.OrderedModel) Objects(java.util.Objects) List(java.util.List) UserModel(org.keycloak.models.UserModel) Stream(java.util.stream.Stream) UserSessionManager(org.keycloak.services.managers.UserSessionManager) UserConsentModel(org.keycloak.models.UserConsentModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) LinkedList(java.util.LinkedList) ClientModel(org.keycloak.models.ClientModel) StorageId(org.keycloak.storage.StorageId)

Example 30 with UserModel

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

the class AuthenticationManager method backchannelLogout.

/**
 * @param session
 * @param realm
 * @param userSession
 * @param uriInfo
 * @param connection
 * @param headers
 * @param logoutBroker
 * @param offlineSession
 *
 * @return BackchannelLogoutResponse with logout information
 */
public static BackchannelLogoutResponse backchannelLogout(KeycloakSession session, RealmModel realm, UserSessionModel userSession, UriInfo uriInfo, ClientConnection connection, HttpHeaders headers, boolean logoutBroker, boolean offlineSession) {
    BackchannelLogoutResponse backchannelLogoutResponse = new BackchannelLogoutResponse();
    if (userSession == null) {
        backchannelLogoutResponse.setLocalLogoutSucceeded(true);
        return backchannelLogoutResponse;
    }
    UserModel user = userSession.getUser();
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        userSession.setState(UserSessionModel.State.LOGGING_OUT);
    }
    logger.debugv("Logging out: {0} ({1}) offline: {2}", user.getUsername(), userSession.getId(), userSession.isOffline());
    boolean expireUserSessionCookieSucceeded = expireUserSessionCookie(session, userSession, realm, uriInfo, headers, connection);
    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, false);
    boolean userSessionOnlyHasLoggedOutClients = false;
    try {
        backchannelLogoutResponse = backchannelLogoutAll(session, realm, userSession, logoutAuthSession, uriInfo, headers, logoutBroker);
        userSessionOnlyHasLoggedOutClients = checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);
    } finally {
        RootAuthenticationSessionModel rootAuthSession = logoutAuthSession.getParentSession();
        rootAuthSession.removeAuthenticationSessionByTabId(logoutAuthSession.getTabId());
    }
    userSession.setState(UserSessionModel.State.LOGGED_OUT);
    if (offlineSession) {
        new UserSessionManager(session).revokeOfflineUserSession(userSession);
        // Check if "online" session still exists and remove it too
        String onlineUserSessionId = userSession.getNote(CORRESPONDING_SESSION_ID);
        UserSessionModel onlineUserSession = (onlineUserSessionId != null) ? session.sessions().getUserSession(realm, onlineUserSessionId) : session.sessions().getUserSession(realm, userSession.getId());
        if (onlineUserSession != null) {
            session.sessions().removeUserSession(realm, onlineUserSession);
        }
    } else {
        session.sessions().removeUserSession(realm, userSession);
    }
    backchannelLogoutResponse.setLocalLogoutSucceeded(expireUserSessionCookieSucceeded && userSessionOnlyHasLoggedOutClients);
    return backchannelLogoutResponse;
}
Also used : UserModel(org.keycloak.models.UserModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse)

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