Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
users: Add parameter to fetch user data for a list of user ids.
Aman Agrawal45d2c8acf5be
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex e70034684d8..f33ae7f2f2b 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,11 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 11.0+**Feature level 384**++* [`GET /users`](/api/get-users): Added `user_ids` query parameter to+ fetch data only for the provided `user_ids`.+**Feature level 383*** [`POST /register`](/api/register-queue), [`PATCHdiff --git a/api_docs/include/rest-endpoints.md b/api_docs/include/rest-endpoints.mdindex 5523caff348..373033b2796 100644--- a/api_docs/include/rest-endpoints.md+++ b/api_docs/include/rest-endpoints.md@@ -69,7 +69,7 @@* [Get a user](/api/get-user)* [Get a user by email](/api/get-user-by-email)* [Get own user](/api/get-own-user)-* [Get all users](/api/get-users)+* [Get users](/api/get-users)* [Create a user](/api/create-user)* [Update a user](/api/update-user)* [Update a user by email](/api/update-user-by-email)diff --git a/version.py b/version.pyindex ead08719edd..71e599ce612 100644--- a/version.py+++ b/version.py@@ -34,7 +34,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# new level means in api_docs/changelog.md, as well as "**Changes**"# entries in the endpoint's documentation in `zulip.yaml`.-API_FEATURE_LEVEL = 383+API_FEATURE_LEVEL = 384# Bump the minor PROVISION_VERSION to indicate that folks should provision# only when going from an old version of the code to a newer version. Bumpdiff --git a/zerver/lib/users.py b/zerver/lib/users.pyindex ab556d1ee37..8f76e996e5b 100644--- a/zerver/lib/users.py+++ b/zerver/lib/users.py@@ -44,6 +44,7 @@ from zerver.models.users import (base_bulk_get_user_queryset,base_get_user_queryset,get_realm_user_dicts,+ get_realm_user_dicts_from_ids,get_user_by_id_in_realm_including_cross_realm,get_user_profile_by_id_in_realm,is_cross_realm_bot_email,@@ -1053,9 +1054,12 @@ def get_accessible_user_ids(def get_user_dicts_in_realm(- realm: Realm, user_profile: UserProfile | None+ realm: Realm, user_profile: UserProfile | None, user_ids: list[int] | None = None) -> tuple[list[RawUserDict], list[APIUserDict]]:- all_user_dicts = get_realm_user_dicts(realm.id)+ if user_ids is not None:+ all_user_dicts = get_realm_user_dicts_from_ids(realm.id, user_ids)+ else:+ all_user_dicts = get_realm_user_dicts(realm.id)if check_user_can_access_all_users(user_profile):return (all_user_dicts, [])@@ -1102,6 +1106,7 @@ def get_users_for_api(user_avatar_url_field_optional: bool,include_custom_profile_fields: bool = True,user_list_incomplete: bool = False,+ user_ids: list[int] | None = None,) -> dict[int, APIUserDict]:"""Fetches data about the target user(s) appropriate for sending toacting_user via the standard format for the Zulip API. If@@ -1114,9 +1119,12 @@ def get_users_for_api(accessible_user_dicts: list[RawUserDict] = []inaccessible_user_dicts: list[APIUserDict] = []if target_user is not None:+ assert user_ids is Noneaccessible_user_dicts = [user_profile_to_user_row(target_user)]else:- accessible_user_dicts, inaccessible_user_dicts = get_user_dicts_in_realm(realm, acting_user)+ accessible_user_dicts, inaccessible_user_dicts = get_user_dicts_in_realm(+ realm, acting_user, user_ids+ )if include_custom_profile_fields:base_query = CustomProfileFieldValue.objects.select_related("field")diff --git a/zerver/models/users.py b/zerver/models/users.pyindex 3d673a465ee..0e3dcba598d 100644--- a/zerver/models/users.py+++ b/zerver/models/users.py@@ -1101,6 +1101,15 @@ def get_realm_user_dicts(realm_id: int) -> list[RawUserDict]:)+def get_realm_user_dicts_from_ids(realm_id: int, user_ids: list[int]) -> list[RawUserDict]:+ return list(+ UserProfile.objects.filter(+ realm_id=realm_id,+ id__in=user_ids,+ ).values(*realm_user_dict_fields)+ )++@cache_with_key(active_user_ids_cache_key, timeout=3600 * 24 * 7)def active_user_ids(realm_id: int) -> list[int]:query = UserProfile.objects.filter(diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 8eab766fcea..130a85c9c57 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -9514,11 +9514,16 @@ paths:/users:get:operationId: get-users- summary: Get all users+ summary: Get userstags: ["users"]description: |- Retrieve details on all users in the organization. Optionally- includes values of [custom profile fields](/help/custom-profile-fields).+ Retrieve details on users in the organization.++ By default, returns all accessible users in the organization.+ The `user_ids` query parameter can be used to limit the+ results to a specific set of user IDs.++ Optionally includes values of [custom profile fields](/help/custom-profile-fields).You can also [fetch details on a single user](/api/get-user).x-curl-examples-parameters:@@ -9536,6 +9541,22 @@ paths:parameters:- $ref: "#/components/parameters/ClientGravatar"- $ref: "#/components/parameters/IncludeCustomProfileFields"+ - name: user_ids+ in: query+ content:+ application/json:+ schema:+ type: array+ items:+ type: integer+ example: [1, 2, 3]+ required: false+ description: |+ Limits the results to the specified user IDs. If not+ provided, the server will return all accessible users in+ the organization.++ **Changes**: New in Zulip 11.0 (feature level 384).responses:"200":description: Success.diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex 6bd1c87e4dc..f9e476057b6 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -2915,7 +2915,7 @@ class GetProfileTest(ZulipTestCase):# 1. Hamlet and Iago - they are subscribed to common streams.# 2. Prospero - Because Polonius sent a DM to Prospero when# they were allowed to access all users.- # 3. Aaron and Zoe - Because they are particapting in a+ # 3. Aaron and Zoe - Because they are participating in a# group DM with Polonius.# 4. Shiva - Because Shiva sent a DM to Polonius.# 5. Polonius - A user can obviously access themselves.@@ -2963,6 +2963,66 @@ class GetProfileTest(ZulipTestCase):inaccessible_user_ids, [cordelia.id, desdemona.id, othello.id, hamlet.id])+ def test_get_user_dicts_with_ids(self) -> None:+ cordelia = self.example_user("cordelia")+ desdemona = self.example_user("desdemona")+ hamlet = self.example_user("hamlet")+ iago = self.example_user("iago")+ zoe = self.example_user("ZOE")+ aaron = self.example_user("aaron")+ webhook_bot = self.example_user("webhook_bot")++ self.set_up_db_for_testing_user_access()+ # Test the /json/users endpoint with user_ids query parameter.+ self.login("polonius")+ # These users are accessible to Polonius because:+ # 1. Hamlet and Iago - they are subscribed to common streams.+ # 3. Aaron and Zoe - Because they are participating in a+ # group DM with Polonius.+ accessible_user_ids_subset = [hamlet.id, iago.id, aaron.id, zoe.id, webhook_bot.id]+ inaccessible_user_ids_subset = [cordelia.id, desdemona.id]+ user_ids_to_fetch = accessible_user_ids_subset + inaccessible_user_ids_subset+ with self.assert_database_query_count(9):+ result = orjson.loads(+ self.client_get(+ "/json/users", {"user_ids": orjson.dumps(user_ids_to_fetch).decode()}+ ).content+ )+ accessible_users = [+ user+ for user in result["members"]+ if user["full_name"] != UserProfile.INACCESSIBLE_USER_NAME+ ]+ self.assert_length(accessible_users, len(accessible_user_ids_subset))+ accessible_user_ids = [user["user_id"] for user in accessible_users]+ self.assertCountEqual(+ accessible_user_ids,+ accessible_user_ids_subset,+ )+ accessible_human_users = [user for user in accessible_users if not user["is_bot"]]+ self.assert_length(accessible_human_users, 4)+ inaccessible_users = [+ user+ for user in result["members"]+ if user["full_name"] == UserProfile.INACCESSIBLE_USER_NAME+ ]+ inaccessible_user_ids = [user["user_id"] for user in inaccessible_users]+ self.assertCountEqual(inaccessible_user_ids, inaccessible_user_ids_subset)++ # Desdemona can access all users since she is an admin.+ self.login("desdemona")+ with self.assert_database_query_count(4):+ result = orjson.loads(+ self.client_get(+ "/json/users", {"user_ids": orjson.dumps(user_ids_to_fetch).decode()}+ ).content+ )+ all_fetched_users = result["members"]+ self.assertCountEqual(+ [user["user_id"] for user in all_fetched_users],+ user_ids_to_fetch,+ )+def test_get_user_with_restricted_access(self) -> None:polonius = self.example_user("polonius")hamlet = self.example_user("hamlet")diff --git a/zerver/views/users.py b/zerver/views/users.pyindex 9a032af534e..7a2992d6c5a 100644--- a/zerver/views/users.py+++ b/zerver/views/users.py@@ -726,6 +726,7 @@ def get_user_data(include_custom_profile_fields: bool,client_gravatar: bool,target_user: UserProfile | None = None,+ user_ids: list[int] | None = None,) -> dict[str, Any]:"""The client_gravatar field here is set to True by default assuming that clients@@ -742,9 +743,11 @@ def get_user_data(client_gravatar=client_gravatar,user_avatar_url_field_optional=False,include_custom_profile_fields=include_custom_profile_fields,+ user_ids=user_ids,)if target_user is not None:+ assert user_ids is Nonedata: dict[str, Any] = {"user": members[target_user.id]}else:data = {"members": [members[k] for k in members]}@@ -773,11 +776,12 @@ def get_members_backend(request: HttpRequest,user_profile: UserProfile,*,+ user_ids: Json[list[int]] | None = None,include_custom_profile_fields: Json[bool] = False,client_gravatar: Json[bool] = True,) -> HttpResponse:data = get_user_data(- user_profile, include_custom_profile_fields, client_gravatar+ user_profile, include_custom_profile_fields, client_gravatar, None, user_ids)return json_success(request, data)