def update_display_settings_backend( request: HttpRequest, user_profile: UserProfile, twenty_four_hour_time: Optional[bool]=REQ(validator=check_bool, default=None), dense_mode: Optional[bool]=REQ(validator=check_bool, default=None), starred_message_counts: Optional[bool]=REQ(validator=check_bool, default=None), fluid_layout_width: Optional[bool]=REQ(validator=check_bool, default=None), high_contrast_mode: Optional[bool]=REQ(validator=check_bool, default=None), color_scheme: Optional[int]=REQ(validator=check_int_in( UserProfile.COLOR_SCHEME_CHOICES), default=None), translate_emoticons: Optional[bool]=REQ(validator=check_bool, default=None), default_language: Optional[str]=REQ(validator=check_string, default=None), left_side_userlist: Optional[bool]=REQ(validator=check_bool, default=None), emojiset: Optional[str]=REQ(validator=check_string_in( emojiset_choices), default=None), demote_inactive_streams: Optional[int]=REQ(validator=check_int_in( UserProfile.DEMOTE_STREAMS_CHOICES), default=None), timezone: Optional[str]=REQ(validator=check_string_in(all_timezones), default=None)) -> HttpResponse: # We can't use REQ for this widget because # get_available_language_codes requires provisioning to be # complete. if (default_language is not None and default_language not in get_available_language_codes()): raise JsonableError(_("Invalid default_language")) request_settings = {k: v for k, v in list(locals().items()) if k in user_profile.property_types} result: Dict[str, Any] = {} for k, v in list(request_settings.items()): if v is not None and getattr(user_profile, k) != v: do_set_user_display_setting(user_profile, k, v) result[k] = v return json_success(result)
def change_plan_status( request: HttpRequest, user: UserProfile, status: int = REQ( "status", json_validator=check_int_in([ CustomerPlan.ACTIVE, CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE, CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE, CustomerPlan.ENDED, ]), ), ) -> HttpResponse: plan = get_current_plan_by_realm(user.realm) assert plan is not None # for mypy if status == CustomerPlan.ACTIVE: assert plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE do_change_plan_status(plan, status) elif status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE: assert plan.status == CustomerPlan.ACTIVE downgrade_at_the_end_of_billing_cycle(user.realm) elif status == CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE: assert plan.billing_schedule == CustomerPlan.MONTHLY assert plan.status == CustomerPlan.ACTIVE assert plan.fixed_price is None do_change_plan_status(plan, status) elif status == CustomerPlan.ENDED: assert plan.status == CustomerPlan.FREE_TRIAL downgrade_now_without_creating_additional_invoices(user.realm) return json_success()
def update_user_backend( request: HttpRequest, user_profile: UserProfile, user_id: int, full_name: Optional[str] = REQ(default=None, validator=check_string), role: Optional[int] = REQ(default=None, validator=check_int_in( UserProfile.ROLE_TYPES, )), profile_data: Optional[List[Dict[str, Optional[Union[ int, str, List[int]]]]]] = REQ( default=None, validator=check_profile_data, ), ) -> HttpResponse: target = access_user_by_id(user_profile, user_id, allow_deactivated=True, allow_bots=True, for_admin=True) if role is not None and target.role != role: # Require that the current user has permissions to # grant/remove the role in question. access_user_by_id has # already verified we're an administrator; here we enforce # that only owners can toggle the is_realm_owner flag. if UserProfile.ROLE_REALM_OWNER in [ role, target.role ] and not user_profile.is_realm_owner: raise OrganizationOwnerRequired() if target.role == UserProfile.ROLE_REALM_OWNER and check_last_owner( user_profile): return json_error( _('The owner permission cannot be removed from the only organization owner.' )) do_change_user_role(target, role, acting_user=user_profile) if (full_name is not None and target.full_name != full_name and full_name.strip() != ""): # We don't respect `name_changes_disabled` here because the request # is on behalf of the administrator. check_change_full_name(target, full_name, user_profile) if profile_data is not None: clean_profile_data = [] for entry in profile_data: assert isinstance(entry["id"], int) if entry["value"] is None or not entry["value"]: field_id = entry["id"] check_remove_custom_profile_field_value(target, field_id) else: clean_profile_data.append({ "id": entry["id"], "value": entry["value"], }) validate_user_custom_profile_data(target.realm.id, clean_profile_data) do_update_user_custom_profile_data_if_changed(target, clean_profile_data) return json_success()
def update_user_backend(request: HttpRequest, user_profile: UserProfile, user_id: int, full_name: Optional[str]=REQ(default=None, validator=check_string), role: Optional[int]=REQ(default=None, validator=check_int_in( UserProfile.ROLE_TYPES)), profile_data: Optional[List[Dict[str, Union[int, str, List[int]]]]]= REQ(default=None, validator=check_list(check_dict([('id', check_int)])))) -> HttpResponse: target = access_user_by_id(user_profile, user_id, allow_deactivated=True, allow_bots=True) if role is not None and target.role != role: if target.role == UserProfile.ROLE_REALM_OWNER and check_last_owner(user_profile): return json_error(_('The owner permission cannot be removed from the only organization owner.')) if UserProfile.ROLE_REALM_OWNER in [role, target.role] and not user_profile.is_realm_owner: raise OrganizationOwnerRequired() do_change_user_role(target, role) if (full_name is not None and target.full_name != full_name and full_name.strip() != ""): # We don't respect `name_changes_disabled` here because the request # is on behalf of the administrator. check_change_full_name(target, full_name, user_profile) if profile_data is not None: clean_profile_data = [] for entry in profile_data: if not entry["value"]: field_id = entry["id"] check_remove_custom_profile_field_value(target, field_id) else: clean_profile_data.append(entry) validate_user_custom_profile_data(target.realm.id, clean_profile_data) do_update_user_custom_profile_data_if_changed(target, clean_profile_data) return json_success()
def update_stream_backend( request: HttpRequest, user_profile: UserProfile, stream_id: int, description: Optional[str]=REQ(validator=check_capped_string( Stream.MAX_DESCRIPTION_LENGTH), default=None), is_private: Optional[bool]=REQ(validator=check_bool, default=None), is_announcement_only: Optional[bool]=REQ(validator=check_bool, default=None), stream_post_policy: Optional[int]=REQ(validator=check_int_in( Stream.STREAM_POST_POLICY_TYPES), default=None), history_public_to_subscribers: Optional[bool]=REQ(validator=check_bool, default=None), new_name: Optional[str]=REQ(validator=check_string, default=None), message_retention_days: Optional[Union[int, str]]=REQ(validator=check_string_or_int, default=None), ) -> HttpResponse: # We allow realm administrators to to update the stream name and # description even for private streams. stream = access_stream_for_delete_or_update(user_profile, stream_id) if message_retention_days is not None: if not user_profile.is_realm_owner: raise OrganizationOwnerRequired() user_profile.realm.ensure_not_on_limited_plan() message_retention_days_value = parse_message_retention_days( message_retention_days, Stream.MESSAGE_RETENTION_SPECIAL_VALUES_MAP) do_change_stream_message_retention_days(stream, message_retention_days_value) if description is not None: if '\n' in description: # We don't allow newline characters in stream descriptions. description = description.replace("\n", " ") do_change_stream_description(stream, description) if new_name is not None: new_name = new_name.strip() if stream.name == new_name: return json_error(_("Stream already has that name!")) if stream.name.lower() != new_name.lower(): # Check that the stream name is available (unless we are # are only changing the casing of the stream name). check_stream_name_available(user_profile.realm, new_name) do_rename_stream(stream, new_name, user_profile) if is_announcement_only is not None: # is_announcement_only is a legacy way to specify # stream_post_policy. We can probably just delete this code, # since we're not aware of clients that used it, but we're # keeping it for backwards-compatibility for now. stream_post_policy = Stream.STREAM_POST_POLICY_EVERYONE if is_announcement_only: stream_post_policy = Stream.STREAM_POST_POLICY_ADMINS if stream_post_policy is not None: do_change_stream_post_policy(stream, stream_post_policy) # But we require even realm administrators to be actually # subscribed to make a private stream public. if is_private is not None: (stream, recipient, sub) = access_stream_by_id(user_profile, stream_id) do_change_stream_invite_only(stream, is_private, history_public_to_subscribers) return json_success()
def update_realm_user_settings_defaults( request: HttpRequest, user_profile: UserProfile, dense_mode: Optional[bool] = REQ(json_validator=check_bool, default=None), starred_message_counts: Optional[bool] = REQ(json_validator=check_bool, default=None), fluid_layout_width: Optional[bool] = REQ(json_validator=check_bool, default=None), high_contrast_mode: Optional[bool] = REQ(json_validator=check_bool, default=None), color_scheme: Optional[int] = REQ(json_validator=check_int_in( UserProfile.COLOR_SCHEME_CHOICES), default=None), translate_emoticons: Optional[bool] = REQ(json_validator=check_bool, default=None), default_view: Optional[str] = REQ( str_validator=check_string_in(default_view_options), default=None), escape_navigates_to_default_view: Optional[bool] = REQ( json_validator=check_bool, default=None), left_side_userlist: Optional[bool] = REQ(json_validator=check_bool, default=None), emojiset: Optional[str] = REQ( str_validator=check_string_in(emojiset_choices), default=None), demote_inactive_streams: Optional[int] = REQ(json_validator=check_int_in( UserProfile.DEMOTE_STREAMS_CHOICES), default=None), enable_stream_desktop_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_stream_email_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_stream_push_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_stream_audible_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), wildcard_mentions_notify: Optional[bool] = REQ(json_validator=check_bool, default=None), notification_sound: Optional[str] = REQ(default=None), enable_desktop_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_sounds: Optional[bool] = REQ(json_validator=check_bool, default=None), enable_offline_email_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_offline_push_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_online_push_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_digest_emails: Optional[bool] = REQ(json_validator=check_bool, default=None), # enable_login_emails is not included here, because we don't want # security-related settings to be controlled by organization administrators. # enable_marketing_emails is not included here, since we don't at # present allow organizations to customize this. (The user's selection # in the signup form takes precedence over RealmUserDefault). # # We may want to change this model in the future, since some SSO signups # do not offer an opportunity to prompt the user at all during signup. message_content_in_email_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), pm_content_in_desktop_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), desktop_icon_count_display: Optional[int] = REQ( json_validator=check_int_in( UserProfile.DESKTOP_ICON_COUNT_DISPLAY_CHOICES), default=None), realm_name_in_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), presence_enabled: Optional[bool] = REQ(json_validator=check_bool, default=None), enter_sends: Optional[bool] = REQ(json_validator=check_bool, default=None), enable_drafts_synchronization: Optional[bool] = REQ( json_validator=check_bool, default=None), email_notifications_batching_period_seconds: Optional[int] = REQ( json_validator=check_int, default=None), twenty_four_hour_time: Optional[bool] = REQ(json_validator=check_bool, default=None), send_stream_typing_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), send_private_typing_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), send_read_receipts: Optional[bool] = REQ(json_validator=check_bool, default=None), ) -> HttpResponse: if notification_sound is not None or email_notifications_batching_period_seconds is not None: check_settings_values(notification_sound, email_notifications_batching_period_seconds) realm_user_default = RealmUserDefault.objects.get(realm=user_profile.realm) request_settings = { k: v for k, v in list(locals().items()) if (k in RealmUserDefault.property_types) } for k, v in list(request_settings.items()): if v is not None and getattr(realm_user_default, k) != v: do_set_realm_user_default_setting(realm_user_default, k, v, acting_user=user_profile) # TODO: Extract `ignored_parameters_unsupported` to be a common feature of the REQ framework. from zerver.lib.request import RequestNotes request_notes = RequestNotes.get_notes(request) for req_var in request.POST: if req_var not in request_notes.processed_parameters: request_notes.ignored_parameters.add(req_var) result: Dict[str, Any] = {} if len(request_notes.ignored_parameters) > 0: result["ignored_parameters_unsupported"] = list( request_notes.ignored_parameters) return json_success(result)
def add_subscriptions_backend( request: HttpRequest, user_profile: UserProfile, streams_raw: Iterable[Dict[str, str]] = REQ( "subscriptions", validator=check_list( check_dict_only([('name', check_string)], optional_keys=[ ('color', check_color), ('description', check_capped_string( Stream.MAX_DESCRIPTION_LENGTH)), ]), )), invite_only: bool = REQ(validator=check_bool, default=False), stream_post_policy: int = REQ(validator=check_int_in( Stream.STREAM_POST_POLICY_TYPES), default=Stream.STREAM_POST_POLICY_EVERYONE), history_public_to_subscribers: Optional[bool] = REQ(validator=check_bool, default=None), message_retention_days: Union[str, int] = REQ(validator=check_string_or_int, default="realm_default"), announce: bool = REQ(validator=check_bool, default=False), principals: Union[Sequence[str], Sequence[int]] = REQ(validator=check_union( [check_list(check_string), check_list(check_int)]), default=[]), authorization_errors_fatal: bool = REQ(validator=check_bool, default=True), ) -> HttpResponse: stream_dicts = [] color_map = {} for stream_dict in streams_raw: # 'color' field is optional # check for its presence in the streams_raw first if 'color' in stream_dict: color_map[stream_dict['name']] = stream_dict['color'] if 'description' in stream_dict: # We don't allow newline characters in stream descriptions. stream_dict['description'] = stream_dict['description'].replace( "\n", " ") stream_dict_copy: Dict[str, Any] = {} for field in stream_dict: stream_dict_copy[field] = stream_dict[field] # Strip the stream name here. stream_dict_copy['name'] = stream_dict_copy['name'].strip() stream_dict_copy["invite_only"] = invite_only stream_dict_copy["stream_post_policy"] = stream_post_policy stream_dict_copy[ "history_public_to_subscribers"] = history_public_to_subscribers stream_dict_copy[ "message_retention_days"] = parse_message_retention_days( message_retention_days) stream_dicts.append(stream_dict_copy) # Validation of the streams arguments, including enforcement of # can_create_streams policy and check_stream_name policy is inside # list_to_streams. existing_streams, created_streams = \ list_to_streams(stream_dicts, user_profile, autocreate=True) authorized_streams, unauthorized_streams = \ filter_stream_authorization(user_profile, existing_streams) if len(unauthorized_streams) > 0 and authorization_errors_fatal: return json_error( _("Unable to access stream ({stream_name}).").format( stream_name=unauthorized_streams[0].name, )) # Newly created streams are also authorized for the creator streams = authorized_streams + created_streams if len(principals) > 0: if user_profile.realm.is_zephyr_mirror_realm and not all( stream.invite_only for stream in streams): return json_error( _("You can only invite other Zephyr mirroring users to private streams." )) if not user_profile.can_subscribe_other_users(): if user_profile.realm.invite_to_stream_policy == Realm.POLICY_ADMINS_ONLY: return json_error( _("Only administrators can modify other users' subscriptions." )) # Realm.POLICY_MEMBERS_ONLY only fails if the # user is a guest, which happens in the decorator above. assert user_profile.realm.invite_to_stream_policy == \ Realm.POLICY_FULL_MEMBERS_ONLY return json_error( _("Your account is too new to modify other users' subscriptions." )) subscribers = { principal_to_user_profile(user_profile, principal) for principal in principals } else: subscribers = {user_profile} (subscribed, already_subscribed) = bulk_add_subscriptions(streams, subscribers, acting_user=user_profile, color_map=color_map) # We can assume unique emails here for now, but we should eventually # convert this function to be more id-centric. email_to_user_profile: Dict[str, UserProfile] = dict() result: Dict[str, Any] = dict(subscribed=defaultdict(list), already_subscribed=defaultdict(list)) for (subscriber, stream) in subscribed: result["subscribed"][subscriber.email].append(stream.name) email_to_user_profile[subscriber.email] = subscriber for (subscriber, stream) in already_subscribed: result["already_subscribed"][subscriber.email].append(stream.name) bots = {subscriber.email: subscriber.is_bot for subscriber in subscribers} newly_created_stream_names = {s.name for s in created_streams} # Inform the user if someone else subscribed them to stuff, # or if a new stream was created with the "announce" option. notifications = [] if len(principals) > 0 and result["subscribed"]: for email, subscribed_stream_names in result["subscribed"].items(): if email == user_profile.email: # Don't send a Zulip if you invited yourself. continue if bots[email]: # Don't send invitation Zulips to bots continue # For each user, we notify them about newly subscribed streams, except for # streams that were newly created. notify_stream_names = set( subscribed_stream_names) - newly_created_stream_names if not notify_stream_names: continue msg = you_were_just_subscribed_message( acting_user=user_profile, stream_names=notify_stream_names, ) sender = get_system_bot(settings.NOTIFICATION_BOT) notifications.append( internal_prep_private_message( realm=user_profile.realm, sender=sender, recipient_user=email_to_user_profile[email], content=msg)) if announce and len(created_streams) > 0: notifications_stream = user_profile.realm.get_notifications_stream() if notifications_stream is not None: if len(created_streams) > 1: content = _( "@_**%(user_name)s|%(user_id)d** created the following streams: %(stream_str)s." ) else: content = _( "@_**%(user_name)s|%(user_id)d** created a new stream %(stream_str)s." ) content = content % { 'user_name': user_profile.full_name, 'user_id': user_profile.id, 'stream_str': ", ".join(f'#**{s.name}**' for s in created_streams) } sender = get_system_bot(settings.NOTIFICATION_BOT) topic = _('new streams') notifications.append( internal_prep_stream_message( realm=user_profile.realm, sender=sender, stream=notifications_stream, topic=topic, content=content, ), ) if not user_profile.realm.is_zephyr_mirror_realm and len( created_streams) > 0: sender = get_system_bot(settings.NOTIFICATION_BOT) for stream in created_streams: notifications.append( internal_prep_stream_message( realm=user_profile.realm, sender=sender, stream=stream, topic=Realm.STREAM_EVENTS_NOTIFICATION_TOPIC, content=_('Stream created by @_**{user_name}|{user_id}**.' ).format( user_name=user_profile.full_name, user_id=user_profile.id, ), ), ) if len(notifications) > 0: do_send_messages(notifications, mark_as_read=[user_profile.id]) result["subscribed"] = dict(result["subscribed"]) result["already_subscribed"] = dict(result["already_subscribed"]) if not authorization_errors_fatal: result["unauthorized"] = [s.name for s in unauthorized_streams] return json_success(result)
def update_realm( request: HttpRequest, user_profile: UserProfile, name: Optional[str] = REQ(validator=check_string, default=None), description: Optional[str] = REQ(validator=check_string, default=None), emails_restricted_to_domains: Optional[bool] = REQ(validator=check_bool, default=None), disallow_disposable_email_addresses: Optional[bool] = REQ( validator=check_bool, default=None), invite_required: Optional[bool] = REQ(validator=check_bool, default=None), invite_by_admins_only: Optional[bool] = REQ(validator=check_bool, default=None), name_changes_disabled: Optional[bool] = REQ(validator=check_bool, default=None), email_changes_disabled: Optional[bool] = REQ(validator=check_bool, default=None), avatar_changes_disabled: Optional[bool] = REQ(validator=check_bool, default=None), inline_image_preview: Optional[bool] = REQ(validator=check_bool, default=None), inline_url_embed_preview: Optional[bool] = REQ(validator=check_bool, default=None), add_emoji_by_admins_only: Optional[bool] = REQ(validator=check_bool, default=None), allow_message_deleting: Optional[bool] = REQ(validator=check_bool, default=None), message_content_delete_limit_seconds: Optional[int] = REQ( converter=to_non_negative_int, default=None), allow_message_editing: Optional[bool] = REQ(validator=check_bool, default=None), allow_community_topic_editing: Optional[bool] = REQ(validator=check_bool, default=None), mandatory_topics: Optional[bool] = REQ(validator=check_bool, default=None), message_content_edit_limit_seconds: Optional[int] = REQ( converter=to_non_negative_int, default=None), allow_edit_history: Optional[bool] = REQ(validator=check_bool, default=None), default_language: Optional[str] = REQ(validator=check_string, default=None), waiting_period_threshold: Optional[int] = REQ( converter=to_non_negative_int, default=None), authentication_methods: Optional[Dict[Any, Any]] = REQ(validator=check_dict([]), default=None), notifications_stream_id: Optional[int] = REQ(validator=check_int, default=None), signup_notifications_stream_id: Optional[int] = REQ(validator=check_int, default=None), message_retention_days: Optional[int] = REQ( converter=to_positive_or_allowed_int(Realm.RETAIN_MESSAGE_FOREVER), default=None), send_welcome_emails: Optional[bool] = REQ(validator=check_bool, default=None), digest_emails_enabled: Optional[bool] = REQ(validator=check_bool, default=None), message_content_allowed_in_email_notifications: Optional[bool] = REQ( validator=check_bool, default=None), bot_creation_policy: Optional[int] = REQ(validator=check_int_in( Realm.BOT_CREATION_POLICY_TYPES), default=None), create_stream_policy: Optional[int] = REQ(validator=check_int_in( Realm.COMMON_POLICY_TYPES), default=None), invite_to_stream_policy: Optional[int] = REQ(validator=check_int_in( Realm.COMMON_POLICY_TYPES), default=None), user_group_edit_policy: Optional[int] = REQ(validator=check_int_in( Realm.USER_GROUP_EDIT_POLICY_TYPES), default=None), private_message_policy: Optional[int] = REQ(validator=check_int_in( Realm.PRIVATE_MESSAGE_POLICY_TYPES), default=None), email_address_visibility: Optional[int] = REQ(validator=check_int_in( Realm.EMAIL_ADDRESS_VISIBILITY_TYPES), default=None), default_twenty_four_hour_time: Optional[bool] = REQ(validator=check_bool, default=None), video_chat_provider: Optional[int] = REQ(validator=check_int, default=None), google_hangouts_domain: Optional[str] = REQ(validator=check_string, default=None), default_code_block_language: Optional[str] = REQ(validator=check_string, default=None), digest_weekday: Optional[int] = REQ(validator=check_int_in( Realm.DIGEST_WEEKDAY_VALUES), default=None), ) -> HttpResponse: realm = user_profile.realm # Additional validation/error checking beyond types go here, so # the entire request can succeed or fail atomically. if default_language is not None and default_language not in get_available_language_codes( ): raise JsonableError(_("Invalid language '%s'") % (default_language, )) if description is not None and len(description) > 1000: return json_error(_("Organization description is too long.")) if name is not None and len(name) > Realm.MAX_REALM_NAME_LENGTH: return json_error(_("Organization name is too long.")) if authentication_methods is not None and True not in list( authentication_methods.values()): return json_error( _("At least one authentication method must be enabled.")) if (video_chat_provider is not None and video_chat_provider not in {p['id'] for p in Realm.VIDEO_CHAT_PROVIDERS.values()}): return json_error( _("Invalid video_chat_provider {}").format(video_chat_provider)) if video_chat_provider == Realm.VIDEO_CHAT_PROVIDERS['google_hangouts'][ 'id']: try: validate_domain(google_hangouts_domain) except ValidationError as e: return json_error(_('Invalid domain: {}').format(e.messages[0])) if message_retention_days is not None: realm.ensure_not_on_limited_plan() # The user of `locals()` here is a bit of a code smell, but it's # restricted to the elements present in realm.property_types. # # TODO: It should be possible to deduplicate this function up # further by some more advanced usage of the # `REQ/has_request_variables` extraction. req_vars = { k: v for k, v in list(locals().items()) if k in realm.property_types } data: Dict[str, Any] = {} for k, v in list(req_vars.items()): if v is not None and getattr(realm, k) != v: do_set_realm_property(realm, k, v) if isinstance(v, str): data[k] = 'updated' else: data[k] = v # The following realm properties do not fit the pattern above # authentication_methods is not supported by the do_set_realm_property # framework because of its bitfield. if authentication_methods is not None and ( realm.authentication_methods_dict() != authentication_methods): do_set_realm_authentication_methods(realm, authentication_methods) data['authentication_methods'] = authentication_methods # The message_editing settings are coupled to each other, and thus don't fit # into the do_set_realm_property framework. if ((allow_message_editing is not None and realm.allow_message_editing != allow_message_editing) or (message_content_edit_limit_seconds is not None and realm.message_content_edit_limit_seconds != message_content_edit_limit_seconds) or (allow_community_topic_editing is not None and realm.allow_community_topic_editing != allow_community_topic_editing)): if allow_message_editing is None: allow_message_editing = realm.allow_message_editing if message_content_edit_limit_seconds is None: message_content_edit_limit_seconds = realm.message_content_edit_limit_seconds if allow_community_topic_editing is None: allow_community_topic_editing = realm.allow_community_topic_editing do_set_realm_message_editing(realm, allow_message_editing, message_content_edit_limit_seconds, allow_community_topic_editing) data['allow_message_editing'] = allow_message_editing data[ 'message_content_edit_limit_seconds'] = message_content_edit_limit_seconds data['allow_community_topic_editing'] = allow_community_topic_editing if (message_content_delete_limit_seconds is not None and realm.message_content_delete_limit_seconds != message_content_delete_limit_seconds): do_set_realm_message_deleting(realm, message_content_delete_limit_seconds) data[ 'message_content_delete_limit_seconds'] = message_content_delete_limit_seconds # Realm.notifications_stream and Realm.signup_notifications_stream are not boolean, # str or integer field, and thus doesn't fit into the do_set_realm_property framework. if notifications_stream_id is not None: if realm.notifications_stream is None or (realm.notifications_stream.id != notifications_stream_id): new_notifications_stream = None if notifications_stream_id >= 0: (new_notifications_stream, recipient, sub) = access_stream_by_id(user_profile, notifications_stream_id) do_set_realm_notifications_stream(realm, new_notifications_stream, notifications_stream_id) data['notifications_stream_id'] = notifications_stream_id if signup_notifications_stream_id is not None: if realm.signup_notifications_stream is None or ( realm.signup_notifications_stream.id != signup_notifications_stream_id): new_signup_notifications_stream = None if signup_notifications_stream_id >= 0: (new_signup_notifications_stream, recipient, sub) = access_stream_by_id(user_profile, signup_notifications_stream_id) do_set_realm_signup_notifications_stream( realm, new_signup_notifications_stream, signup_notifications_stream_id) data[ 'signup_notifications_stream_id'] = signup_notifications_stream_id if default_code_block_language is not None: # Migrate '', used in the API to encode the default/None behavior of this feature. if default_code_block_language == '': data['default_code_block_language'] = None else: data['default_code_block_language'] = default_code_block_language return json_success(data)
def update_plan( request: HttpRequest, user: UserProfile, status: Optional[int] = REQ( "status", json_validator=check_int_in([ CustomerPlan.ACTIVE, CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE, CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE, CustomerPlan.ENDED, ]), default=None, ), licenses: Optional[int] = REQ("licenses", json_validator=check_int, default=None), licenses_at_next_renewal: Optional[int] = REQ("licenses_at_next_renewal", json_validator=check_int, default=None), ) -> HttpResponse: plan = get_current_plan_by_realm(user.realm) assert plan is not None # for mypy new_plan, last_ledger_entry = make_end_of_cycle_updates_if_needed( plan, timezone_now()) if new_plan is not None: raise JsonableError( _("Unable to update the plan. The plan has been expired and replaced with a new plan." )) if last_ledger_entry is None: raise JsonableError( _("Unable to update the plan. The plan has ended.")) if status is not None: if status == CustomerPlan.ACTIVE: assert plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE do_change_plan_status(plan, status) elif status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE: assert plan.status == CustomerPlan.ACTIVE downgrade_at_the_end_of_billing_cycle(user.realm) elif status == CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE: assert plan.billing_schedule == CustomerPlan.MONTHLY assert plan.status == CustomerPlan.ACTIVE assert plan.fixed_price is None do_change_plan_status(plan, status) elif status == CustomerPlan.ENDED: assert plan.is_free_trial() downgrade_now_without_creating_additional_invoices(user.realm) return json_success() if licenses is not None: if plan.automanage_licenses: raise JsonableError( _("Unable to update licenses manually. Your plan is on automatic license management." )) if last_ledger_entry.licenses == licenses: raise JsonableError( _("Your plan is already on {licenses} licenses in the current billing period." ).format(licenses=licenses)) if last_ledger_entry.licenses > licenses: raise JsonableError( _("You cannot decrease the licenses in the current billing period." ).format(licenses=licenses)) validate_licenses(plan.charge_automatically, licenses, get_latest_seat_count(user.realm)) update_license_ledger_for_manual_plan(plan, timezone_now(), licenses=licenses) return json_success() if licenses_at_next_renewal is not None: if plan.automanage_licenses: raise JsonableError( _("Unable to update licenses manually. Your plan is on automatic license management." )) if last_ledger_entry.licenses_at_next_renewal == licenses_at_next_renewal: raise JsonableError( _("Your plan is already scheduled to renew with {licenses_at_next_renewal} licenses." ).format(licenses_at_next_renewal=licenses_at_next_renewal)) validate_licenses( plan.charge_automatically, licenses_at_next_renewal, get_latest_seat_count(user.realm), ) update_license_ledger_for_manual_plan( plan, timezone_now(), licenses_at_next_renewal=licenses_at_next_renewal) return json_success() raise JsonableError(_("Nothing to change."))
def update_stream_backend( request: HttpRequest, user_profile: UserProfile, stream_id: int, description: Optional[str] = REQ(str_validator=check_capped_string( Stream.MAX_DESCRIPTION_LENGTH), default=None), is_private: Optional[bool] = REQ(json_validator=check_bool, default=None), is_announcement_only: Optional[bool] = REQ(json_validator=check_bool, default=None), stream_post_policy: Optional[int] = REQ(json_validator=check_int_in( Stream.STREAM_POST_POLICY_TYPES), default=None), history_public_to_subscribers: Optional[bool] = REQ( json_validator=check_bool, default=None), is_web_public: Optional[bool] = REQ(json_validator=check_bool, default=None), new_name: Optional[str] = REQ(default=None), message_retention_days: Optional[Union[int, str]] = REQ( json_validator=check_string_or_int, default=None), ) -> HttpResponse: # We allow realm administrators to to update the stream name and # description even for private streams. (stream, sub) = access_stream_for_delete_or_update(user_profile, stream_id) if message_retention_days is not None: if not user_profile.is_realm_owner: raise OrganizationOwnerRequired() user_profile.realm.ensure_not_on_limited_plan() new_message_retention_days_value = parse_message_retention_days( message_retention_days, Stream.MESSAGE_RETENTION_SPECIAL_VALUES_MAP) do_change_stream_message_retention_days( stream, user_profile, new_message_retention_days_value) if description is not None: if "\n" in description: # We don't allow newline characters in stream descriptions. description = description.replace("\n", " ") do_change_stream_description(stream, description, acting_user=user_profile) if new_name is not None: new_name = new_name.strip() if stream.name == new_name: raise JsonableError(_("Stream already has that name!")) if stream.name.lower() != new_name.lower(): # Check that the stream name is available (unless we are # are only changing the casing of the stream name). check_stream_name_available(user_profile.realm, new_name) do_rename_stream(stream, new_name, user_profile) if is_announcement_only is not None: # is_announcement_only is a legacy way to specify # stream_post_policy. We can probably just delete this code, # since we're not aware of clients that used it, but we're # keeping it for backwards-compatibility for now. stream_post_policy = Stream.STREAM_POST_POLICY_EVERYONE if is_announcement_only: stream_post_policy = Stream.STREAM_POST_POLICY_ADMINS if stream_post_policy is not None: do_change_stream_post_policy(stream, stream_post_policy, acting_user=user_profile) # But we require even realm administrators to be actually # subscribed to make a private stream public. if is_private is not None: default_stream_ids = { s.id for s in get_default_streams_for_realm(stream.realm_id) } (stream, sub) = access_stream_by_id(user_profile, stream_id) if is_private and stream.id in default_stream_ids: raise JsonableError(_("Default streams cannot be made private.")) if is_web_public: # Enforce restrictions on creating web-public streams. if not user_profile.realm.web_public_streams_enabled(): raise JsonableError(_("Web-public streams are not enabled.")) if not user_profile.can_create_web_public_streams(): raise JsonableError(_("Insufficient permission")) # Forbid parameter combinations that are inconsistent if is_private or history_public_to_subscribers is False: raise JsonableError(_("Invalid parameters")) if is_private is not None or is_web_public is not None: do_change_stream_permission( stream, invite_only=is_private, history_public_to_subscribers=history_public_to_subscribers, is_web_public=is_web_public, acting_user=user_profile, ) return json_success(request)
_check_realm_user_person = check_dict_only( required_keys=[ # vertical formatting ("user_id", check_int), ], optional_keys=[ ("avatar_source", check_string), ("avatar_url", check_none_or(check_string)), ("avatar_url_medium", check_none_or(check_string)), ("avatar_version", check_int), ("bot_owner_id", check_int), ("custom_profile_field", _check_custom_profile_field), ("delivery_email", check_string), ("full_name", check_string), ("role", check_int_in(UserProfile.ROLE_TYPES)), ("email", check_string), ("user_id", check_int), ("timezone", check_string), ], ) _check_realm_user_update = check_events_dict( required_keys=[ ("type", equals("realm_user")), ("op", equals("update")), ("person", _check_realm_user_person), ] )
("rendered_description", check_string), ("stream_id", check_int), ("stream_post_policy", check_int), ("date_created", check_int), ] subscription_fields: Sequence[Tuple[str, Validator[object]]] = [ *basic_stream_fields, ("audible_notifications", check_none_or(check_bool)), ("color", check_string), ("desktop_notifications", check_none_or(check_bool)), ("email_address", check_string), ("email_notifications", check_none_or(check_bool)), ("in_home_view", check_bool), ("is_muted", check_bool), ("role", check_int_in(Subscription.ROLE_TYPES)), ("pin_to_top", check_bool), ("push_notifications", check_none_or(check_bool)), ("stream_weekly_traffic", check_none_or(check_int)), ("wildcard_mentions_notify", check_none_or(check_bool)), ] def check_events_dict( required_keys: Sequence[Tuple[str, Validator[object]]], optional_keys: Sequence[Tuple[str, Validator[object]]] = [], ) -> Validator[Dict[str, object]]: """ This is just a tiny wrapper on check_dict, but it provides some minor benefits:
def patch_bot_backend( request: HttpRequest, user_profile: UserProfile, bot_id: int, full_name: Optional[str] = REQ(default=None), role: Optional[int] = REQ( default=None, json_validator=check_int_in(UserProfile.ROLE_TYPES, ), ), bot_owner_id: Optional[int] = REQ(json_validator=check_int, default=None), config_data: Optional[Dict[str, str]] = REQ( default=None, json_validator=check_dict(value_validator=check_string)), service_payload_url: Optional[str] = REQ(json_validator=check_url, default=None), service_interface: int = REQ(json_validator=check_int, default=1), default_sending_stream: Optional[str] = REQ(default=None), default_events_register_stream: Optional[str] = REQ(default=None), default_all_public_streams: Optional[bool] = REQ( default=None, json_validator=check_bool), ) -> HttpResponse: bot = access_bot_by_id(user_profile, bot_id) if full_name is not None: check_change_bot_full_name(bot, full_name, user_profile) if role is not None and bot.role != role: # Logic duplicated from update_user_backend. if UserProfile.ROLE_REALM_OWNER in [ role, bot.role ] and not user_profile.is_realm_owner: raise OrganizationOwnerRequired() do_change_user_role(bot, role, acting_user=user_profile) if bot_owner_id is not None: try: owner = get_user_profile_by_id_in_realm(bot_owner_id, user_profile.realm) except UserProfile.DoesNotExist: raise JsonableError(_("Failed to change owner, no such user")) if not owner.is_active: raise JsonableError( _("Failed to change owner, user is deactivated")) if owner.is_bot: raise JsonableError( _("Failed to change owner, bots can't own other bots")) previous_owner = bot.bot_owner if previous_owner != owner: do_change_bot_owner(bot, owner, user_profile) if default_sending_stream is not None: if default_sending_stream == "": stream: Optional[Stream] = None else: (stream, sub) = access_stream_by_name(user_profile, default_sending_stream) do_change_default_sending_stream(bot, stream, acting_user=user_profile) if default_events_register_stream is not None: if default_events_register_stream == "": stream = None else: (stream, sub) = access_stream_by_name(user_profile, default_events_register_stream) do_change_default_events_register_stream(bot, stream, acting_user=user_profile) if default_all_public_streams is not None: do_change_default_all_public_streams(bot, default_all_public_streams, acting_user=user_profile) if service_payload_url is not None: check_valid_interface_type(service_interface) assert service_interface is not None do_update_outgoing_webhook_service(bot, service_interface, service_payload_url) if config_data is not None: do_update_bot_config_data(bot, config_data) if len(request.FILES) == 0: pass elif len(request.FILES) == 1: user_file = list(request.FILES.values())[0] assert isinstance(user_file, UploadedFile) assert user_file.size is not None upload_avatar_image(user_file, user_profile, bot) avatar_source = UserProfile.AVATAR_FROM_USER do_change_avatar_fields(bot, avatar_source, acting_user=user_profile) else: raise JsonableError(_("You may only upload one file at a time")) json_result = dict( full_name=bot.full_name, avatar_url=avatar_url(bot), service_interface=service_interface, service_payload_url=service_payload_url, config_data=config_data, default_sending_stream=get_stream_name(bot.default_sending_stream), default_events_register_stream=get_stream_name( bot.default_events_register_stream), default_all_public_streams=bot.default_all_public_streams, ) # Don't include the bot owner in case it is not set. # Default bots have no owner. if bot.bot_owner is not None: json_result["bot_owner"] = bot.bot_owner.email return json_success(request, data=json_result)
def update_realm( request: HttpRequest, user_profile: UserProfile, name: Optional[str] = REQ(validator=check_string, default=None), description: Optional[str] = REQ(validator=check_string, default=None), emails_restricted_to_domains: Optional[bool] = REQ(validator=check_bool, default=None), disallow_disposable_email_addresses: Optional[bool] = REQ( validator=check_bool, default=None), invite_required: Optional[bool] = REQ(validator=check_bool, default=None), invite_by_admins_only: Optional[bool] = REQ(validator=check_bool, default=None), name_changes_disabled: Optional[bool] = REQ(validator=check_bool, default=None), email_changes_disabled: Optional[bool] = REQ(validator=check_bool, default=None), avatar_changes_disabled: Optional[bool] = REQ(validator=check_bool, default=None), inline_image_preview: Optional[bool] = REQ(validator=check_bool, default=None), inline_url_embed_preview: Optional[bool] = REQ(validator=check_bool, default=None), add_emoji_by_admins_only: Optional[bool] = REQ(validator=check_bool, default=None), allow_message_deleting: Optional[bool] = REQ(validator=check_bool, default=None), message_content_delete_limit_seconds: Optional[int] = REQ( converter=to_non_negative_int, default=None), allow_message_editing: Optional[bool] = REQ(validator=check_bool, default=None), testFeature=REQ(validator=check_string, default=None), #testFeature=REQ(validator=[bool], default=None), allow_community_topic_editing: Optional[bool] = REQ(validator=check_bool, default=None), mandatory_topics: Optional[bool] = REQ(validator=check_bool, default=None), message_content_edit_limit_seconds: Optional[int] = REQ( converter=to_non_negative_int, default=None), allow_edit_history: Optional[bool] = REQ(validator=check_bool, default=None), default_language: Optional[str] = REQ(validator=check_string, default=None), waiting_period_threshold: Optional[int] = REQ( converter=to_non_negative_int, default=None), authentication_methods: Optional[Dict[Any, Any]] = REQ(validator=check_dict([]), default=None), notifications_stream_id: Optional[int] = REQ(validator=check_int, default=None), signup_notifications_stream_id: Optional[int] = REQ(validator=check_int, default=None), message_retention_days: Optional[int] = REQ( converter=to_not_negative_int_or_none, default=None), send_welcome_emails: Optional[bool] = REQ(validator=check_bool, default=None), digest_emails_enabled: Optional[bool] = REQ(validator=check_bool, default=None), message_content_allowed_in_email_notifications: Optional[bool] = REQ( validator=check_bool, default=None), bot_creation_policy: Optional[int] = REQ(validator=check_int_in( Realm.BOT_CREATION_POLICY_TYPES), default=None), create_stream_policy: Optional[int] = REQ(validator=check_int_in( Realm.CREATE_STREAM_POLICY_TYPES), default=None), invite_to_stream_policy: Optional[int] = REQ(validator=check_int_in( Realm.INVITE_TO_STREAM_POLICY_TYPES), default=None), user_group_edit_policy: Optional[int] = REQ(validator=check_int_in( Realm.USER_GROUP_EDIT_POLICY_TYPES), default=None), private_message_policy: Optional[int] = REQ(validator=check_int_in( Realm.PRIVATE_MESSAGE_POLICY_TYPES), default=None), email_address_visibility: Optional[int] = REQ(validator=check_int_in( Realm.EMAIL_ADDRESS_VISIBILITY_TYPES), default=None), default_twenty_four_hour_time: Optional[bool] = REQ(validator=check_bool, default=None), video_chat_provider: Optional[int] = REQ(validator=check_int, default=None), google_hangouts_domain: Optional[str] = REQ(validator=check_string, default=None), zoom_user_id: Optional[str] = REQ(validator=check_string, default=None), zoom_api_key: Optional[str] = REQ(validator=check_string, default=None), zoom_api_secret: Optional[str] = REQ(validator=check_string, default=None), digest_weekday: Optional[int] = REQ(validator=check_int_in( Realm.DIGEST_WEEKDAY_VALUES), default=None), ) -> HttpResponse: realm = user_profile.realm # Additional validation/error checking beyond types go here, so # the entire request can succeed or fail atomically. if default_language is not None and default_language not in get_available_language_codes( ): raise JsonableError(_("Invalid language '%s'") % (default_language, )) if description is not None and len(description) > 1000: return json_error(_("Organization description is too long.")) if name is not None and len(name) > Realm.MAX_REALM_NAME_LENGTH: return json_error(_("Organization name is too long.")) if authentication_methods is not None and True not in list( authentication_methods.values()): return json_error( _("At least one authentication method must be enabled.")) if (video_chat_provider is not None and video_chat_provider not in set( p['id'] for p in Realm.VIDEO_CHAT_PROVIDERS.values())): return json_error( _("Invalid video_chat_provider {}").format(video_chat_provider)) if video_chat_provider == Realm.VIDEO_CHAT_PROVIDERS['google_hangouts'][ 'id']: try: validate_domain(google_hangouts_domain) except ValidationError as e: return json_error(_('Invalid domain: {}').format(e.messages[0])) if video_chat_provider == Realm.VIDEO_CHAT_PROVIDERS['zoom']['id']: if not zoom_api_secret: # Use the saved Zoom API secret if a new value isn't being sent zoom_api_secret = user_profile.realm.zoom_api_secret if not zoom_user_id: return json_error(_('User ID cannot be empty')) if not zoom_api_key: return json_error(_('API key cannot be empty')) if not zoom_api_secret: return json_error(_('API secret cannot be empty')) # If any of the Zoom settings have changed, validate the Zoom credentials. # # Technically, we could call some other API endpoint that # doesn't create a video call link, but this is a nicer # end-to-end test, since it verifies that the Zoom API user's # scopes includes the ability to create video calls, which is # the only capabiility we use. if ((zoom_user_id != realm.zoom_user_id or zoom_api_key != realm.zoom_api_key or zoom_api_secret != realm.zoom_api_secret) and not request_zoom_video_call_url(zoom_user_id, zoom_api_key, zoom_api_secret)): return json_error( _('Invalid credentials for the %(third_party_service)s API.') % dict(third_party_service="Zoom")) # The user of `locals()` here is a bit of a code smell, but it's # restricted to the elements present in realm.property_types. # # TODO: It should be possible to deduplicate this function up # further by some more advanced usage of the # `REQ/has_request_variables` extraction. req_vars = { k: v for k, v in list(locals().items()) if k in realm.property_types } data = {} # type: Dict[str, Any] for k, v in list(req_vars.items()): if v is not None and getattr(realm, k) != v: do_set_realm_property(realm, k, v) if isinstance(v, str): data[k] = 'updated' else: data[k] = v # The following realm properties do not fit the pattern above # authentication_methods is not supported by the do_set_realm_property # framework because of its bitfield. if authentication_methods is not None and ( realm.authentication_methods_dict() != authentication_methods): do_set_realm_authentication_methods(realm, authentication_methods) data['authentication_methods'] = authentication_methods # The message_editing settings are coupled to each other, and thus don't fit # into the do_set_realm_property framework. if ((allow_message_editing is not None and realm.allow_message_editing != allow_message_editing) or (message_content_edit_limit_seconds is not None and realm.message_content_edit_limit_seconds != message_content_edit_limit_seconds) or (allow_community_topic_editing is not None and realm.allow_community_topic_editing != allow_community_topic_editing)): if allow_message_editing is None: allow_message_editing = realm.allow_message_editing if message_content_edit_limit_seconds is None: message_content_edit_limit_seconds = realm.message_content_edit_limit_seconds if allow_community_topic_editing is None: allow_community_topic_editing = realm.allow_community_topic_editing do_set_realm_message_editing(realm, allow_message_editing, message_content_edit_limit_seconds, allow_community_topic_editing) data['allow_message_editing'] = allow_message_editing data[ 'message_content_edit_limit_seconds'] = message_content_edit_limit_seconds data['allow_community_topic_editing'] = allow_community_topic_editing if (message_content_delete_limit_seconds is not None and realm.message_content_delete_limit_seconds != message_content_delete_limit_seconds): do_set_realm_message_deleting(realm, message_content_delete_limit_seconds) data[ 'message_content_delete_limit_seconds'] = message_content_delete_limit_seconds # Realm.notifications_stream and Realm.signup_notifications_stream are not boolean, # str or integer field, and thus doesn't fit into the do_set_realm_property framework. if notifications_stream_id is not None: if realm.notifications_stream is None or (realm.notifications_stream.id != notifications_stream_id): new_notifications_stream = None if notifications_stream_id >= 0: (new_notifications_stream, recipient, sub) = access_stream_by_id(user_profile, notifications_stream_id) do_set_realm_notifications_stream(realm, new_notifications_stream, notifications_stream_id) data['notifications_stream_id'] = notifications_stream_id if signup_notifications_stream_id is not None: if realm.signup_notifications_stream is None or ( realm.signup_notifications_stream.id != signup_notifications_stream_id): new_signup_notifications_stream = None if signup_notifications_stream_id >= 0: (new_signup_notifications_stream, recipient, sub) = access_stream_by_id(user_profile, signup_notifications_stream_id) do_set_realm_signup_notifications_stream( realm, new_signup_notifications_stream, signup_notifications_stream_id) data[ 'signup_notifications_stream_id'] = signup_notifications_stream_id return json_success(data)
def update_realm( request: HttpRequest, user_profile: UserProfile, name: Optional[str] = REQ(str_validator=check_capped_string( Realm.MAX_REALM_NAME_LENGTH), default=None), description: Optional[str] = REQ(str_validator=check_capped_string( Realm.MAX_REALM_DESCRIPTION_LENGTH), default=None), emails_restricted_to_domains: Optional[bool] = REQ( json_validator=check_bool, default=None), disallow_disposable_email_addresses: Optional[bool] = REQ( json_validator=check_bool, default=None), invite_required: Optional[bool] = REQ(json_validator=check_bool, default=None), invite_to_realm_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.INVITE_TO_REALM_POLICY_TYPES), default=None), name_changes_disabled: Optional[bool] = REQ(json_validator=check_bool, default=None), email_changes_disabled: Optional[bool] = REQ(json_validator=check_bool, default=None), avatar_changes_disabled: Optional[bool] = REQ(json_validator=check_bool, default=None), inline_image_preview: Optional[bool] = REQ(json_validator=check_bool, default=None), inline_url_embed_preview: Optional[bool] = REQ(json_validator=check_bool, default=None), add_custom_emoji_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.COMMON_POLICY_TYPES), default=None), delete_own_message_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.COMMON_MESSAGE_POLICY_TYPES), default=None), message_content_delete_limit_seconds_raw: Optional[Union[int, str]] = REQ( "message_content_delete_limit_seconds", json_validator=check_string_or_int, default=None), allow_message_editing: Optional[bool] = REQ(json_validator=check_bool, default=None), edit_topic_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.COMMON_MESSAGE_POLICY_TYPES), default=None), mandatory_topics: Optional[bool] = REQ(json_validator=check_bool, default=None), message_content_edit_limit_seconds: Optional[int] = REQ( converter=to_non_negative_int, default=None), allow_edit_history: Optional[bool] = REQ(json_validator=check_bool, default=None), default_language: Optional[str] = REQ(default=None), waiting_period_threshold: Optional[int] = REQ( converter=to_non_negative_int, default=None), authentication_methods: Optional[Dict[str, Any]] = REQ( json_validator=check_dict([]), default=None), notifications_stream_id: Optional[int] = REQ(json_validator=check_int, default=None), signup_notifications_stream_id: Optional[int] = REQ( json_validator=check_int, default=None), message_retention_days_raw: Optional[Union[int, str]] = REQ( "message_retention_days", json_validator=check_string_or_int, default=None), send_welcome_emails: Optional[bool] = REQ(json_validator=check_bool, default=None), digest_emails_enabled: Optional[bool] = REQ(json_validator=check_bool, default=None), message_content_allowed_in_email_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), bot_creation_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.BOT_CREATION_POLICY_TYPES), default=None), create_public_stream_policy: Optional[int] = REQ( json_validator=check_int_in(Realm.COMMON_POLICY_TYPES), default=None), create_private_stream_policy: Optional[int] = REQ( json_validator=check_int_in(Realm.COMMON_POLICY_TYPES), default=None), create_web_public_stream_policy: Optional[int] = REQ( json_validator=check_int_in( Realm.CREATE_WEB_PUBLIC_STREAM_POLICY_TYPES), default=None), invite_to_stream_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.COMMON_POLICY_TYPES), default=None), move_messages_between_streams_policy: Optional[int] = REQ( json_validator=check_int_in(Realm.COMMON_POLICY_TYPES), default=None), user_group_edit_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.COMMON_POLICY_TYPES), default=None), private_message_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.PRIVATE_MESSAGE_POLICY_TYPES), default=None), wildcard_mention_policy: Optional[int] = REQ(json_validator=check_int_in( Realm.WILDCARD_MENTION_POLICY_TYPES), default=None), email_address_visibility: Optional[int] = REQ(json_validator=check_int_in( Realm.EMAIL_ADDRESS_VISIBILITY_TYPES), default=None), video_chat_provider: Optional[int] = REQ(json_validator=check_int, default=None), giphy_rating: Optional[int] = REQ(json_validator=check_int, default=None), default_code_block_language: Optional[str] = REQ(default=None), digest_weekday: Optional[int] = REQ(json_validator=check_int_in( Realm.DIGEST_WEEKDAY_VALUES), default=None), string_id: Optional[str] = REQ( str_validator=check_capped_string(Realm.MAX_REALM_SUBDOMAIN_LENGTH), default=None, ), enable_spectator_access: Optional[bool] = REQ(json_validator=check_bool, default=None), ) -> HttpResponse: realm = user_profile.realm # Additional validation/error checking beyond types go here, so # the entire request can succeed or fail atomically. if default_language is not None and default_language not in get_available_language_codes( ): raise JsonableError( _("Invalid language '{}'").format(default_language)) if authentication_methods is not None: if not user_profile.is_realm_owner: raise OrganizationOwnerRequired() if True not in list(authentication_methods.values()): raise JsonableError( _("At least one authentication method must be enabled.")) if video_chat_provider is not None and video_chat_provider not in { p["id"] for p in Realm.VIDEO_CHAT_PROVIDERS.values() }: raise JsonableError( _("Invalid video_chat_provider {}").format(video_chat_provider)) if giphy_rating is not None and giphy_rating not in { p["id"] for p in Realm.GIPHY_RATING_OPTIONS.values() }: raise JsonableError(_("Invalid giphy_rating {}").format(giphy_rating)) message_retention_days: Optional[int] = None if message_retention_days_raw is not None: if not user_profile.is_realm_owner: raise OrganizationOwnerRequired() realm.ensure_not_on_limited_plan() message_retention_days = parse_message_retention_days( message_retention_days_raw, Realm.MESSAGE_RETENTION_SPECIAL_VALUES_MAP) if invite_to_realm_policy is not None and not user_profile.is_realm_owner: raise OrganizationOwnerRequired() data: Dict[str, Any] = {} message_content_delete_limit_seconds: Optional[int] = None if message_content_delete_limit_seconds_raw is not None: message_content_delete_limit_seconds = parse_message_content_delete_limit( message_content_delete_limit_seconds_raw, Realm.MESSAGE_CONTENT_DELETE_LIMIT_SPECIAL_VALUES_MAP, ) do_set_realm_property( realm, "message_content_delete_limit_seconds", message_content_delete_limit_seconds, acting_user=user_profile, ) data[ "message_content_delete_limit_seconds"] = message_content_delete_limit_seconds # The user of `locals()` here is a bit of a code smell, but it's # restricted to the elements present in realm.property_types. # # TODO: It should be possible to deduplicate this function up # further by some more advanced usage of the # `REQ/has_request_variables` extraction. req_vars = { k: v for k, v in list(locals().items()) if k in realm.property_types } for k, v in list(req_vars.items()): if v is not None and getattr(realm, k) != v: do_set_realm_property(realm, k, v, acting_user=user_profile) if isinstance(v, str): data[k] = "updated" else: data[k] = v # The following realm properties do not fit the pattern above # authentication_methods is not supported by the do_set_realm_property # framework because of its bitfield. if authentication_methods is not None and ( realm.authentication_methods_dict() != authentication_methods): do_set_realm_authentication_methods(realm, authentication_methods, acting_user=user_profile) data["authentication_methods"] = authentication_methods # The message_editing settings are coupled to each other, and thus don't fit # into the do_set_realm_property framework. if ((allow_message_editing is not None and realm.allow_message_editing != allow_message_editing) or (message_content_edit_limit_seconds is not None and realm.message_content_edit_limit_seconds != message_content_edit_limit_seconds) or (edit_topic_policy is not None and realm.edit_topic_policy != edit_topic_policy)): if allow_message_editing is None: allow_message_editing = realm.allow_message_editing if message_content_edit_limit_seconds is None: message_content_edit_limit_seconds = realm.message_content_edit_limit_seconds if edit_topic_policy is None: edit_topic_policy = realm.edit_topic_policy do_set_realm_message_editing( realm, allow_message_editing, message_content_edit_limit_seconds, edit_topic_policy, acting_user=user_profile, ) data["allow_message_editing"] = allow_message_editing data[ "message_content_edit_limit_seconds"] = message_content_edit_limit_seconds data["edit_topic_policy"] = edit_topic_policy # Realm.notifications_stream and Realm.signup_notifications_stream are not boolean, # str or integer field, and thus doesn't fit into the do_set_realm_property framework. if notifications_stream_id is not None: if realm.notifications_stream is None or (realm.notifications_stream.id != notifications_stream_id): new_notifications_stream = None if notifications_stream_id >= 0: (new_notifications_stream, sub) = access_stream_by_id(user_profile, notifications_stream_id) do_set_realm_notifications_stream(realm, new_notifications_stream, notifications_stream_id, acting_user=user_profile) data["notifications_stream_id"] = notifications_stream_id if signup_notifications_stream_id is not None: if realm.signup_notifications_stream is None or ( realm.signup_notifications_stream.id != signup_notifications_stream_id): new_signup_notifications_stream = None if signup_notifications_stream_id >= 0: (new_signup_notifications_stream, sub) = access_stream_by_id(user_profile, signup_notifications_stream_id) do_set_realm_signup_notifications_stream( realm, new_signup_notifications_stream, signup_notifications_stream_id, acting_user=user_profile, ) data[ "signup_notifications_stream_id"] = signup_notifications_stream_id if default_code_block_language is not None: # Migrate '', used in the API to encode the default/None behavior of this feature. if default_code_block_language == "": data["default_code_block_language"] = None else: data["default_code_block_language"] = default_code_block_language if string_id is not None: if not user_profile.is_realm_owner: raise OrganizationOwnerRequired() if realm.demo_organization_scheduled_deletion_date is None: raise JsonableError(_("Must be a demo organization.")) try: check_subdomain(string_id) except ValidationError as err: raise JsonableError(str(err.message)) do_change_realm_subdomain(realm, string_id, acting_user=user_profile) data["realm_uri"] = realm.uri return json_success(data)
def add_subscriptions_backend( request: HttpRequest, user_profile: UserProfile, streams_raw: Sequence[Mapping[str, str]] = REQ( "subscriptions", json_validator=add_subscriptions_schema), invite_only: bool = REQ(json_validator=check_bool, default=False), stream_post_policy: int = REQ( json_validator=check_int_in(Stream.STREAM_POST_POLICY_TYPES), default=Stream.STREAM_POST_POLICY_EVERYONE, ), history_public_to_subscribers: Optional[bool] = REQ( json_validator=check_bool, default=None), message_retention_days: Union[str, int] = REQ( json_validator=check_string_or_int, default=RETENTION_DEFAULT), announce: bool = REQ(json_validator=check_bool, default=False), principals: Union[Sequence[str], Sequence[int]] = REQ( json_validator=check_principals, default=EMPTY_PRINCIPALS, ), authorization_errors_fatal: bool = REQ(json_validator=check_bool, default=True), ) -> HttpResponse: realm = user_profile.realm stream_dicts = [] color_map = {} for stream_dict in streams_raw: # 'color' field is optional # check for its presence in the streams_raw first if "color" in stream_dict: color_map[stream_dict["name"]] = stream_dict["color"] stream_dict_copy: StreamDict = {} stream_dict_copy["name"] = stream_dict["name"].strip() # We don't allow newline characters in stream descriptions. if "description" in stream_dict: stream_dict_copy["description"] = stream_dict[ "description"].replace("\n", " ") stream_dict_copy["invite_only"] = invite_only stream_dict_copy["stream_post_policy"] = stream_post_policy stream_dict_copy[ "history_public_to_subscribers"] = history_public_to_subscribers stream_dict_copy[ "message_retention_days"] = parse_message_retention_days( message_retention_days, Stream.MESSAGE_RETENTION_SPECIAL_VALUES_MAP) stream_dicts.append(stream_dict_copy) # Validation of the streams arguments, including enforcement of # can_create_streams policy and check_stream_name policy is inside # list_to_streams. existing_streams, created_streams = list_to_streams(stream_dicts, user_profile, autocreate=True) authorized_streams, unauthorized_streams = filter_stream_authorization( user_profile, existing_streams) if len(unauthorized_streams) > 0 and authorization_errors_fatal: return json_error( _("Unable to access stream ({stream_name}).").format( stream_name=unauthorized_streams[0].name, )) # Newly created streams are also authorized for the creator streams = authorized_streams + created_streams if len(principals) > 0: if realm.is_zephyr_mirror_realm and not all(stream.invite_only for stream in streams): return json_error( _("You can only invite other Zephyr mirroring users to private streams." )) if not user_profile.can_subscribe_other_users(): # Guest users case will not be handled here as it will # be handled by the decorator above. raise JsonableError(_("Insufficient permission")) subscribers = { principal_to_user_profile(user_profile, principal) for principal in principals } else: subscribers = {user_profile} (subscribed, already_subscribed) = bulk_add_subscriptions(realm, streams, subscribers, acting_user=user_profile, color_map=color_map) # We can assume unique emails here for now, but we should eventually # convert this function to be more id-centric. email_to_user_profile: Dict[str, UserProfile] = {} result: Dict[str, Any] = dict(subscribed=defaultdict(list), already_subscribed=defaultdict(list)) for sub_info in subscribed: subscriber = sub_info.user stream = sub_info.stream result["subscribed"][subscriber.email].append(stream.name) email_to_user_profile[subscriber.email] = subscriber for sub_info in already_subscribed: subscriber = sub_info.user stream = sub_info.stream result["already_subscribed"][subscriber.email].append(stream.name) result["subscribed"] = dict(result["subscribed"]) result["already_subscribed"] = dict(result["already_subscribed"]) send_messages_for_new_subscribers( user_profile=user_profile, subscribers=subscribers, new_subscriptions=result["subscribed"], email_to_user_profile=email_to_user_profile, created_streams=created_streams, announce=announce, ) result["subscribed"] = dict(result["subscribed"]) result["already_subscribed"] = dict(result["already_subscribed"]) if not authorization_errors_fatal: result["unauthorized"] = [s.name for s in unauthorized_streams] return json_success(result)
def json_change_settings( request: HttpRequest, user_profile: UserProfile, full_name: str = REQ(default=""), email: str = REQ(default=""), old_password: str = REQ(default=""), new_password: str = REQ(default=""), twenty_four_hour_time: Optional[bool] = REQ(json_validator=check_bool, default=None), dense_mode: Optional[bool] = REQ(json_validator=check_bool, default=None), starred_message_counts: Optional[bool] = REQ(json_validator=check_bool, default=None), fluid_layout_width: Optional[bool] = REQ(json_validator=check_bool, default=None), high_contrast_mode: Optional[bool] = REQ(json_validator=check_bool, default=None), color_scheme: Optional[int] = REQ(json_validator=check_int_in( UserProfile.COLOR_SCHEME_CHOICES), default=None), translate_emoticons: Optional[bool] = REQ(json_validator=check_bool, default=None), default_language: Optional[str] = REQ(default=None), default_view: Optional[str] = REQ( str_validator=check_string_in(default_view_options), default=None), left_side_userlist: Optional[bool] = REQ(json_validator=check_bool, default=None), emojiset: Optional[str] = REQ( str_validator=check_string_in(emojiset_choices), default=None), demote_inactive_streams: Optional[int] = REQ(json_validator=check_int_in( UserProfile.DEMOTE_STREAMS_CHOICES), default=None), timezone: Optional[str] = REQ(str_validator=check_string_in( pytz.all_timezones_set), default=None), email_notifications_batching_period_seconds: Optional[int] = REQ( json_validator=check_int, default=None), enable_stream_desktop_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_stream_email_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_stream_push_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_stream_audible_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), wildcard_mentions_notify: Optional[bool] = REQ(json_validator=check_bool, default=None), notification_sound: Optional[str] = REQ(default=None), enable_desktop_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_sounds: Optional[bool] = REQ(json_validator=check_bool, default=None), enable_offline_email_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_offline_push_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_online_push_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), enable_digest_emails: Optional[bool] = REQ(json_validator=check_bool, default=None), enable_login_emails: Optional[bool] = REQ(json_validator=check_bool, default=None), enable_marketing_emails: Optional[bool] = REQ(json_validator=check_bool, default=None), message_content_in_email_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), pm_content_in_desktop_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), desktop_icon_count_display: Optional[int] = REQ(json_validator=check_int, default=None), realm_name_in_notifications: Optional[bool] = REQ( json_validator=check_bool, default=None), presence_enabled: Optional[bool] = REQ(json_validator=check_bool, default=None), enter_sends: Optional[bool] = REQ(json_validator=check_bool, default=None), ) -> HttpResponse: # We can't use REQ for this widget because # get_available_language_codes requires provisioning to be # complete. if default_language is not None and default_language not in get_available_language_codes( ): raise JsonableError(_("Invalid default_language")) if (notification_sound is not None and notification_sound not in get_available_notification_sounds() and notification_sound != "none"): raise JsonableError( _("Invalid notification sound '{}'").format(notification_sound)) if email_notifications_batching_period_seconds is not None and ( email_notifications_batching_period_seconds <= 0 or email_notifications_batching_period_seconds > 7 * 24 * 60 * 60): # We set a limit of one week for the batching period raise JsonableError( _("Invalid email batching period: {} seconds").format( email_notifications_batching_period_seconds)) if new_password != "": return_data: Dict[str, Any] = {} if email_belongs_to_ldap(user_profile.realm, user_profile.delivery_email): raise JsonableError(_("Your Zulip password is managed in LDAP")) try: if not authenticate( request, username=user_profile.delivery_email, password=old_password, realm=user_profile.realm, return_data=return_data, ): raise JsonableError(_("Wrong password!")) except RateLimited as e: assert e.secs_to_freedom is not None secs_to_freedom = int(e.secs_to_freedom) raise JsonableError( _("You're making too many attempts! Try again in {} seconds."). format(secs_to_freedom), ) if not check_password_strength(new_password): raise JsonableError(_("New password is too weak!")) do_change_password(user_profile, new_password) # In Django 1.10, password changes invalidates sessions, see # https://docs.djangoproject.com/en/1.10/topics/auth/default/#session-invalidation-on-password-change # for details. To avoid this logging the user out of their own # session (which would provide a confusing UX at best), we # update the session hash here. update_session_auth_hash(request, user_profile) # We also save the session to the DB immediately to mitigate # race conditions. In theory, there is still a race condition # and to completely avoid it we will have to use some kind of # mutex lock in `django.contrib.auth.get_user` where session # is verified. To make that lock work we will have to control # the AuthenticationMiddleware which is currently controlled # by Django, request.session.save() result: Dict[str, Any] = {} new_email = email.strip() if user_profile.delivery_email != new_email and new_email != "": if user_profile.realm.email_changes_disabled and not user_profile.is_realm_admin: raise JsonableError( _("Email address changes are disabled in this organization.")) error = validate_email_is_valid( new_email, get_realm_email_validator(user_profile.realm), ) if error: raise JsonableError(error) try: validate_email_not_already_in_realm( user_profile.realm, new_email, verbose=False, ) except ValidationError as e: raise JsonableError(e.message) do_start_email_change_process(user_profile, new_email) if user_profile.full_name != full_name and full_name.strip() != "": if name_changes_disabled( user_profile.realm) and not user_profile.is_realm_admin: # Failingly silently is fine -- they can't do it through the UI, so # they'd have to be trying to break the rules. pass else: # Note that check_change_full_name strips the passed name automatically check_change_full_name(user_profile, full_name, user_profile) # Loop over user_profile.property_types request_settings = { k: v for k, v in list(locals().items()) if k in user_profile.property_types } for k, v in list(request_settings.items()): if v is not None and getattr(user_profile, k) != v: do_set_user_display_setting(user_profile, k, v) req_vars = { k: v for k, v in list(locals().items()) if k in user_profile.notification_setting_types } for k, v in list(req_vars.items()): if v is not None and getattr(user_profile, k) != v: do_change_notification_settings(user_profile, k, v, acting_user=user_profile) if timezone is not None and user_profile.timezone != timezone: do_set_user_display_setting(user_profile, "timezone", timezone) # TODO: Do this more generally. from zerver.lib.request import get_request_notes request_notes = get_request_notes(request) for req_var in request.POST: if req_var not in request_notes.processed_parameters: request_notes.ignored_parameters.add(req_var) if len(request_notes.ignored_parameters) > 0: result["ignored_parameters_unsupported"] = list( request_notes.ignored_parameters) return json_success(result)