diff --git a/zerver/models.py b/zerver/models.py index dacac37fdb..060ad50170 100644 --- a/zerver/models.py +++ b/zerver/models.py @@ -1551,6 +1551,10 @@ def active_user_ids(realm_id: int) -> List[int]: ).values_list('id', flat=True) return list(query) +def get_membership_realms(email: str) -> List[Realm]: + profiles = UserProfile.objects.select_related('realm').filter(email__iexact=email.strip()) + return [profile.realm for profile in profiles] + @cache_with_key(bot_dicts_in_realm_cache_key, timeout=3600*24*7) def get_bot_dicts_in_realm(realm: Realm) -> List[Dict[str, Any]]: return UserProfile.objects.filter(realm=realm, is_bot=True).values(*bot_dict_fields) diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py index 013502d9ca..3a66b247f0 100644 --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -20,7 +20,8 @@ from zerver.lib.test_runner import slow from zerver.models import UserProfile, Recipient, \ Realm, RealmDomain, UserActivity, \ get_user, get_realm, get_client, get_stream, get_stream_recipient, \ - Message, get_context_for_message, ScheduledEmail + Message, get_context_for_message, ScheduledEmail, \ + get_membership_realms from zerver.lib.avatar import avatar_url from zerver.lib.email_mirror import create_missed_message_address @@ -329,6 +330,27 @@ class UserProfileTest(ZulipTestCase): self.assertEqual(result[cordelia].email, cordelia) self.assertEqual(result[webhook_bot].email, webhook_bot) + def test_get_membership_realms(self) -> None: + zulip_realm = get_realm("zulip") + lear_realm = get_realm("lear") + + email = "cordelia@zulip.com" + realms = get_membership_realms(email) + self.assert_length(realms, 2) + self.assertIn(zulip_realm, realms) + self.assertIn(lear_realm, realms) + + email = "CORDelia@zulip.com" + realms = get_membership_realms(email) + self.assert_length(realms, 2) + self.assertIn(zulip_realm, realms) + self.assertIn(lear_realm, realms) + + email = "IAGO@ZULIP.COM" + realms = get_membership_realms(email) + self.assert_length(realms, 1) + self.assertIn(zulip_realm, realms) + class ActivateTest(ZulipTestCase): def test_basics(self) -> None: user = self.example_user('hamlet')