Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
user_settings: Add backend for admin to modify user settings.
Aditya Kumar Kasaudhane49f0ded8608
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex c5242907962..8c1960030bd 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,12 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 12.0+**Feature level 444**++* [`PATCH /settings`](/api/update-settings): Added support for bulk updating+ settings for specified users or members of user groups using `target_users`+ and `skip_if_already_edited` parameters.+**Feature level 443*** [`GET /attachments`](/api/get-attachments), [`GET /events`](/api/get-events):diff --git a/version.py b/version.pyindex daabc640efe..97229a71b0f 100644--- a/version.py+++ b/version.py@@ -35,7 +35,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 = 443+API_FEATURE_LEVEL = 444# 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/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 83cd94484fd..4777baea87f 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -21163,9 +21163,18 @@ paths:description: |This endpoint is used to edit the current user's settings.- **Changes**: Removed `dense_mode` setting in Zulip 10.0- (feature level 364) as we now have `web_font_size_px` and- `web_line_height_percent` settings for more control.+ When invoked by a realm admin, it supports bulk updates to+ settings for specified users or members of user groups using+ the `target_users` parameter.++ **Changes**: Added support for bulk updating the settings+ for specified users or members of user groups in+ Zulip 12.0 (feature level 444) using the `target_users`+ and `skip_if_already_edited` parameters.++ Removed `dense_mode` setting in Zulip 10.0 (feature level 364)+ as we now have `web_font_size_px` and `web_line_height_percent`+ settings for more control.Prior to Zulip 5.0 (feature level 80), this endpoint onlysupported the `full_name`, `email`, `old_password`, and@@ -21212,6 +21221,42 @@ paths:schema:type: objectproperties:+ target_users:+ description: |+ An object specifying the collection of users whose settings should be modified,+ for modification of other users' settings by an organization administrator.+ When this parameter is absent, this API endpoint always modifies the current+ user's own settings.++ **Changes**: New in Zulip 12.0 (feature level 444).+ type: object+ properties:+ user_ids:+ description: |+ A list of integer user IDs representing individual users whose settings will be updated.+ type: array+ items:+ type: integer+ group_ids:+ description: |+ A list of integer group IDs representing user groups, where settings will be applied to+ all active members of the specified groups.+ type: array+ items:+ type: integer+ skip_if_already_edited:+ description: |+ Whether to skip editing the settings of users who have previously edited their settings,+ which can be useful for adjusting a default without overriding users' own directly+ expressed preferences.+ type: boolean+ example: false+ example:+ {+ "user_ids": [6, 8],+ "group_ids": [24],+ skip_if_alread_edited: false,+ }full_name:description: |A new display name for the user.@@ -21945,6 +21990,10 @@ paths:type: booleanexample: trueencoding:+ target_users:+ contentType: application/json+ skip_if_already_edited:+ contentType: application/jsontwenty_four_hour_time:contentType: application/jsonweb_mark_read_on_scroll_policy:diff --git a/zerver/tests/test_settings.py b/zerver/tests/test_settings.pyindex 7378a00153f..690c453d1ac 100644--- a/zerver/tests/test_settings.py+++ b/zerver/tests/test_settings.py@@ -10,7 +10,7 @@ from django.test import override_settingsfrom zerver.lib.initial_password import initial_passwordfrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import get_test_image_file, ratelimit_rule-from zerver.models import Draft, ScheduledMessageNotificationEmail, UserProfile+from zerver.models import Draft, NamedUserGroup, ScheduledMessageNotificationEmail, UserProfilefrom zerver.models.scheduled_jobs import NotificationTriggersfrom zerver.models.users import ResolvedTopicNoticeAutoReadPolicyEnum, get_user_profile_by_api_key@@ -621,6 +621,117 @@ class ChangeSettingsTest(ZulipTestCase):self.assertEqual(hamlet.web_font_size_px, 14)self.assertEqual(hamlet.web_line_height_percent, 122)+ def test_admin_change_settings_for_other_users(self) -> None:+ # Non-admin cannot change settings for other users+ hamlet = self.example_user("hamlet")+ cordelia = self.example_user("cordelia")+ othello = self.example_user("othello")+ iago = self.example_user("iago")+ hamletcharacters_group = NamedUserGroup.objects.get(+ name="hamletcharacters", realm_for_sharding=iago.realm+ )++ target_users_dict = {+ "user_ids": [iago.id, othello.id],+ "group_ids": [hamletcharacters_group.id],+ "skip_if_already_edited": False,+ }+ self.assertEqual(cordelia.automatically_follow_topics_where_mentioned, False)+ self.assertEqual(hamlet.automatically_follow_topics_where_mentioned, False)+ self.assertEqual(othello.automatically_follow_topics_where_mentioned, False)+ self.assertEqual(iago.automatically_follow_topics_where_mentioned, False)++ self.login("hamlet")+ data = {+ "target_users": orjson.dumps(target_users_dict).decode(),+ "automatically_follow_topics_where_mentioned": orjson.dumps(True).decode(),+ "web_font_size_px": orjson.dumps(18).decode(),+ }+ result = self.client_patch("/json/settings", data)+ self.assert_json_error(result, "Must be an organization administrator")++ # Admin can change non-sensitive settings for other users+ self.login("desdemona")+ result = self.client_patch("/json/settings", data)+ self.assert_json_success(result)+ cordelia.refresh_from_db()+ othello.refresh_from_db()+ iago.refresh_from_db()+ hamlet.refresh_from_db()+ self.assertEqual(cordelia.automatically_follow_topics_where_mentioned, True)+ self.assertEqual(cordelia.web_font_size_px, 18)+ self.assertEqual(hamlet.automatically_follow_topics_where_mentioned, True)+ self.assertEqual(hamlet.web_font_size_px, 18)+ self.assertEqual(othello.automatically_follow_topics_where_mentioned, True)+ self.assertEqual(othello.web_font_size_px, 18)+ self.assertEqual(iago.automatically_follow_topics_where_mentioned, True)+ self.assertEqual(iago.web_font_size_px, 18)++ # Test skip users who have already edited their specific settings+ target_users_dict["skip_if_already_edited"] = True+ data = {+ "target_users": orjson.dumps(target_users_dict).decode(),+ "automatically_follow_topics_where_mentioned": orjson.dumps(False).decode(),+ }+ result = self.client_patch("/json/settings", data)+ self.assert_json_success(result)+ cordelia.refresh_from_db()+ othello.refresh_from_db()+ iago.refresh_from_db()+ hamlet.refresh_from_db()+ self.assertEqual(cordelia.automatically_follow_topics_where_mentioned, True)+ self.assertEqual(othello.automatically_follow_topics_where_mentioned, True)+ self.assertEqual(iago.automatically_follow_topics_where_mentioned, True)+ self.assertEqual(hamlet.automatically_follow_topics_where_mentioned, True)++ # Admin cannot change sensitive settings for other users.+ data = {+ "target_users": orjson.dumps(target_users_dict).decode(),+ "send_read_receipts": orjson.dumps(False).decode(),+ }+ result = self.client_patch("/json/settings", data)+ self.assert_json_error(result, "Cannot change this setting for other users.")++ # Admin cannot change timezone setting for other users.+ data = {+ "target_users": orjson.dumps(target_users_dict).decode(),+ "timezone": "Asia/Kolkata",+ }+ result = self.client_patch("/json/settings", data)+ self.assert_json_error(result, "Cannot change this setting for other users.")++ # Test with invalid users.+ invalid_target_users_dict = {+ "user_ids": [500, othello.id],+ "skip_if_already_edited": False,+ }+ data = {+ "target_users": orjson.dumps(invalid_target_users_dict).decode(),+ "automatically_follow_topics_where_mentioned": orjson.dumps(False).decode(),+ }+ result = self.client_patch("/json/settings", data)+ self.assert_json_error(result, "Invalid user ID: 500")++ # Test with invalid groups.+ invalid_target_users_dict = {+ "group_ids": [500, hamletcharacters_group.id],+ "skip_if_already_edited": False,+ }+ data = {+ "target_users": orjson.dumps(invalid_target_users_dict).decode(),+ "automatically_follow_topics_where_mentioned": orjson.dumps(False).decode(),+ }+ result = self.client_patch("/json/settings", data)+ self.assert_json_error(result, "Invalid user group ID: 500")++ # Test target users dict without user_ids and group_ids.+ data = {+ "target_users": orjson.dumps({"skip_if_already_edited": False}).decode(),+ "automatically_follow_topics_where_mentioned": orjson.dumps(False).decode(),+ }+ result = self.client_patch("/json/settings", data)+ self.assert_json_error(result, "Either user_ids or group_ids must be provided.")+class UserChangesTest(ZulipTestCase):def test_update_api_key(self) -> None:diff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.pyindex 4b39bad16fc..961638ad48f 100644--- a/zerver/views/user_settings.py+++ b/zerver/views/user_settings.py@@ -14,7 +14,7 @@ from django.utils.html import escapefrom django.utils.safestring import SafeStringfrom django.utils.translation import gettext as _from django.utils.translation import gettext_lazy-from pydantic import Json+from pydantic import BaseModel, Json, model_validatorfrom pydantic.functional_validators import AfterValidatorfrom confirmation.models import (@@ -24,6 +24,7 @@ from confirmation.models import (render_confirmation_key_error,)from zerver.actions.user_settings import (+ bulk_change_user_setting,check_change_full_name,do_change_avatar_fields,do_change_password,@@ -41,7 +42,12 @@ from zerver.lib.email_validation import (validate_email_is_valid,validate_email_not_already_in_realm,)-from zerver.lib.exceptions import JsonableError, RateLimitedError, UserDeactivatedError+from zerver.lib.exceptions import (+ JsonableError,+ OrganizationAdministratorRequiredError,+ RateLimitedError,+ UserDeactivatedError,+)from zerver.lib.i18n import get_available_language_codesfrom zerver.lib.rate_limiter import RateLimitedUser, should_rate_limitfrom zerver.lib.response import json_success@@ -55,7 +61,13 @@ from zerver.lib.typed_endpoint_validators import (timezone_validator,)from zerver.lib.upload import upload_avatar_image-from zerver.models import EmailChangeStatus, UserProfile+from zerver.lib.user_groups import (+ get_recursive_group_members_union_for_groups,+ user_group_ids_to_user_groups,+)+from zerver.lib.users import user_ids_to_users+from zerver.models import EmailChangeStatus, RealmAuditLog, UserBaseSettings, UserProfile+from zerver.models.realm_audit_logs import AuditLogEventTypefrom zerver.models.realms import avatar_changes_disabled, name_changes_disabledfrom zerver.models.users import ResolvedTopicNoticeAutoReadPolicyEnumfrom zerver.views.auth import redirect_to_deactivation_notice@@ -227,6 +239,18 @@ def check_settings_values()+class TargetUsersData(BaseModel):+ user_ids: list[int] = []+ group_ids: list[int] = []+ skip_if_already_edited: bool++ @model_validator(mode="after")+ def validate_terms(self) -> "TargetUsersData":+ if not self.user_ids and not self.group_ids:+ raise JsonableError(_("Either user_ids or group_ids must be provided."))+ return self++@human_users_only@typed_endpointdef json_change_settings(@@ -314,6 +338,7 @@ def json_change_settings(send_read_receipts: Json[bool] | None = None,send_stream_typing_notifications: Json[bool] | None = None,starred_message_counts: Json[bool] | None = None,+ target_users: Json[TargetUsersData] | None = None,timezone: Annotated[str, timezone_validator()] | None = None,translate_emoticons: Json[bool] | None = None,twenty_four_hour_time: Json[bool] | None = None,@@ -357,6 +382,77 @@ def json_change_settings(# TODO: Change the cache flushing strategy to make sure cache# does not contain stale objects.user_profile = UserProfile.objects.get(id=user_profile.id)++ # Loop over user_profile.property_types+ request_settings = {+ setting_name: requested_value+ for setting_name, requested_value in locals().items()+ if setting_name in user_profile.property_types and requested_value is not None+ }++ if target_users is not None:+ if not user_profile.is_realm_admin:+ raise OrganizationAdministratorRequiredError++ # "email" and "password" are not user settings but users still update them+ # using this endpoint.+ if email is not None or new_password is not None or timezone is not None:+ raise JsonableError(_("Cannot change this setting for other users."))++ for setting_name in request_settings:+ if setting_name in UserBaseSettings.SECURITY_SENSITIVE_USER_SETTINGS:+ raise JsonableError(_("Cannot change this setting for other users."))++ user_ids = target_users.user_ids+ group_member_ids = set()++ if target_users.group_ids:+ valid_groups = user_group_ids_to_user_groups(target_users.group_ids, user_profile.realm)+ valid_group_ids = [group.id for group in valid_groups]+ group_member_ids = set(+ get_recursive_group_members_union_for_groups(valid_group_ids).values_list(+ "id", flat=True+ )+ )++ all_user_ids = list(set(user_ids) | group_member_ids)++ # User settings do not apply to bots, so exclude them from the query even if they+ # are in a member of a targeted group or are included in user_ids list. Deactivated+ # users are included, so that the right thing happens if they are later reactivated.+ users = user_ids_to_users(+ all_user_ids, user_profile.realm, allow_deactivated=True, allow_bots=False+ )++ for setting_name, requested_value in request_settings.items():+ if target_users.skip_if_already_edited:+ already_edited_user_ids = set(+ RealmAuditLog.objects.filter(+ modified_user__in=users,+ event_type=AuditLogEventType.USER_SETTING_CHANGED,+ extra_data__property=setting_name,+ ).values_list("modified_user_id", flat=True)+ )++ eligible_users = [user for user in users if user.id not in already_edited_user_ids]+ else:+ eligible_users = users++ users_to_update = [+ user for user in eligible_users if getattr(user, setting_name) != requested_value+ ]++ if users_to_update:+ bulk_change_user_setting(+ user_profile.realm,+ users_to_update,+ setting_name,+ requested_value,+ acting_user=user_profile,+ )++ return json_success(request, data={})+if (default_language is not Noneor notification_sound is not None@@ -433,10 +529,8 @@ def json_change_settings(# Note that check_change_full_name strips the passed name automaticallycheck_change_full_name(user_profile, full_name, user_profile)- # Loop over user_profile.property_types- request_settings = {k: v for k, v in locals().items() if k in user_profile.property_types}for k, v in request_settings.items():- if v is not None and getattr(user_profile, k) != v:+ if getattr(user_profile, k) != v:do_change_user_setting(user_profile, k, v, acting_user=user_profile)if timezone is not None and user_profile.timezone != timezone: