Search in sources :

Example 1 with UserPermissionEvaluator

use of org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator in project keycloak by keycloak.

the class UsersResource method getUsersCount.

/**
 * Returns the number of users that match the given criteria.
 * It can be called in three different ways.
 * 1. Don't specify any criteria and pass {@code null}. The number of all
 * users within that realm will be returned.
 * <p>
 * 2. If {@code search} is specified other criteria such as {@code last} will
 * be ignored even though you set them. The {@code search} string will be
 * matched against the first and last name, the username and the email of a
 * user.
 * <p>
 * 3. If {@code search} is unspecified but any of {@code last}, {@code first},
 * {@code email} or {@code username} those criteria are matched against their
 * respective fields on a user entity. Combined with a logical and.
 *
 * @param search   arbitrary search string for all the fields below
 * @param last     last name filter
 * @param first    first name filter
 * @param email    email filter
 * @param username username filter
 * @return the number of users that match the given criteria
 */
@Path("count")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Integer getUsersCount(@QueryParam("search") String search, @QueryParam("lastName") String last, @QueryParam("firstName") String first, @QueryParam("email") String email, @QueryParam("emailVerified") Boolean emailVerified, @QueryParam("username") String username) {
    UserPermissionEvaluator userPermissionEvaluator = auth.users();
    userPermissionEvaluator.requireQuery();
    if (search != null) {
        if (search.startsWith(SEARCH_ID_PARAMETER)) {
            UserModel userModel = session.users().getUserById(realm, search.substring(SEARCH_ID_PARAMETER.length()).trim());
            return userModel != null && userPermissionEvaluator.canView(userModel) ? 1 : 0;
        } else if (userPermissionEvaluator.canView()) {
            return session.users().getUsersCount(realm, search.trim());
        } else {
            return session.users().getUsersCount(realm, search.trim(), auth.groups().getGroupsWithViewPermission());
        }
    } else if (last != null || first != null || email != null || username != null || emailVerified != null) {
        Map<String, String> parameters = new HashMap<>();
        if (last != null) {
            parameters.put(UserModel.LAST_NAME, last);
        }
        if (first != null) {
            parameters.put(UserModel.FIRST_NAME, first);
        }
        if (email != null) {
            parameters.put(UserModel.EMAIL, email);
        }
        if (username != null) {
            parameters.put(UserModel.USERNAME, username);
        }
        if (emailVerified != null) {
            parameters.put(UserModel.EMAIL_VERIFIED, emailVerified.toString());
        }
        if (userPermissionEvaluator.canView()) {
            return session.users().getUsersCount(realm, parameters);
        } else {
            return session.users().getUsersCount(realm, parameters, auth.groups().getGroupsWithViewPermission());
        }
    } else if (userPermissionEvaluator.canView()) {
        return session.users().getUsersCount(realm);
    } else {
        return session.users().getUsersCount(realm, auth.groups().getGroupsWithViewPermission());
    }
}
Also used : UserModel(org.keycloak.models.UserModel) UserPermissionEvaluator(org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) KeycloakModelUtils.findGroupByPath(org.keycloak.models.utils.KeycloakModelUtils.findGroupByPath) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 2 with UserPermissionEvaluator

use of org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator in project keycloak by keycloak.

the class UsersResource method getUsers.

