Membership: optional "Sign up with Google/GitHub" next to email sign-up

Google (OIDC) or GitHub (OAuth, primary+verified email from /user/emails)
only proves the email address at registration. The person then chooses an
eom.dev username and password, the LDAP account is created by the same
provisioning helper as email sign-up, and every login still goes through
Dex. Provider tokens and user IDs are never stored; GitHub noreply
addresses are refused. Each button appears only when its client ID and
secret are configured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 20:41:34 -05:00
co-authored by Claude Opus 5.5
parent c5d7dc7f03
commit 461917595f
6 changed files with 434 additions and 25 deletions
+10
View File
@@ -88,6 +88,16 @@ DEX_CLIENT_ID = os.environ.get("DEX_CLIENT_ID", "www-membership")
DEX_CLIENT_SECRET = os.environ.get("DEX_CLIENT_SECRET", "")
DEX_CONNECTOR_ID = os.environ.get("DEX_CONNECTOR_ID", "ldap")
# Optional "Sign up with Google/GitHub": the provider only verifies the email address at
# registration. Accounts still live in LDAP and every login goes through Dex.
GOOGLE_ISSUER = "https://accounts.google.com"
GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "")
GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET", "")
GOOGLE_SIGNUP_ENABLED = bool(GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET)
GITHUB_CLIENT_ID = os.environ.get("GITHUB_CLIENT_ID", "")
GITHUB_CLIENT_SECRET = os.environ.get("GITHUB_CLIENT_SECRET", "")
GITHUB_SIGNUP_ENABLED = bool(GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET)
LDAP_URL = os.environ.get("LDAP_URL", "")
# Explicit opt-in for trusted internal networks; never a TLS-error fallback.
LDAP_ALLOW_INSECURE = os.environ.get("LDAP_ALLOW_INSECURE", "0") == "1"
+13
View File
@@ -35,3 +35,16 @@ class PasswordForm(forms.Form):
if data.get("password") != data.get("confirm_password"):
self.add_error("confirm_password", "Passwords must match.")
return data
class SocialRegistrationForm(PasswordForm):
"""Google or GitHub already verified the email; only the username and password remain."""
uid = RegistrationForm.base_fields["uid"]
newsletter = forms.BooleanField(required=False, label=NEWSLETTER_LABEL)
field_order = ["uid", "password", "confirm_password", "newsletter"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not settings.LISTMONK_ENABLED:
del self.fields["newsletter"]
@@ -0,0 +1,223 @@
import time
from datetime import timedelta
from unittest.mock import MagicMock, patch
from urllib.parse import parse_qs, urlsplit
from authlib.integrations.django_client import OAuth
from django.test import TestCase, override_settings
from django.utils import timezone
from joserfc import jwt
from joserfc.jwk import RSAKey
from members.models import Account, Registration
ISSUER = "https://accounts.google.com"
CLIENT_ID = "test-client.apps.googleusercontent.com"
PASSWORD = "correct-horse-purple-planet-943!"
IDENTITY = {"uid": "alice", "email": "alice@example.org", "ldap_dn": "uid=alice,ou=people,dc=example,dc=org", "ldap_uuid": "uuid-alice"}
@override_settings(GOOGLE_CLIENT_ID=CLIENT_ID, GOOGLE_CLIENT_SECRET="test-only", GOOGLE_SIGNUP_ENABLED=True, GITHUB_SIGNUP_ENABLED=False, LISTMONK_ENABLED=False)
class GoogleSignupTests(TestCase):
"""Google only verifies the email; the account is LDAP and logs in through Dex."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.key = RSAKey.generate_key(2048, parameters={"kid": "google-test"})
def remote(self):
return OAuth().register("google", client_id=CLIENT_ID, client_secret="test-only", issuer=ISSUER, authorization_endpoint="https://accounts.google.com/o/oauth2/v2/auth", token_endpoint="https://oauth2.googleapis.com/token", jwks_uri="https://www.googleapis.com/oauth2/v3/certs", id_token_signing_alg_values_supported=["RS256"], client_kwargs={"scope": "openid email", "code_challenge_method": "S256"})
def google_round_trip(self, **changes):
remote = self.remote()
with patch("members.views.google", return_value=remote):
start = self.client.get("/members/register/google/")
self.assertEqual(start.status_code, 302)
url = urlsplit(start["Location"])
self.assertEqual(url.hostname, "accounts.google.com")
params = parse_qs(url.query)
self.assertEqual(params["code_challenge_method"], ["S256"])
self.assertEqual(params["scope"], ["openid email"])
self.assertEqual(params["redirect_uri"], ["https://eom.dev/members/register/google/callback/"])
claims = {"iss": ISSUER, "sub": "google-sub-123", "aud": CLIENT_ID, "iat": int(time.time()), "exp": int(time.time()) + 300, "nonce": params["nonce"][0], "email": "Alice@Example.org", "email_verified": True, **changes}
token = {"access_token": "test-only", "id_token": jwt.encode({"alg": "RS256", "kid": "google-test"}, claims, self.key)}
with patch.object(remote, "fetch_access_token", return_value=token), patch.object(remote, "fetch_jwk_set", return_value={"keys": [self.key.as_dict(private=False)]}):
return self.client.get("/members/register/google/callback/", {"code": "test-code", "state": params["state"][0]})
def test_register_page_offers_both_options(self):
response = self.client.get("/members/register/")
self.assertContains(response, "Sign up with Google")
self.assertContains(response, "Send verification email")
with self.settings(GOOGLE_SIGNUP_ENABLED=False):
response = self.client.get("/members/register/")
self.assertNotContains(response, "Sign up with Google")
self.assertContains(response, "Send verification email")
@patch("members.views.directory.create_account", return_value=IDENTITY)
def test_google_verified_email_then_username_and_password(self, provision):
response = self.google_round_trip()
self.assertRedirects(response, "/members/register/social/finish/", fetch_redirect_response=False)
# Only the verified address is kept: no Google tokens or subject IDs.
proof = self.client.session["social_registration"]
self.assertEqual(set(proof), {"provider", "email", "expires_at"})
self.assertEqual(proof["provider"], "google")
self.assertEqual(proof["email"], "alice@example.org")
self.assertNotIn("google-sub-123", str(dict(self.client.session)))
self.assertContains(self.client.get("/members/register/social/finish/"), "Google verified alice@example.org")
response = self.client.post("/members/register/social/finish/", {"uid": "alice", "password": PASSWORD, "confirm_password": PASSWORD})
self.assertContains(response, "Account created")
provision.assert_called_once_with("alice", "alice@example.org", PASSWORD)
member = Account.objects.get()
self.assertEqual(member.membership_level, 0)
# Not signed in and not bound to Google: the first login goes through Dex.
self.assertEqual(member.oidc_sub, None)
self.assertNotIn("account_id", self.client.session)
self.assertNotIn("social_registration", self.client.session)
self.assertEqual(self.client.session["registration_identity"]["account_id"], str(member.pk))
# The proof is single use.
self.assertContains(self.client.post("/members/register/social/finish/", {"uid": "alice2", "password": PASSWORD, "confirm_password": PASSWORD}), "Sign-up expired")
self.assertEqual(provision.call_count, 1)
@patch("members.views.directory.create_account")
def test_unverified_or_foreign_tokens_rejected(self, provision):
for changes in ({"email_verified": False}, {"email_verified": "true"}, {"email": None}, {"iss": "https://evil.example"}, {"aud": "another-client"}, {"nonce": "attacker"}):
with self.subTest(changes=changes):
self.client.session.flush()
response = self.google_round_trip(**changes)
self.assertContains(response, "could not be verified")
self.assertNotIn("social_registration", self.client.session)
provision.assert_not_called()
@patch("members.views.directory.create_account")
def test_finish_requires_fresh_proof(self, provision):
self.assertContains(self.client.post("/members/register/social/finish/", {"uid": "alice", "password": PASSWORD, "confirm_password": PASSWORD}), "Sign-up expired")
session = self.client.session
session["social_registration"] = {"provider": "google", "email": "alice@example.org", "expires_at": (timezone.now() - timedelta(seconds=1)).timestamp()}
session.save()
self.assertContains(self.client.post("/members/register/social/finish/", {"uid": "alice", "password": PASSWORD, "confirm_password": PASSWORD}), "Sign-up expired")
provision.assert_not_called()
@patch("members.views.directory.create_account", side_effect=ValueError("exists"))
def test_taken_username_or_email_keeps_proof_for_retry(self, provision):
self.google_round_trip()
response = self.client.post("/members/register/social/finish/", {"uid": "alice", "password": PASSWORD, "confirm_password": PASSWORD})
self.assertContains(response, "already in use")
self.assertFalse(Account.objects.exists())
self.assertIn("social_registration", self.client.session)
@patch("members.views.directory.create_account", return_value=IDENTITY)
def test_clears_pending_email_registration_for_same_username(self, provision):
Registration.objects.create(token_hash="a" * 64, uid="alice", email="alice@example.org", expires_at=timezone.now() + timedelta(hours=1))
self.google_round_trip()
self.client.post("/members/register/social/finish/", {"uid": "alice", "password": PASSWORD, "confirm_password": PASSWORD})
self.assertFalse(Registration.objects.exists())
@patch("members.views.directory.create_account", return_value=IDENTITY)
def test_accepts_schemeless_google_issuer(self, provision):
response = self.google_round_trip(iss="accounts.google.com")
self.assertRedirects(response, "/members/register/social/finish/", fetch_redirect_response=False)
def test_disabled_without_client_credentials(self):
with self.settings(GOOGLE_SIGNUP_ENABLED=False):
self.assertEqual(self.client.get("/members/register/google/").status_code, 404)
self.assertEqual(self.client.get("/members/register/google/callback/").status_code, 404)
self.assertEqual(self.client.get("/members/register/github/").status_code, 404)
self.assertContains(self.client.get("/members/register/social/finish/"), "Sign-up expired")
def test_password_rules_apply(self):
self.google_round_trip()
response = self.client.post("/members/register/social/finish/", {"uid": "alice", "password": "123", "confirm_password": "123"})
self.assertContains(response, "too short")
GITHUB_EMAILS = [
{"email": "old@example.org", "primary": False, "verified": True, "visibility": None},
{"email": "Bob@Example.org", "primary": True, "verified": True, "visibility": "private"},
]
@override_settings(GITHUB_CLIENT_ID="Iv1.test", GITHUB_CLIENT_SECRET="test-only", GITHUB_SIGNUP_ENABLED=True, GOOGLE_SIGNUP_ENABLED=False, LISTMONK_ENABLED=False)
class GitHubSignupTests(TestCase):
def remote(self):
return OAuth().register("github", client_id="Iv1.test", client_secret="test-only", authorize_url="https://github.com/login/oauth/authorize", access_token_url="https://github.com/login/oauth/access_token", api_base_url="https://api.github.com/", client_kwargs={"scope": "user:email", "code_challenge_method": "S256"})
def github_round_trip(self, emails=GITHUB_EMAILS, token=None, status=200):
remote = self.remote()
with patch("members.views.github", return_value=remote):
start = self.client.get("/members/register/github/")
self.assertEqual(start.status_code, 302)
url = urlsplit(start["Location"])
self.assertEqual(url.hostname, "github.com")
params = parse_qs(url.query)
self.assertEqual(params["scope"], ["user:email"])
self.assertEqual(params["code_challenge_method"], ["S256"])
self.assertEqual(params["redirect_uri"], ["https://eom.dev/members/register/github/callback/"])
api = MagicMock()
api.json.return_value = emails
if status != 200:
api.raise_for_status.side_effect = Exception("HTTP error")
token = {"access_token": "gho_test", "token_type": "bearer", "scope": "user:email"} if token is None else token
with patch.object(remote, "fetch_access_token", return_value=token) as exchange, patch.object(remote, "get", return_value=api) as get:
response = self.client.get("/members/register/github/callback/", {"code": "test-code", "state": params["state"][0]})
if exchange.called:
self.assertTrue(exchange.call_args.kwargs["code_verifier"])
if get.called:
self.assertEqual(get.call_args.args[0], "user/emails")
return response
def test_register_page_offers_github(self):
response = self.client.get("/members/register/")
self.assertContains(response, "Sign up with GitHub")
self.assertNotContains(response, "Sign up with Google")
self.assertEqual(self.client.get("/members/register/google/").status_code, 404)
@patch("members.views.directory.create_account", return_value=IDENTITY)
def test_primary_verified_email_then_username_and_password(self, provision):
response = self.github_round_trip()
self.assertRedirects(response, "/members/register/social/finish/", fetch_redirect_response=False)
proof = self.client.session["social_registration"]
self.assertEqual((proof["provider"], proof["email"]), ("github", "bob@example.org"))
self.assertNotIn("gho_test", str(dict(self.client.session)))
self.assertContains(self.client.get("/members/register/social/finish/"), "GitHub verified bob@example.org")
response = self.client.post("/members/register/social/finish/", {"uid": "bob", "password": PASSWORD, "confirm_password": PASSWORD})
self.assertContains(response, "Account created")
provision.assert_called_once_with("bob", "bob@example.org", PASSWORD)
self.assertIsNone(Account.objects.get().oidc_sub)
self.assertNotIn("social_registration", self.client.session)
@patch("members.views.directory.create_account")
def test_rejects_unverified_nonprimary_noreply_and_errors(self, provision):
cases = [
[{"email": "bob@example.org", "primary": True, "verified": False}],
[{"email": "bob@example.org", "primary": False, "verified": True}],
[{"email": "123+bob@users.noreply.github.com", "primary": True, "verified": True}],
[{"email": "not-an-email", "primary": True, "verified": True}],
{"message": "Bad credentials"},
[],
]
for emails in cases:
with self.subTest(emails=emails):
self.client.session.flush()
self.assertContains(self.github_round_trip(emails=emails), "could not be verified")
self.assertNotIn("social_registration", self.client.session)
self.client.session.flush()
self.assertContains(self.github_round_trip(status=401), "could not be verified")
self.client.session.flush()
self.assertContains(self.github_round_trip(token={"error": "bad_verification_code"}), "could not be verified")
provision.assert_not_called()
def test_denied_or_forged_state_never_exchanges_code(self):
remote = self.remote()
with patch("members.views.github", return_value=remote), patch.object(remote, "fetch_access_token") as exchange:
self.client.get("/members/register/github/")
self.assertContains(self.client.get("/members/register/github/callback/", {"code": "x", "state": "forged"}), "could not be verified")
self.assertContains(self.client.get("/members/register/github/callback/", {"error": "access_denied"}), "could not be verified")
exchange.assert_not_called()
@patch("members.views.directory.create_account")
def test_proof_from_disabled_provider_is_ignored(self, provision):
self.github_round_trip()
with self.settings(GITHUB_SIGNUP_ENABLED=False):
self.assertContains(self.client.post("/members/register/social/finish/", {"uid": "bob", "password": PASSWORD, "confirm_password": PASSWORD}), "Sign-up expired")
provision.assert_not_called()
+3
View File
@@ -8,6 +8,9 @@ urlpatterns = [
path("register/", views.register, name="register"),
path("verify/<str:token>/", views.verify, name="verify"),
path("register/finish/", views.finish_registration, name="finish_registration"),
path("register/social/finish/", views.social_finish, name="social_finish"),
path("register/<slug:provider>/", views.social_signup, name="social_signup"),
path("register/<slug:provider>/callback/", views.social_callback, name="social_callback"),
path("login/", views.login, name="login"),
path("oidc/callback/", views.callback, name="callback"),
path("logout/", views.logout, name="logout"),
+181 -25
View File
@@ -24,7 +24,7 @@ from django.views.decorators.debug import sensitive_post_parameters
from django.views.decorators.http import require_GET, require_POST, require_http_methods
from . import billing, directory, newsletter, profiles, shkeeper
from .forms import PasswordForm, RegistrationForm
from .forms import PasswordForm, RegistrationForm, SocialRegistrationForm
from .service_groups import configured_groups, service_access_catalog
from .profile_forms import CurrentPasswordForm, ProfileEmailForm, ProfileForm, ProfilePasswordForm
from .models import Account, CryptoInvoice, ManagedGroup, ProfileEmailChange, RateWindow, Registration, Subscription, WebhookEvent
@@ -101,7 +101,7 @@ def register(request):
logger.error("Registration email failed kind=%s", type(exc).__name__)
return page(request, title="Email unavailable", message="Account email could not be sent. Please try again later.")
return page(request, title="Check your inbox", message="Follow the confirmation link in your email to choose a password and finish creating your free eom.dev account. If you already have an account, sign in instead.")
return page(request, title="Create your free account", form=form, submit="Send verification email", registration=True)
return page(request, title="Create your free account", form=form, submit="Send verification email", registration=True, signup_providers=signup_providers())
@sensitive_post_parameters("password", "confirm_password")
@@ -130,32 +130,188 @@ def finish_registration(request):
if request.method == "POST" and form.is_valid():
if limited("provision-ip", client_ip(request), 10):
return HttpResponse("Please try again later.", status=429)
try:
with transaction.atomic():
registration = Registration.objects.select_for_update().get(pk=digest, expires_at__gt=timezone.now())
identity = directory.create_account(registration.uid, registration.email, form.cleaned_data["password"])
account = Account.objects.create(**identity)
remember_groups(account)
Registration.objects.filter(uid=registration.uid).delete()
request.session.pop("registration_hash", None)
subscribed = registration.newsletter and _subscribe_newsletter(account)
# Server-side, short-lived proof permits first binding of ONLY the
# account just provisioned in this browser, never an email match.
request.session["registration_identity"] = {"account_id": str(account.pk), "expires_at": (timezone.now() + timedelta(hours=1)).timestamp()}
message = "Your free eom.dev account is ready. Sign in to explore the community and its services, or choose an optional paid membership for additional benefits."
if subscribed:
message += " You're subscribed to premiere emails; you can change that from your profile."
elif registration.newsletter:
message += " We couldn't sign you up for premiere emails just now; you can try again from your profile."
return page(request, title="Account created", message=message)
except ValueError:
form.add_error(None, "An account with those details may already exist. Try signing in or contact us for help.")
except Exception as exc:
logger.error("Account provisioning failed kind=%s", type(exc).__name__)
form.add_error(None, "Account creation could not finish. Try signing in first, or contact us for help before retrying.")
def claim():
registration = Registration.objects.select_for_update().get(pk=digest, expires_at__gt=timezone.now())
Registration.objects.filter(uid=registration.uid).delete()
return registration.uid, registration.email, registration.newsletter
response = _provision(request, form, claim, session_key="registration_hash", duplicate_error="An account with those details may already exist. Try signing in or contact us for help.")
if response:
return response
return page(request, title="Choose your password", form=form, submit="Create free account")
def _provision(request, form, claim, *, session_key, duplicate_error):
"""Create the LDAP account and local record for a verified email address.
``claim`` runs inside the transaction and returns (uid, email, newsletter)
after consuming whatever proved the email. Returns a response on success,
or None after adding an error to ``form``.
"""
try:
with transaction.atomic():
uid, email, wants_newsletter = claim()
identity = directory.create_account(uid, email, form.cleaned_data["password"])
account = Account.objects.create(**identity)
remember_groups(account)
except ValueError:
form.add_error(None, duplicate_error)
return None
except Exception as exc:
logger.error("Account provisioning failed kind=%s", type(exc).__name__)
form.add_error(None, "Account creation could not finish. Try signing in first, or contact us for help before retrying.")
return None
request.session.pop(session_key, None)
subscribed = wants_newsletter and _subscribe_newsletter(account)
# Server-side, short-lived proof permits first binding of ONLY the
# account just provisioned in this browser, never an email match.
request.session["registration_identity"] = {"account_id": str(account.pk), "expires_at": (timezone.now() + timedelta(hours=1)).timestamp()}
message = "Your free eom.dev account is ready. Sign in to explore the community and its services, or choose an optional paid membership for additional benefits."
if subscribed:
message += " You're subscribed to premiere emails; you can change that from your profile."
elif wants_newsletter:
message += " We couldn't sign you up for premiere emails just now; you can try again from your profile."
return page(request, title="Account created", message=message)
# Each provider only proves an email address at registration. None of them is a
# login method: the account lives in LDAP and signs in through Dex.
SIGNUP_PROVIDERS = {"google": "Google", "github": "GitHub"}
def signup_providers():
return {key: label for key, label in SIGNUP_PROVIDERS.items() if getattr(settings, f"{key.upper()}_SIGNUP_ENABLED", False)}
def google():
oauth = OAuth()
remote = oauth.register("google", client_id=settings.GOOGLE_CLIENT_ID, client_secret=settings.GOOGLE_CLIENT_SECRET, server_metadata_url=settings.GOOGLE_ISSUER + "/.well-known/openid-configuration", client_kwargs={"scope": "openid email", "code_challenge_method": "S256", "timeout": 10})
metadata = remote.load_server_metadata()
if metadata.get("issuer") != settings.GOOGLE_ISSUER:
raise ValueError("Google discovery issuer mismatch.")
metadata["id_token_signing_alg_values_supported"] = ["RS256"]
for endpoint in ("authorization_endpoint", "token_endpoint", "jwks_uri"):
url = urlsplit(metadata.get(endpoint, ""))
if url.scheme != "https" or not url.hostname or not (url.hostname == "google.com" or url.hostname.endswith(".google.com") or url.hostname.endswith(".googleapis.com")) or url.username:
raise ValueError("Google endpoints must be HTTPS URLs on Google domains.")
return remote
def _clean_email(email):
if not isinstance(email, str) or len(email) > 254:
raise ValueError("A verified email is required.")
validate_email(email)
return email.strip().casefold()
def google_email(claims):
"""Return the casefolded, Google-verified email from ID token claims."""
if claims.get("iss") not in (settings.GOOGLE_ISSUER, "accounts.google.com") or claims.get("email_verified") is not True:
raise ValueError("A verified Google email is required.")
return _clean_email(claims.get("email"))
def github():
# GitHub is plain OAuth 2.0, not OpenID Connect: there is no ID token, so the
# verified address comes from the authenticated /user/emails API instead.
oauth = OAuth()
return oauth.register("github", client_id=settings.GITHUB_CLIENT_ID, client_secret=settings.GITHUB_CLIENT_SECRET, authorize_url="https://github.com/login/oauth/authorize", access_token_url="https://github.com/login/oauth/access_token", api_base_url="https://api.github.com/", client_kwargs={"scope": "user:email", "code_challenge_method": "S256", "timeout": 10})
def github_email(remote, token):
"""Return the casefolded primary email, only if GitHub has verified it."""
response = remote.get("user/emails", token=token, headers={"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28"})
response.raise_for_status()
entries = response.json()
if not isinstance(entries, list):
raise ValueError("Unexpected GitHub email response.")
for entry in entries:
if isinstance(entry, dict) and entry.get("primary") is True and entry.get("verified") is True:
email = _clean_email(entry.get("email"))
# Private relay addresses cannot receive account mail.
if email.endswith("@users.noreply.github.com"):
break
return email
raise ValueError("A verified primary GitHub email is required.")
@require_GET
def social_signup(request, provider):
# A plain link, not a form post, so CSP form-action 'self' never blocks the
# redirect to the provider. State (and PKCE, plus a nonce for Google)
# protects the callback.
providers = signup_providers()
if provider not in providers:
return HttpResponse(status=404)
if limited("signup-ip", client_ip(request), 20):
return HttpResponse("Please try again later.", status=429)
callback = settings.PUBLIC_URL + reverse("members:social_callback", args=[provider])
try:
if provider == "google":
return google().authorize_redirect(request, callback, nonce=secrets.token_urlsafe(32), prompt="select_account")
return github().authorize_redirect(request, callback)
except Exception as exc:
logger.error("Sign-up provider unavailable provider=%s kind=%s", provider, type(exc).__name__)
return page(request, title=f"{providers[provider]} sign-up unavailable", message="Please try again later, or create your account with email instead.")
@require_GET
def social_callback(request, provider):
providers = signup_providers()
if provider not in providers:
return HttpResponse(status=404)
try:
if provider == "google":
token = google().authorize_access_token(request, claims_options={"iss": {"essential": True, "values": [settings.GOOGLE_ISSUER, "accounts.google.com"]}}, leeway=30)
if not token.get("id_token"):
raise ValueError("ID token is required.")
email = google_email(token.get("userinfo") or {})
else:
remote = github()
token = remote.authorize_access_token(request)
if not token.get("access_token"):
raise ValueError("Access token is required.")
email = github_email(remote, token)
except Exception as exc:
logger.error("Sign-up callback rejected provider=%s kind=%s", provider, type(exc).__name__)
return page(request, title=f"{providers[provider]} sign-up could not be verified", message="Try again, or create your account with email instead.")
# Keep only the verified address; never store provider tokens or user IDs.
request.session["social_registration"] = {"provider": provider, "email": email, "expires_at": (timezone.now() + timedelta(hours=1)).timestamp()}
return redirect("members:social_finish")
def _social_registration(request):
proof = request.session.get("social_registration")
if not isinstance(proof, dict) or proof.get("provider") not in signup_providers() or not isinstance(proof.get("email"), str):
return None
if not isinstance(proof.get("expires_at"), (int, float)) or proof["expires_at"] <= timezone.now().timestamp():
return None
return proof["provider"], proof["email"]
@sensitive_post_parameters("password", "confirm_password")
@require_http_methods(["GET", "POST"])
def social_finish(request):
proof = _social_registration(request)
if not proof:
return page(request, title="Sign-up expired", message="Start again, or create your account with email instead.")
provider, email = proof
form = SocialRegistrationForm(request.POST or None)
if request.method == "POST" and form.is_valid():
if limited("provision-ip", client_ip(request), 10) or limited("signup-email", email, 3):
return HttpResponse("Please try again later.", status=429)
def claim():
Registration.objects.filter(uid=form.cleaned_data["uid"]).delete()
return form.cleaned_data["uid"], email, form.cleaned_data.get("newsletter", False)
response = _provision(request, form, claim, session_key="social_registration", duplicate_error="That username or email address is already in use. Choose another username, or sign in if you already have an account.")
if response:
return response
return page(request, title="Choose your username and password", message=f"{SIGNUP_PROVIDERS[provider]} verified {email}. Choose how you'll sign in to eom.dev: you'll use this username and password for every eom.dev service.", form=form, submit="Create free account")
def _subscribe_newsletter(account):
# The address was verified by the registration link, so it is preconfirmed.
# Best effort: the account already exists whatever happens here.
+4
View File
@@ -29,6 +29,10 @@
</ol>
<p>Creating an account is free. Paid memberships are optional and unlock additional benefits.</p>
{% endif %}
{% if signup_providers %}
<p class="member-actions">{% for key, label in signup_providers.items %}<a class="button button-secondary" href="{% url 'members:social_signup' key %}">Sign up with {{ label }}</a> {% endfor %}</p>
<p class="tier-footnote">This only confirms your email address. You'll still choose an eom.dev username and password, and use them to sign in everywhere. Or sign up with email below.</p>
{% endif %}
{% if form %}
<form method="post">
{% csrf_token %}