An open source, non-profit web search engine
Dedup marketing consent: only append on a state change
Daoud Clarkeb4b8931ddf75
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex 0e0974c..12c5d56 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -366,6 +366,20 @@ def _record_agreements(user: MwmblUser, agreement_types: list) -> None:def _record_marketing_consent(user: MwmblUser, source: MarketingSource, opted_in: bool) -> MarketingConsent:+ """+ Append a consent decision for this (user, source), but only when it changes the+ current state. Repeated identical decisions — e.g. mail-client scanners POSTing+ the one-click unsubscribe URL, or a user re-confirming an existing choice — return+ the existing row instead of growing the audit trail. Returns the row representing+ the current state.+ """+ latest = (+ MarketingConsent.objects.filter(user=user, source=source)+ .order_by("-timestamp", "-id")+ .first()+ )+ if latest is not None and latest.opted_in == opted_in:+ return latestreturn MarketingConsent.objects.create(user=user, source=source, opted_in=opted_in)diff --git a/test/test_marketing_consent.py b/test/test_marketing_consent.pyindex 96c24e4..71f4094 100644--- a/test/test_marketing_consent.py+++ b/test/test_marketing_consent.py@@ -110,6 +110,22 @@ def test_update_marketing_consent_appends_row(client, verified_user, access_tokeassert latest[0]["opted_in"] is False+def test_update_marketing_consent_noop_does_not_append(client, verified_user, access_token):+ MarketingConsent.objects.create(user=verified_user, source=MarketingSource.GUI, opted_in=True)++ response = client.post(+ CONSENT_URL,+ data=json.dumps({"source": "GUI", "opted_in": True}),+ content_type="application/json",+ HTTP_AUTHORIZATION=f"Bearer {access_token}",+ )+ assert response.status_code == 200+ assert response.json()["opted_in"] is True+ # Re-confirming the existing state must not grow the audit trail.+ assert MarketingConsent.objects.filter(user=verified_user, source=MarketingSource.GUI).count() == 1++@pytest.mark.django_dbdef test_marketing_consent_requires_auth(client):assert client.get(CONSENT_URL).status_code == 401@@ -133,9 +149,11 @@ def test_unsubscribe_is_idempotent(client, verified_user):token = make_unsubscribe_token(verified_user, MarketingSource.GUI)client.post(f"{UNSUBSCRIBE_URL}?token={token}")client.post(f"{UNSUBSCRIBE_URL}?token={token}")+ # Idempotent at the storage layer too: a repeat POST (e.g. a mail-client link+ # scanner) that doesn't change the state must not append a duplicate opt-out row.consents = MarketingConsent.objects.filter(user=verified_user, source=MarketingSource.GUI)- assert consents.count() == 2- assert all(c.opted_in is False for c in consents)+ assert consents.count() == 1+ assert consents.first().opted_in is False@pytest.mark.django_db