Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

webhooks: Add function to guess Zulip username.

The Dancea82d7b8476e4
diff --git a/docs/webhooks/incoming-webhooks-overview.md b/docs/webhooks/incoming-webhooks-overview.md
index dfb80202045..214ab2c21ca 100644
--- a/docs/webhooks/incoming-webhooks-overview.md
+++ b/docs/webhooks/incoming-webhooks-overview.md
@@ -117,6 +117,12 @@ configured! 🎉"
together; this makes for much better consumption by Zulip users. E.g.,
for a bug tracker integration, put the bug number in the topic for all
messages; for an integration like Nagios, put the service in the topic.
+- If your integration references usernames from external accounts (such as
+ GitHub usernames), consider using the `guess_zulip_user_from_external_account`
+ helper function from `zerver/lib/webhooks/common.py`. This function automatically
+ matches external accounts to Zulip users who have linked those accounts in their
+ profile's custom fields. This enables converting external usernames to silent mentions,
+ notifying the relevant Zulip users.
- Integrations that don't match a team's workflow can often be uselessly
spammy. Give careful thought to providing options for triggering Zulip
messages only for certain event types, certain projects, or sending
diff --git a/zerver/lib/webhooks/common.py b/zerver/lib/webhooks/common.py
index d3922ea48f1..49a9faa54b2 100644
--- a/zerver/lib/webhooks/common.py
+++ b/zerver/lib/webhooks/common.py
@@ -31,7 +31,8 @@ from zerver.lib.request import RequestNotes
from zerver.lib.send_email import FromAddress
from zerver.lib.typed_endpoint import ApiParamConfig, typed_endpoint
from zerver.lib.validator import check_bool, check_string
-from zerver.models import UserProfile
+from zerver.models import Realm, UserProfile
+from zerver.models.custom_profile_fields import CustomProfileField, CustomProfileFieldValue
MISSING_EVENT_HEADER_MESSAGE = """\
Hi there! Your bot {bot_name} just sent an HTTP request to {request_path} that
@@ -342,3 +343,37 @@ def validate_webhook_signature(
if signed_payload != signature:
raise JsonableError(_("Webhook signature verification failed."))
+
+
+def guess_zulip_user_from_external_account(
+ realm: Realm,
+ external_username: str,
+ external_account_field_name: str,
+ external_username_case_insensitive: bool,
+) -> UserProfile | None:
+ try:
+ external_account_field = CustomProfileField.objects.get(
+ realm=realm,
+ field_type=CustomProfileField.EXTERNAL_ACCOUNT,
+ name=external_account_field_name,
+ )
+ except CustomProfileField.DoesNotExist:
+ return None
+
+ lookup = "value__iexact" if external_username_case_insensitive else "value__exact"
+
+ try:
+ matching_user = (
+ CustomProfileFieldValue.objects.filter(
+ field=external_account_field,
+ **{lookup: external_username},
+ user_profile__realm=realm,
+ user_profile__is_active=True,
+ )
+ .select_related("user_profile")
+ .only("user_profile__id", "user_profile__full_name")
+ .get()
+ )
+ return matching_user.user_profile
+ except (CustomProfileFieldValue.DoesNotExist, CustomProfileFieldValue.MultipleObjectsReturned):
+ return None
diff --git a/zerver/tests/test_webhooks_common.py b/zerver/tests/test_webhooks_common.py
index 61f70a481c7..0cb1b206e67 100644
--- a/zerver/tests/test_webhooks_common.py
+++ b/zerver/tests/test_webhooks_common.py
@@ -9,6 +9,7 @@ from django.test import override_settings
from django.utils.encoding import force_bytes
from typing_extensions import override
+from zerver.actions.custom_profile_fields import try_add_realm_custom_profile_field
from zerver.actions.streams import do_rename_stream
from zerver.decorator import webhook_view
from zerver.lib.exceptions import InvalidJSONError, JsonableError
@@ -23,10 +24,11 @@ from zerver.lib.webhooks.common import (
call_fixture_to_headers,
check_send_webhook_message,
get_event_header,
+ guess_zulip_user_from_external_account,
standardize_headers,
validate_webhook_signature,
)
-from zerver.models import Client, Message, UserProfile
+from zerver.models import Client, CustomProfileField, Message, UserProfile
from zerver.models.realms import get_realm
from zerver.models.users import get_user
@@ -200,6 +202,81 @@ class WebhooksCommonTestCase(ZulipTestCase):
self.assertEqual(msg.topic_name(), "Test topic")
+class TestGuessZulipUserFromExternalAccount(ZulipTestCase):
+ @override
+ def setUp(self) -> None:
+ super().setUp()
+ self.realm = get_realm("zulip")
+ self.hamlet = self.example_user("hamlet")
+ self.othello = self.example_user("othello")
+ self.github_name = "GitHub username"
+
+ def get_github_field(self) -> CustomProfileField:
+ return CustomProfileField.objects.get(
+ realm=self.realm,
+ name=self.github_name,
+ )
+
+ def set_user_external_account(
+ self, user: UserProfile, field: CustomProfileField, value: str
+ ) -> None:
+ self.set_user_custom_profile_data(user, [{"id": field.id, "value": value}])
+
+ def test_single_exact_match(self) -> None:
+ github_field = self.get_github_field()
+ self.set_user_external_account(self.hamlet, github_field, "octocat")
+
+ result = guess_zulip_user_from_external_account(
+ self.realm, "octocat", self.github_name, external_username_case_insensitive=True
+ )
+ self.assertEqual(result, self.hamlet)
+
+ # Test case-sensitive account names
+ result = guess_zulip_user_from_external_account(
+ self.realm, "ocTOcat", self.github_name, external_username_case_insensitive=False
+ )
+ self.assertIsNone(result)
+
+ # Test multiple matching field values found
+ self.set_user_external_account(self.othello, github_field, "octocat")
+
+ result = guess_zulip_user_from_external_account(
+ self.realm, "octocat", self.github_name, external_username_case_insensitive=True
+ )
+ self.assertIsNone(result)
+
+ def test_no_matches_found(self) -> None:
+ # Test no matching field
+ result = guess_zulip_user_from_external_account(
+ self.realm, "someuser", "gitlab", external_username_case_insensitive=True
+ )
+ self.assertIsNone(result)
+
+ # test no matching field value
+ result = guess_zulip_user_from_external_account(
+ self.realm, "nonexistentuser", self.github_name, external_username_case_insensitive=True
+ )
+ self.assertIsNone(result)
+
+ def test_matches_from_custom_external_account_field(self) -> None:
+ external_account_field_name = "Otherhub username"
+ external_account_field = try_add_realm_custom_profile_field(
+ self.realm,
+ external_account_field_name,
+ CustomProfileField.EXTERNAL_ACCOUNT,
+ field_data={"subtype": "custom", "url_pattern": "https://other.com/%(username)s"},
+ )
+ self.set_user_external_account(self.hamlet, external_account_field, "octocat")
+
+ result = guess_zulip_user_from_external_account(
+ self.realm,
+ "octocat",
+ external_account_field_name,
+ external_username_case_insensitive=True,
+ )
+ self.assertEqual(result, self.hamlet)
+
+
class WebhookURLConfigurationTestCase(WebhookTestCase):
WEBHOOK_DIR_NAME = "helloworld"