From 630b37f2d80265ee0bd525fd1c1d3f5476c06dc9 Mon Sep 17 00:00:00 2001 From: Sahil Batra Date: Mon, 21 Feb 2022 14:03:08 +0530 Subject: [PATCH] users: Refactor get_user_by_email. This commit refactors get_user_by_email function to use access_user_by_email which is similar to already existing access_user_by_id and thus using get_user_data function added recently. We also remove the unnecessary check for email as email will always be passed to this endpoint. Preparatory commit for #10970. --- zerver/lib/users.py | 18 ++++++++++++++++++ zerver/views/users.py | 16 ++++++---------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/zerver/lib/users.py b/zerver/lib/users.py index ec778a4884..aac6791787 100644 --- a/zerver/lib/users.py +++ b/zerver/lib/users.py @@ -28,6 +28,7 @@ from zerver.models import ( Service, UserProfile, get_realm_user_dicts, + get_user, get_user_profile_by_id_in_realm, ) @@ -281,6 +282,23 @@ def access_user_by_id( return access_user_common(target, user_profile, allow_deactivated, allow_bots, for_admin) +def access_user_by_email( + user_profile: UserProfile, + email: str, + *, + allow_deactivated: bool = False, + allow_bots: bool = False, + for_admin: bool, +) -> UserProfile: + + try: + target = get_user(email, user_profile.realm) + except UserProfile.DoesNotExist: + raise JsonableError(_("No such user")) + + return access_user_common(target, user_profile, allow_deactivated, allow_bots, for_admin) + + class Accounts(TypedDict): realm_name: str realm_id: int diff --git a/zerver/views/users.py b/zerver/views/users.py index 0e2bb169e5..9e33dd4558 100644 --- a/zerver/views/users.py +++ b/zerver/views/users.py @@ -46,6 +46,7 @@ from zerver.lib.upload import upload_avatar_image from zerver.lib.url_encoding import append_url_query_string from zerver.lib.users import ( access_bot_by_id, + access_user_by_email, access_user_by_id, add_service, check_bot_creation_policy, @@ -82,7 +83,6 @@ from zerver.models import ( Service, Stream, UserProfile, - get_user, get_user_by_delivery_email, get_user_by_id_in_realm_including_cross_realm, get_user_including_cross_realm, @@ -687,13 +687,9 @@ def get_user_by_email( include_custom_profile_fields: bool = REQ(json_validator=check_bool, default=False), client_gravatar: bool = REQ(json_validator=check_bool, default=True), ) -> HttpResponse: - realm = user_profile.realm + target_user = access_user_by_email( + user_profile, email, allow_deactivated=True, allow_bots=True, for_admin=False + ) - target_user = None - if email is not None: - try: - target_user = get_user(email, realm) - except UserProfile.DoesNotExist: - raise JsonableError(_("No such user")) - - return get_members_backend(request, user_profile, user_id=target_user.id) + data = get_user_data(user_profile, include_custom_profile_fields, client_gravatar, target_user) + return json_success(request, data)