Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add UserAgreement to track what a user agrees to

Daoud Clarke260f9bde1abc
diff --git a/mwmbl/migrations/0022_add_useragreement.py b/mwmbl/migrations/0022_add_useragreement.py
new file mode 100644
index 0000000..961883d
--- /dev/null
+++ b/mwmbl/migrations/0022_add_useragreement.py
@@ -0,0 +1,38 @@
+# Generated by Django 5.2.13 on 2026-04-30 20:22
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('mwmbl', '0021_hash_api_keys'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='UserAgreement',
+ fields=[
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('agreement_type', models.CharField(choices=[('TERMS_OF_SERVICE_GUI', 'Terms of Service (GUI)'), ('TERMS_OF_SERVICE_API', 'Terms of Service (API)')], max_length=50)),
+ ('version_id', models.CharField(max_length=100)),
+ ('accepted_at', models.DateTimeField(auto_now_add=True)),
+ ],
+ ),
+ migrations.RenameIndex(
+ model_name='usagebucket',
+ new_name='mwmbl_usage_year_584313_idx',
+ old_name='mwmbl_usage_year_mo_idx',
+ ),
+ migrations.AddField(
+ model_name='useragreement',
+ name='user',
+ field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='agreements', to=settings.AUTH_USER_MODEL),
+ ),
+ migrations.AddIndex(
+ model_name='useragreement',
+ index=models.Index(fields=['user', 'agreement_type', '-accepted_at'], name='mwmbl_usera_user_id_e959ac_idx'),
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 7838701..23b99d4 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -187,6 +187,26 @@ class UserBilling(models.Model):
current_period_end = models.DateTimeField(null=True, blank=True)
+class AgreementType(models.TextChoices):
+ TERMS_OF_SERVICE_GUI = "TERMS_OF_SERVICE_GUI", "Terms of Service (GUI)"
+ TERMS_OF_SERVICE_API = "TERMS_OF_SERVICE_API", "Terms of Service (API)"
+
+
+class UserAgreement(models.Model):
+ # SET_NULL rather than CASCADE so the audit record survives account deletion.
+ user = models.ForeignKey(
+ MwmblUser, on_delete=models.SET_NULL, null=True, related_name="agreements"
+ )
+ agreement_type = models.CharField(max_length=50, choices=AgreementType.choices)
+ version_id = models.CharField(max_length=100)
+ accepted_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["user", "agreement_type", "-accepted_at"]),
+ ]
+
+
class SearchResultVote(models.Model):
VOTE_TYPES = {
"upvote": "User upvoted this result",
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 1f840f9..b3457ce 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -11,13 +11,14 @@ from polar_sdk.webhooks import validate_event, WebhookVerificationError
from mwmbl.exceptions import InvalidRequest
from mwmbl.search_auth import invalidate_api_key_cache, invalidate_user_api_key_cache
-from mwmbl.models import MwmblUser, DomainSubmission, SearchResultVote, ApiKey, UsageBucket, UserBilling, generate_username
+from mwmbl.models import AgreementType, MwmblUser, DomainSubmission, SearchResultVote, ApiKey, UsageBucket, UserBilling, UserAgreement, generate_username
from mwmbl.platform.schemas import (
Registration, ConfirmEmail, DomainSubmissionSchema, UpdateDomainSubmission,
VoteRequest, VoteRemoveRequest, VoteStatsRequest, VoteResponse, VoteStats, UserVoteHistory,
CreateApiKeyRequest, ApiKeyCreatedResponse, ApiKeyListItem,
UserProfileResponse, SubscriptionResponse, CheckoutRequest, CheckoutResponse,
ForgotPasswordRequest, ResetPasswordRequest,
+ AgreementAcceptRequest, AgreementResponse,
)
router = Router(tags=["Platform"])
@@ -53,6 +54,9 @@ def register(request, registration: Registration):
user.set_password(registration.password)
user.save()
+ if registration.agreements:
+ _record_agreements(user, registration.agreements)
+
setup_user_email(request, user, [])
send_email_confirmation(request, user, signup=True)
@@ -335,6 +339,117 @@ def get_user_vote_history(request) -> list[SearchResultVote]:
return SearchResultVote.objects.filter(user=request.user).order_by('-timestamp')
+# ---------------------------------------------------------------------------
+# Agreements helpers
+# ---------------------------------------------------------------------------
+
+def _record_agreements(user: MwmblUser, agreement_types: list) -> None:
+ for agreement_type in agreement_types:
+ version_id = settings.CURRENT_AGREEMENT_VERSIONS.get(agreement_type)
+ if version_id:
+ UserAgreement.objects.create(
+ user=user,
+ agreement_type=agreement_type,
+ version_id=version_id,
+ )
+
+
+def _require_current_agreement(user: MwmblUser, agreement_type: AgreementType) -> None:
+ current_version = settings.CURRENT_AGREEMENT_VERSIONS.get(agreement_type)
+ accepted = UserAgreement.objects.filter(
+ user=user,
+ agreement_type=agreement_type,
+ version_id=current_version,
+ ).exists()
+ if not accepted:
+ raise InvalidRequest(
+ f"You must accept the current {agreement_type} (version {current_version}) before using this feature.",
+ status=403,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Agreement endpoints
+# ---------------------------------------------------------------------------
+
+ "/agreements/",
+ auth=JWTAuth(),
+ response=AgreementResponse,
+ summary="Accept a terms agreement",
+ description=(
+ "Record acceptance of a terms agreement for the authenticated user. "
+ "The server stamps the current version and timestamp — the client only supplies the agreement type. "
+ "Calling this again after a version update creates a new acceptance record for the new version. "
+ "Requires a verified account."
+ ),
+ tags=["Agreements"],
+)
+def accept_agreement(request, body: AgreementAcceptRequest):
+ check_email_verified(request)
+ version_id = settings.CURRENT_AGREEMENT_VERSIONS.get(body.agreement_type)
+ if not version_id:
+ raise InvalidRequest("Unknown agreement type.", status=400)
+ agreement = UserAgreement.objects.create(
+ user=request.user,
+ agreement_type=body.agreement_type,
+ version_id=version_id,
+ )
+ return AgreementResponse(
+ agreement_type=agreement.agreement_type,
+ version_id=agreement.version_id,
+ accepted_at=agreement.accepted_at,
+ )
+
+
+ "/agreements/",
+ auth=JWTAuth(),
+ response=list[AgreementResponse],
+ summary="Get current agreements",
+ description=(
+ "Returns the most recently accepted version of each agreement type for the authenticated user. "
+ "Only types the user has accepted appear in the response. "
+ "Requires a verified account."
+ ),
+ tags=["Agreements"],
+)
+def get_agreements(request) -> list[AgreementResponse]:
+ check_email_verified(request)
+ result = []
+ for agreement_type in AgreementType:
+ latest = (
+ UserAgreement.objects.filter(user=request.user, agreement_type=agreement_type)
+ .order_by("-accepted_at")
+ .first()
+ )
+ if latest:
+ result.append(AgreementResponse(
+ agreement_type=latest.agreement_type,
+ version_id=latest.version_id,
+ accepted_at=latest.accepted_at,
+ ))
+ return result
+
+
+ "/agreements/history/",
+ auth=JWTAuth(),
+ response=list[AgreementResponse],
+ summary="Get agreement acceptance history",
+ description=(
+ "Returns the full history of all agreement acceptances for the authenticated user, "
+ "ordered most-recent first. Useful for compliance audits. "
+ "Requires a verified account."
+ ),
+ tags=["Agreements"],
+)
+@paginate
+def get_agreement_history(request) -> list[AgreementResponse]:
+ check_email_verified(request)
+ return UserAgreement.objects.filter(user=request.user).order_by("-accepted_at")
+
+
# ---------------------------------------------------------------------------
# API key management
# ---------------------------------------------------------------------------
@@ -354,6 +469,7 @@ def get_user_vote_history(request) -> list[SearchResultVote]:
)
def create_api_key(request, body: CreateApiKeyRequest):
check_email_verified(request)
+ _require_current_agreement(request.user, AgreementType.TERMS_OF_SERVICE_API)
from mwmbl.models import generate_api_key
raw_key, key_hash = generate_api_key()
api_key = ApiKey.objects.create(
diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.py
index edc5f41..39e19a1 100644
--- a/mwmbl/platform/schemas.py
+++ b/mwmbl/platform/schemas.py
@@ -2,7 +2,7 @@ from datetime import datetime
from typing import Optional, Literal
from ninja import Schema, ModelSchema, Field
-from mwmbl.models import DomainSubmission
+from mwmbl.models import AgreementType, DomainSubmission
class UserProfileResponse(Schema):
@@ -76,6 +76,20 @@ class ApiKeyListItem(Schema):
scopes: list[str] = Field(description="Scopes granted to this key.")
+# ---------------------------------------------------------------------------
+# Agreements
+# ---------------------------------------------------------------------------
+
+class AgreementAcceptRequest(Schema):
+ agreement_type: AgreementType = Field(description="The type of agreement being accepted.")
+
+
+class AgreementResponse(Schema):
+ agreement_type: str = Field(description="The type of agreement.")
+ version_id: str = Field(description="The version of the agreement that was accepted.")
+ accepted_at: datetime = Field(description="When the agreement was accepted.")
+
+
class Registration(Schema):
email: str = Field(description="Email address for the new account. Must be unique.")
password: str = Field(description="Password for the new account.")
@@ -86,6 +100,14 @@ class Registration(Schema):
"`adjective_noun_NNN` (e.g. `swift_falcon_379`). Must be unique if provided."
),
)
+ agreements: list[AgreementType] = Field(
+ default=[],
+ description=(
+ "Optional list of agreement types accepted at signup. "
+ "The server stamps the current version and timestamp. "
+ "Accepted values: `TERMS_OF_SERVICE_GUI`, `TERMS_OF_SERVICE_API`."
+ ),
+ )
class ConfirmEmail(Schema):
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index 3df3551..b5fec1d 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -268,3 +268,8 @@ POLAR_ACCESS_TOKEN = os.environ.get("POLAR_ACCESS_TOKEN", "")
POLAR_WEBHOOK_SECRET = os.environ.get("POLAR_WEBHOOK_SECRET", "")
POLAR_PRODUCT_ID_STARTER = os.environ.get("POLAR_PRODUCT_ID_STARTER", "")
POLAR_PRODUCT_ID_PRO = os.environ.get("POLAR_PRODUCT_ID_PRO", "")
+
+CURRENT_AGREEMENT_VERSIONS = {
+ "TERMS_OF_SERVICE_GUI": "v2026-04-A",
+ "TERMS_OF_SERVICE_API": "v2026-04-A",
+}