/**
 * Get users
 *
 * Returns a stream of users, filtered according to query parameters.
 *
 * @param search A String contained in username, first or last name, or email
 * @param last A String contained in lastName, or the complete lastName, if param "exact" is true
 * @param first A String contained in firstName, or the complete firstName, if param "exact" is true
 * @param email A String contained in email, or the complete email, if param "exact" is true
 * @param username A String contained in username, or the complete username, if param "exact" is true
 * @param emailVerified whether the email has been verified
 * @param idpAlias The alias of an Identity Provider linked to the user
 * @param idpUserId The userId at an Identity Provider linked to the user
 * @param firstResult Pagination offset
 * @param maxResults Maximum results size (defaults to 100)
 * @param enabled Boolean representing if user is enabled or not
 * @param briefRepresentation Boolean which defines whether brief representations are returned (default: false)
 * @param exact Boolean which defines whether the params "last", "first", "email" and "username" must match exactly
 * @param searchQuery A query to search for custom attributes, in the format 'key1:value2 key2:value2'
 * @return a non-null {@code Stream} of users
 */
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Stream<UserRepresentation> getUsers(@QueryParam("search") String search, @QueryParam("lastName") String last, @QueryParam("firstName") String first, @QueryParam("email") String email, @QueryParam("username") String username, @QueryParam("emailVerified") Boolean emailVerified, @QueryParam("idpAlias") String idpAlias, @QueryParam("idpUserId") String idpUserId, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults, @QueryParam("enabled") Boolean enabled, @QueryParam("briefRepresentation") Boolean briefRepresentation, @QueryParam("exact") Boolean exact, @QueryParam("q") String searchQuery) {
    UserPermissionEvaluator userPermissionEvaluator = auth.users();
    userPermissionEvaluator.requireQuery();
    firstResult = firstResult != null ? firstResult : -1;
    maxResults = maxResults != null ? maxResults : Constants.DEFAULT_MAX_RESULTS;
    Map<String, String> searchAttributes = searchQuery == null ? Collections.emptyMap() : SearchQueryUtils.getFields(searchQuery);
    Stream<UserModel> userModels = Stream.empty();
    if (search != null) {
        if (search.startsWith(SEARCH_ID_PARAMETER)) {
            UserModel userModel = session.users().getUserById(realm, search.substring(SEARCH_ID_PARAMETER.length()).trim());
            if (userModel != null) {
                userModels = Stream.of(userModel);
            }
        } else {
            Map<String, String> attributes = new HashMap<>();
            attributes.put(UserModel.SEARCH, search.trim());
            if (enabled != null) {
                attributes.put(UserModel.ENABLED, enabled.toString());
            }
            return searchForUser(attributes, realm, userPermissionEvaluator, briefRepresentation, firstResult, maxResults, false);
        }
    } else if (last != null || first != null || email != null || username != null || emailVerified != null || idpAlias != null || idpUserId != null || enabled != null || exact != null || !searchAttributes.isEmpty()) {
        Map<String, String> attributes = new HashMap<>();
        if (last != null) {
            attributes.put(UserModel.LAST_NAME, last);
        }
        if (first != null) {
            attributes.put(UserModel.FIRST_NAME, first);
        }
        if (email != null) {
            attributes.put(UserModel.EMAIL, email);
        }
        if (username != null) {
            attributes.put(UserModel.USERNAME, username);
        }
        if (emailVerified != null) {
            attributes.put(UserModel.EMAIL_VERIFIED, emailVerified.toString());
        }
        if (idpAlias != null) {
            attributes.put(UserModel.IDP_ALIAS, idpAlias);
        }
        if (idpUserId != null) {
            attributes.put(UserModel.IDP_USER_ID, idpUserId);
        }
        if (enabled != null) {
            attributes.put(UserModel.ENABLED, enabled.toString());
        }
        if (exact != null) {
            attributes.put(UserModel.EXACT, exact.toString());
        }
        attributes.putAll(searchAttributes);
        return searchForUser(attributes, realm, userPermissionEvaluator, briefRepresentation, firstResult, maxResults, true);
    } else {
        return searchForUser(new HashMap<>(), realm, userPermissionEvaluator, briefRepresentation, firstResult, maxResults, false);
    }
    return toRepresentation(realm, userPermissionEvaluator, briefRepresentation, userModels);
}
Also used : UserModel(org.keycloak.models.UserModel) UserPermissionEvaluator(org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator) HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 3 with UserPermissionEvaluator

use of org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator in project keycloak by keycloak.

the class UsersResource method toRepresentation.

private Stream<UserRepresentation> toRepresentation(RealmModel realm, UserPermissionEvaluator usersEvaluator, Boolean briefRepresentation, Stream<UserModel> userModels) {
    boolean briefRepresentationB = briefRepresentation != null && briefRepresentation;
    boolean canViewGlobal = usersEvaluator.canView();
    usersEvaluator.grantIfNoPermission(session.getAttribute(UserModel.GROUPS) != null);
    return userModels.filter(user -> canViewGlobal || usersEvaluator.canView(user)).map(user -> {
        UserRepresentation userRep = briefRepresentationB ? ModelToRepresentation.toBriefRepresentation(user) : ModelToRepresentation.toRepresentation(session, realm, user);
        userRep.setAccess(usersEvaluator.getAccess(user));
        return userRep;
    });
}
Also used : ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) Path(javax.ws.rs.Path) USER_API(org.keycloak.userprofile.UserProfileContext.USER_API) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) Set(java.util.Set) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) KeycloakModelUtils.findGroupByPath(org.keycloak.models.utils.KeycloakModelUtils.findGroupByPath) Objects(java.util.Objects) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) ForbiddenException(org.keycloak.services.ForbiddenException) Optional(java.util.Optional) SearchQueryUtils(org.keycloak.utils.SearchQueryUtils) OperationType(org.keycloak.events.admin.OperationType) UserProfile(org.keycloak.userprofile.UserProfile) PathParam(javax.ws.rs.PathParam) UserPermissionEvaluator(org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator) Profile(org.keycloak.common.Profile) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Constants(org.keycloak.models.Constants) HashMap(java.util.HashMap) ObjectUtil(org.keycloak.common.util.ObjectUtil) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) UserModel(org.keycloak.models.UserModel) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) GroupModel(org.keycloak.models.GroupModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) POST(javax.ws.rs.POST) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) NoCache(org.jboss.resteasy.annotations.cache.NoCache) ModelException(org.keycloak.models.ModelException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) Collections(java.util.Collections) ErrorResponse(org.keycloak.services.ErrorResponse) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Aggregations

HashMap (java.util.HashMap)3 Map (java.util.Map)3 GET (javax.ws.rs.GET)3 Produces (javax.ws.rs.Produces)3 NoCache (org.jboss.resteasy.annotations.cache.NoCache)3 UserModel (org.keycloak.models.UserModel)3 UserPermissionEvaluator (org.keycloak.services.resources.admin.permissions.UserPermissionEvaluator)3 Path (javax.ws.rs.Path)2 KeycloakModelUtils.findGroupByPath (org.keycloak.models.utils.KeycloakModelUtils.findGroupByPath)2 Collections (java.util.Collections)1 List (java.util.List)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1 Stream (java.util.stream.Stream)1 Consumes (javax.ws.rs.Consumes)1 NotFoundException (javax.ws.rs.NotFoundException)1 POST (javax.ws.rs.POST)1 PathParam (javax.ws.rs.PathParam)1