diff --git a/kitsune/customercare/zendesk.py b/kitsune/customercare/zendesk.py index 0d0c4fbc0a6..925486036db 100644 --- a/kitsune/customercare/zendesk.py +++ b/kitsune/customercare/zendesk.py @@ -18,6 +18,14 @@ def __init__(self, **kwargs): self.client = Zenpy(**creds) def _user_to_zendesk_user(self, user, email): + """Given a Django user, return a Zendesk user.""" + # If the user already exists in Zendesk return + # the Zendesk user object + # instead of creating a new one + if zuser := self.get_user_by_email(email): + return zuser + # If the user is not authenticated, we can't save anything to + # AnonymousUser Profile as it has none if not user.is_authenticated: name = "Anonymous User" locale = "en-US" @@ -42,6 +50,21 @@ def _user_to_zendesk_user(self, user, email): external_id=external_id, ) + def get_user_by_email(self, email): + """Given an email, return a user from Zendesk.""" + # This returns a generator, but we only want/expect one user + # If it returns more than one, we should fail + # Otherwise return the Zendesk user object + search_results = self.client.search(type="user", query=f"email:{email}") + + user_found = None + for user in search_results: + if user_found is not None: + raise ValueError(f"Found more than one user with email {email}") + user_found = user + + return user_found + def create_user(self, user, email=""): """Given a Django user, create a user in Zendesk.""" zendesk_user = self._user_to_zendesk_user(user, email=email)