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.

social_auth: Add Discord as an authentication option.

PieterCK1aa5338c2804
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index 2014a87bd13..817636a7c90 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -20,6 +20,12 @@ format used by the Zulip server that they are interacting with.
## Changes in Zulip 12.0
+**Feature level 488**
+
+* [`GET /server_settings`](/api/get-server-settings): Added `discord` boolean
+ as a field in `authentication_methods` which indicates whether the realm has
+ Discord as a valid authentication method.
+
**Feature level 487**
* [`GET /users/{user_id_or_email}/presence`](/api/get-user-presence): The
diff --git a/docs/development/authentication.md b/docs/development/authentication.md
index 5f97aa294cb..705ecba0898 100644
--- a/docs/development/authentication.md
+++ b/docs/development/authentication.md
@@ -105,6 +105,17 @@ details worth understanding:
- Put the private key file you got from apple at the path
`zproject/dev_apple.key`.
+### Discord
+
+- Register an OAuth application with Discord at
+ <https://discord.com/developers/applications>.
+ Specify `http://auth.zulipdev.com:9991/complete/discord/` as the callback URL.
+
+- You should get a page containing the Client ID and Secret for
+ your new application. In `dev-secrets.conf`, enter the Client
+ ID as `social_auth_discord_key` and the Secret as
+ `social_auth_discord_secret`.
+
### SAML
- Sign up for a [developer Okta account](https://developer.okta.com/).
diff --git a/docs/production/authentication-methods.md b/docs/production/authentication-methods.md
index 10a952c2724..37e3523e5f0 100644
--- a/docs/production/authentication-methods.md
+++ b/docs/production/authentication-methods.md
@@ -98,6 +98,7 @@ authenticate users with:
- Google accounts, with `GoogleAuthBackend`
- GitHub accounts, with `GitHubAuthBackend`
- GitLab accounts, with `GitLabAuthBackend`
+- Discord accounts, with `DiscordAuthBackend`
Each of these requires one to a handful of lines of configuration in
`settings.py`, as well as a secret in `zulip-secrets.conf`. Details
diff --git a/static/images/authentication_backends/discord-icon.png b/static/images/authentication_backends/discord-icon.png
new file mode 100644
index 00000000000..ef19031c1e2
Binary files /dev/null and b/static/images/authentication_backends/discord-icon.png differ
diff --git a/templates/zerver/config_error/discord.html b/templates/zerver/config_error/discord.html
new file mode 100644
index 00000000000..033cffc44f3
--- /dev/null
+++ b/templates/zerver/config_error/discord.html
@@ -0,0 +1,28 @@
+{% extends "zerver/config_error/social-container.html" %}
+
+{% block error_content %}
+ <p>
+ You are attempting to use the <strong>Discord auth backend</strong>, but it
+ is not properly configured. To configure, please check the following:
+ </p>
+ <ul>
+ <li>
+ You have added
+ <code>{{ root_domain_url }}/complete/discord/</code> as the callback URL
+ in the OAuth application in Discord Developer Portal. You can register
+ OAuth apps at <a href="https://discord.com/developers/applications">Discord
+ Developer Portal</a>.
+ </li>
+ <li>
+ You have set <code>{{ client_id_key_name }}</code> in
+ <code>{{ auth_settings_path }}</code> and
+ <code>social_auth_discord_secret</code> in
+ <code>{{ secrets_path }}</code> with the values from your OAuth
+ application.
+ </li>
+ <li>
+ Navigate back to the login page and attempt the Discord auth flow again.
+ </li>
+ </ul>
+ {{ super() }}
+{% endblock %}
diff --git a/version.py b/version.py
index 57d8018a8ac..a2228ff6f13 100644
--- a/version.py
+++ b/version.py
@@ -33,7 +33,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"
# https://zulip.readthedocs.io/en/latest/documentation/api.html#step-by-step-guide
# Also available at docs/documentation/api.md.
-API_FEATURE_LEVEL = 487
+API_FEATURE_LEVEL = 488
# Bump the minor PROVISION_VERSION to indicate that folks should provision
# only when going from an old version of the code to a newer version. Bump
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index b5fedbaa356..b65efd14e63 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -22220,6 +22220,12 @@ paths:
description: |
Whether the user can authenticate using OpenID Connect.
type: boolean
+ discord:
+ description: |
+ Whether the user can authenticate using their Discord account.
+
+ **Changes**: New in Zulip 12.0 (feature level 488).
+ type: boolean
external_authentication_methods:
type: array
description: |
diff --git a/zerver/tests/test_audit_log.py b/zerver/tests/test_audit_log.py
index 8ada0f0eacd..f16ec281bc1 100644
--- a/zerver/tests/test_audit_log.py
+++ b/zerver/tests/test_audit_log.py
@@ -554,6 +554,7 @@ class TestRealmAuditLog(ZulipTestCase):
"SAML": True,
"GitLab": False,
"OpenID Connect": False,
+ "Discord": False,
}
do_set_realm_authentication_methods(realm, auth_method_dict, acting_user=user)
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py
index df93b6e59cd..660fc024f04 100644
--- a/zerver/tests/test_auth_backends.py
+++ b/zerver/tests/test_auth_backends.py
@@ -126,6 +126,7 @@ from zproject.backends import (
AuthFuncT,
AzureADAuthBackend,
DevAuthBackend,
+ DiscordAuthBackend,
EmailAuthBackend,
ExternalAuthDataDict,
ExternalAuthMethod,
@@ -153,6 +154,7 @@ from zproject.backends import (
auth_enabled_helper,
check_password_strength,
dev_auth_enabled,
+ discord_auth_enabled,
email_belongs_to_ldap,
get_external_method_dicts,
github_auth_enabled,
@@ -5941,6 +5943,52 @@ class GoogleAuthBackendTest(SocialAuthBase):
self.assert_json_error(result, "Invalid subdomain")
+class DiscordAuthBackendTest(SocialAuthBase):
+ BACKEND_CLASS = DiscordAuthBackend
+ CLIENT_KEY_SETTING = "SOCIAL_AUTH_DISCORD_KEY"
+ CLIENT_SECRET_SETTING = "SOCIAL_AUTH_DISCORD_SECRET"
+ LOGIN_URL = "/accounts/login/social/discord"
+ SIGNUP_URL = "/accounts/register/social/discord"
+ AUTHORIZATION_URL = "https://discord.com/api/oauth2/authorize"
+ ACCESS_TOKEN_URL = "https://discord.com/api/oauth2/token"
+ USER_INFO_URL = "https://discord.com/api/users/@me"
+ AUTH_FINISH_URL = "/complete/discord/"
+
+ def test_discord_auth_enabled(self) -> None:
+ with self.settings(AUTHENTICATION_BACKENDS=("zproject.backends.DiscordAuthBackend",)):
+ self.assertTrue(discord_auth_enabled())
+
+ @override
+ def get_account_data_dict(self, email: str, name: str, verified: bool = True) -> dict[str, Any]:
+ return dict(
+ email=email,
+ global_name=name,
+ username=name.lower(),
+ verified=verified,
+ email_verified=True,
+ )
+
+ def test_social_auth_email_not_verified(self) -> None:
+ account_data_dict = self.get_account_data_dict(
+ email=self.email, name=self.name, verified=False
+ )
+ subdomain = "zulip"
+ realm = get_realm(subdomain)
+ with self.assertLogs(self.logger_string, level="WARNING") as m:
+ result = self.social_auth_test(account_data_dict, subdomain=subdomain)
+ self.assertEqual(result.status_code, 302)
+ self.assertEqual(result["Location"], realm.url + "/login/")
+ self.assertEqual(
+ m.output,
+ [
+ self.logger_output(
+ "Social auth ({}) failed because user has no verified emails".format("Discord"),
+ "warning",
+ )
+ ],
+ )
+
+
class JSONFetchAPIKeyTest(ZulipTestCase):
def test_success(self) -> None:
user = self.example_user("hamlet")
diff --git a/zerver/tests/test_zilencer_analytics.py b/zerver/tests/test_zilencer_analytics.py
index d710950bfe8..9e061831562 100644
--- a/zerver/tests/test_zilencer_analytics.py
+++ b/zerver/tests/test_zilencer_analytics.py
@@ -393,6 +393,7 @@ class AnalyticsBouncerTest(BouncerTestCase):
"SAML": True,
"GitLab": False,
"OpenID Connect": False,
+ "Discord": False,
}
do_set_realm_authentication_methods(zephyr_realm, new_auth_method_dict, acting_user=user)
diff --git a/zerver/views/auth.py b/zerver/views/auth.py
index f920b6f1ba6..acad15c3cd1 100644
--- a/zerver/views/auth.py
+++ b/zerver/views/auth.py
@@ -765,7 +765,7 @@ def _start_social_auth_flow(
return config_error(request, "apple")
# TODO: Add AzureAD also.
- if backend in ["github", "google", "gitlab"]:
+ if backend in ["github", "google", "gitlab", "discord"]:
key_setting = "SOCIAL_AUTH_" + backend.upper() + "_KEY"
secret_setting = "SOCIAL_AUTH_" + backend.upper() + "_SECRET"
if not (getattr(settings, key_setting) and getattr(settings, secret_setting)):
diff --git a/zproject/backends.py b/zproject/backends.py
index 51e6e0f737c..b55fcde9688 100644
--- a/zproject/backends.py
+++ b/zproject/backends.py
@@ -53,6 +53,7 @@ from requests import HTTPError
from social_core.backends.apple import AppleIdAuth
from social_core.backends.azuread import AzureADOAuth2
from social_core.backends.base import BaseAuth
+from social_core.backends.discord import DiscordOAuth2
from social_core.backends.github import GithubOAuth2, GithubOrganizationOAuth2, GithubTeamOAuth2
from social_core.backends.gitlab import GitLabOAuth2
from social_core.backends.google import GoogleOAuth2
@@ -242,6 +243,12 @@ def apple_auth_enabled(
return auth_enabled_helper(["Apple"], realm, realm_authentication_methods)
+def discord_auth_enabled(
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
+) -> bool:
+ return auth_enabled_helper(["Discord"], realm, realm_authentication_methods)
+
+
def saml_auth_enabled(
realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
@@ -2895,6 +2902,38 @@ class AzureADAuthBackend(SocialAuthMixin, AzureADOAuth2):
return staticfiles_storage.url("images/authentication_backends/azuread-icon.png")
+@external_auth_method
+class DiscordAuthBackend(SocialAuthMixin, DiscordOAuth2):
+ sort_order = 60
+ name = "discord"
+ auth_backend_name = "Discord"
+ # https://docs.discord.com/developers/resources/user
+ DEFAULT_SCOPE = ["identify", "email"]
+
+ @classmethod
+ @override
+ def display_icon(cls) -> str:
+ return staticfiles_storage.url("images/authentication_backends/discord-icon.png")
+
+ def get_verified_emails(self, *args: Any, **kwargs: Any) -> list[str]:
+ verified_emails: list[str] = []
+ details = kwargs["response"]
+ email_verified = details.get("verified")
+ if email_verified:
+ verified_emails.append(details["email"])
+ return verified_emails
+
+ @override
+ def get_user_details(self, response: dict[str, Any]) -> dict[str, Any]:
+ # Discord has a "global_name" field which is more apt as a display name
+ # than the default "username" field. However, the field is optional.
+ # https://support.discord.com/hc/en-us/articles/12620128861463-New-Usernames-Display-Names#h_01GXPQABMYGEHGPRJJXJMPHF5C
+ return {
+ "fullname": response.get("global_name") or response.get("username"),
+ "email": response.get("email") or "",
+ }
+
+
@external_auth_method
class GitLabAuthBackend(SocialAuthMixin, GitLabOAuth2):
sort_order = 75
diff --git a/zproject/computed_settings.py b/zproject/computed_settings.py
index 13eae142307..2dedcd2900e 100644
--- a/zproject/computed_settings.py
+++ b/zproject/computed_settings.py
@@ -1172,6 +1172,7 @@ SOCIAL_AUTH_GOOGLE_SECRET = get_secret("social_auth_google_secret")
GOOGLE_OAUTH2_CLIENT_SECRET = get_secret("google_oauth2_client_secret")
SOCIAL_AUTH_GOOGLE_KEY = SOCIAL_AUTH_GOOGLE_KEY or GOOGLE_OAUTH2_CLIENT_ID
SOCIAL_AUTH_GOOGLE_SECRET = SOCIAL_AUTH_GOOGLE_SECRET or GOOGLE_OAUTH2_CLIENT_SECRET
+SOCIAL_AUTH_DISCORD_SECRET = get_secret("social_auth_discord_secret")
if PRODUCTION:
SOCIAL_AUTH_SAML_SP_PUBLIC_CERT = get_from_file_if_exists("/etc/zulip/saml/zulip-cert.crt")
diff --git a/zproject/default_settings.py b/zproject/default_settings.py
index 3ea6521ec2f..cb0b1f917e3 100644
--- a/zproject/default_settings.py
+++ b/zproject/default_settings.py
@@ -86,6 +86,7 @@ SOCIAL_AUTH_GITLAB_KEY = get_secret("social_auth_gitlab_key", development_only=T
SOCIAL_AUTH_SUBDOMAIN: str | None = None
SOCIAL_AUTH_AZUREAD_OAUTH2_KEY = get_secret("social_auth_azuread_oauth2_key", development_only=True)
SOCIAL_AUTH_GOOGLE_KEY = get_secret("social_auth_google_key", development_only=True)
+SOCIAL_AUTH_DISCORD_KEY = get_secret("social_auth_discord_key", development_only=True)
# SAML:
SOCIAL_AUTH_SAML_SP_ENTITY_ID: str | None = None
SOCIAL_AUTH_SAML_SP_PUBLIC_CERT = ""
diff --git a/zproject/dev_settings.py b/zproject/dev_settings.py
index 21c79f80ea0..f0c252a9243 100644
--- a/zproject/dev_settings.py
+++ b/zproject/dev_settings.py
@@ -61,6 +61,7 @@ AUTHENTICATION_BACKENDS: tuple[str, ...] = (
"zproject.backends.GitLabAuthBackend",
"zproject.backends.AppleAuthBackend",
"zproject.backends.GenericOpenIdConnectBackend",
+ "zproject.backends.DiscordAuthBackend",
)
EXTERNAL_URI_SCHEME = "http://"
diff --git a/zproject/prod_settings_template.py b/zproject/prod_settings_template.py
index eda89e93577..0d3c8754a2d 100644
--- a/zproject/prod_settings_template.py
+++ b/zproject/prod_settings_template.py
@@ -166,6 +166,7 @@ AUTHENTICATION_BACKENDS: tuple[str, ...] = (
# "zproject.backends.ZulipLDAPAuthBackend", # LDAP, setup below
# "zproject.backends.ZulipRemoteUserBackend", # Local SSO, setup docs on readthedocs
# "zproject.backends.GenericOpenIdConnectBackend", # Generic OIDC integration, setup below
+ # "zproject.backends.DiscordAuthBackend", # Discord auth, setup below
)
## LDAP integration.
@@ -397,6 +398,20 @@ AUTH_LDAP_USER_ATTR_MAP = {
#
# SOCIAL_AUTH_SUBDOMAIN = "auth"
+########
+## Discord OAuth.
+## To set up Discord authentication, you'll need to do the following:
+## (1) Register a new application at the Discord Developer Portal:
+## https://discord.com/developers/applications
+## (2) Navigate to the OAuth menu. Set the callback URI with value like:
+## https://zulip.example.com/complete/discord/
+## based on your value for EXTERNAL_HOST
+## (3) Note the Client ID and Secret for your new Discord application.
+## Use the Client ID as `SOCIAL_AUTH_DISCORD_KEY` here, and
+## put the Secret in zulip-secrets.conf as `social_auth_discord_secret`.
+#
+# SOCIAL_AUTH_DISCORD_KEY = "<your client ID from Discord>"
+
########
## Generic OpenID Connect (OIDC). See also documentation here:
##
diff --git a/zproject/test_extra_settings.py b/zproject/test_extra_settings.py
index 7f51fde40b6..7e2e25519a6 100644
--- a/zproject/test_extra_settings.py
+++ b/zproject/test_extra_settings.py
@@ -179,6 +179,8 @@ SOCIAL_AUTH_APPLE_AUDIENCE = [SOCIAL_AUTH_APPLE_APP_ID, SOCIAL_AUTH_APPLE_SERVIC
SOCIAL_AUTH_APPLE_KEY = "KEYISKEY"
SOCIAL_AUTH_APPLE_TEAM = "TEAMSTRING"
SOCIAL_AUTH_APPLE_SECRET = get_from_file_if_exists("zerver/tests/fixtures/apple/private_key.pem")
+SOCIAL_AUTH_DISCORD_KEY = "key"
+SOCIAL_AUTH_DISCORD_SECRET = "secret"
SOCIAL_AUTH_OIDC_ENABLED_IDPS: dict[str, OIDCIdPConfigDict] = {