Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add endpoints for users to change their username and email address

Claudedda72fa7d2e7
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 2f46035..0b5b885 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -1,11 +1,12 @@
import logging
from allauth.account.adapter import get_adapter
-from allauth.account.models import EmailConfirmationHMAC
+from allauth.account.models import EmailAddress, EmailConfirmationHMAC
from allauth.account.utils import send_email_confirmation, setup_user_email
from django.conf import settings
from django.core import signing
from django.core.exceptions import ValidationError
+from django.core.validators import validate_email
from django.db import transaction
from django.db.models import F
from django.utils import timezone
@@ -56,6 +57,8 @@ from mwmbl.platform.schemas import (
ApiKeyCreatedResponse,
ApiKeyListItem,
BulkDecisionRequest,
+ ChangeEmailRequest,
+ ChangeUsernameRequest,
CheckoutRequest,
CheckoutResponse,
CombinedSearchPreference,
@@ -106,8 +109,9 @@ router = Router(tags=["Platform"])
def check_email_verified(request):
- from_email_address = request.user.emailaddress_set.first()
- if not from_email_address.verified:
+ # Not the first address: while an email change awaits confirmation, the user also has
+ # the new, unverified one.
+ if not request.user.emailaddress_set.filter(verified=True).exists():
raise InvalidRequest("Email address is not verified", status=403)
@@ -1204,16 +1208,94 @@ def get_current_user(request):
user = request.user
billing = getattr(user, "billing", None)
spend_cents = billing.max_monthly_spend_cents if billing else 0
- email_address = user.emailaddress_set.first()
+ pending_email = _pending_email_addresses(user).first()
return UserProfileResponse(
username=user.username,
email=user.email,
plan="free" if spend_cents == 0 else "pay-as-you-go",
- email_confirmed=email_address.verified if email_address else False,
+ email_confirmed=user.emailaddress_set.filter(verified=True).exists(),
+ pending_email=pending_email.email if pending_email else None,
date_joined=user.date_joined,
)
+def _pending_email_addresses(user: MwmblUser):
+ return user.emailaddress_set.filter(verified=False).exclude(email__iexact=user.email)
+
+
+ "/user/username",
+ auth=JWTAuth(),
+ summary="Change username",
+ description=(
+ "Change the authenticated user's username. It must be unique, ignoring case, and may "
+ "contain only letters, digits and `@.+-_`. Returns the new username."
+ ),
+ tags=["Users"],
+)
+def change_username(request, body: ChangeUsernameRequest):
+ user = request.user
+ new_username = body.username.strip()
+ if new_username == user.username:
+ raise InvalidRequest("That is already your username.")
+
+ # A change of case alone would otherwise collide with the user's own name.
+ case_change_only = new_username.lower() == user.username.lower()
+ try:
+ get_adapter().clean_username(new_username, shallow=case_change_only)
+ except ValidationError as error:
+ raise InvalidRequest(error.messages[0])
+
+ user.username = new_username
+ user.save(update_fields=["username"])
+ # Cached API keys carry the user, whose username names their crawl uploads.
+ invalidate_user_api_key_cache(user.id)
+ return {"status": "ok", "username": new_username}
+
+
+ "/user/email",
+ auth=JWTAuth(),
+ summary="Change email address",
+ description=(
+ "Start changing the authenticated user's email address. Requires the current password. "
+ "A confirmation email is sent to the new address; the current address stays in use until "
+ "the new one is confirmed, and is then replaced by it. Requesting another change replaces "
+ "a pending one."
+ ),
+ tags=["Users"],
+)
+def change_email(request, body: ChangeEmailRequest):
+ user = request.user
+ if not user.check_password(body.password):
+ raise InvalidRequest("Incorrect password.", status=403)
+
+ new_email = body.email.strip()
+ try:
+ validate_email(new_email)
+ except ValidationError:
+ raise InvalidRequest("Enter a valid email address.")
+ if new_email.lower() == user.email.lower():
+ raise InvalidRequest("That is already your email address.")
+
+ used_by_another_user = (
+ MwmblUser.objects.filter(email__iexact=new_email).exclude(id=user.id).exists()
+ or EmailAddress.objects.filter(email__iexact=new_email).exclude(user=user).exists()
+ )
+ if used_by_another_user:
+ raise InvalidRequest("Email already registered")
+
+ with transaction.atomic():
+ _pending_email_addresses(user).delete()
+ EmailAddress.objects.add_email(request, user, new_email, confirm=True)
+
+ return {
+ "status": "ok",
+ "pending_email": new_email,
+ "message": "Check your new email address for a confirmation link.",
+ }
+
+
@router.get(
"/user/stats",
auth=JWTAuth(),
diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.py
index 5cf3645..3005d56 100644
--- a/mwmbl/platform/schemas.py
+++ b/mwmbl/platform/schemas.py
@@ -13,6 +13,10 @@ class UserProfileResponse(Schema):
email: str
plan: str
email_confirmed: bool
+ pending_email: Optional[str] = Field(
+ default=None,
+ description="A new email address awaiting confirmation, which replaces `email` once confirmed.",
+ )
date_joined: datetime
@@ -131,6 +135,15 @@ class ForgotPasswordRequest(Schema):
email: str
+class ChangeUsernameRequest(Schema):
+ username: str = Field(description="The new username. Must be unique, ignoring case.")
+
+
+class ChangeEmailRequest(Schema):
+ email: str = Field(description="The new email address. Must not belong to another account.")
+ password: str = Field(description="The account's current password.")
+
+
class ResetPasswordRequest(Schema):
email: str
key: str
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index f4cf616..3dbc7ea 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -149,6 +149,9 @@ ACCOUNT_USERNAME_REQUIRED = False
# mwmbl.models.SEED_CRAWLER_USERNAME, which settings cannot import.
ACCOUNT_USERNAME_BLACKLIST = ["mwmbl-seed-crawler"]
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
+# A new address waits beside the current one until it is confirmed, then replaces it.
+ACCOUNT_CHANGE_EMAIL = True
+ACCOUNT_MAX_EMAIL_ADDRESSES = 2
DEFAULT_FROM_EMAIL = "[email protected]"
diff --git a/test/test_platform_user_api.py b/test/test_platform_user_api.py
index 6c5411f..0725eff 100644
--- a/test/test_platform_user_api.py
+++ b/test/test_platform_user_api.py
@@ -4,9 +4,10 @@ re-crawl of a submission.
"""
import pytest
-from allauth.account.models import EmailAddress
+from allauth.account.models import EmailAddress, EmailConfirmationHMAC
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
+from django.core import mail
from ninja_jwt.tokens import RefreshToken
from mwmbl.models import Device, DomainEvidence, DomainSubmission, UserAgreement
@@ -104,6 +105,103 @@ def test_profile_reports_the_account_and_plan(client, member):
assert body["plan"] == "free"
+def _change_username(client, user, username: str):
+ return client.put(
+ f"{BASE}/user/username", data={"username": username}, content_type="application/json", headers=_auth(user)
+ )
+
+
+def _change_email(client, user, email: str, password: str = "correctpassword"):
+ return client.post(
+ f"{BASE}/user/email",
+ data={"email": email, "password": password},
+ content_type="application/json",
+ headers=_auth(user),
+ )
+
+
+def test_a_user_can_change_their_username(client, member):
+ response = _change_username(client, member, "new_name")
+
+ assert response.status_code == 200
+ assert response.json()["username"] == "new_name"
+ member.refresh_from_db()
+ assert member.username == "new_name"
+
+
+def test_a_username_can_change_case_alone(client, member):
+ response = _change_username(client, member, "Member")
+
+ assert response.status_code == 200
+ member.refresh_from_db()
+ assert member.username == "Member"
+
+
[email protected]("username", ["STRANGER", "mwmbl-seed-crawler", "has space", ""])
+def test_taken_reserved_and_invalid_usernames_are_refused(client, member, username):
+ _user("stranger")
+
+ response = _change_username(client, member, username)
+
+ assert response.status_code == 400
+ member.refresh_from_db()
+ assert member.username == "member"
+
+
+def test_changing_email_needs_the_password(client, member):
+ response = _change_email(client, member, "[email protected]", password="wrong")
+
+ assert response.status_code == 403
+ assert not EmailAddress.objects.filter(email="[email protected]").exists()
+
+
+ "email", ["[email protected]", "[email protected]", "not-an-email", "[email protected]"]
+)
+def test_taken_invalid_and_unchanged_emails_are_refused(client, member, email):
+ _user("stranger")
+
+ response = _change_email(client, member, email)
+
+ assert response.status_code == 400
+
+
+def test_a_new_email_replaces_the_old_one_once_confirmed(client, member):
+ response = _change_email(client, member, "[email protected]")
+
+ assert response.status_code == 200
+ assert mail.outbox[-1].to == ["[email protected]"]
+ # The old address keeps working until the new one is confirmed.
+ member.refresh_from_db()
+ assert member.email == "[email protected]"
+ assert client.get(f"{BASE}/protected", headers=_auth(member)).status_code == 200
+ assert client.get(f"{BASE}/user", headers=_auth(member)).json()["pending_email"] == "[email protected]"
+
+ pending = EmailAddress.objects.get(email="[email protected]")
+ confirmed = client.post(
+ f"{BASE}/confirm-email",
+ data={"email": "[email protected]", "key": EmailConfirmationHMAC(pending).key},
+ content_type="application/json",
+ )
+
+ assert confirmed.status_code == 200
+ member.refresh_from_db()
+ assert member.email == "[email protected]"
+ assert list(EmailAddress.objects.filter(user=member).values_list("email", "verified", "primary")) == [
+ ("[email protected]", True, True)
+ ]
+
+
+def test_a_second_email_change_replaces_the_pending_one(client, member):
+ _change_email(client, member, "[email protected]")
+ _change_email(client, member, "[email protected]")
+
+ assert sorted(EmailAddress.objects.filter(user=member).values_list("email", flat=True)) == [
+ ]
+
+
def test_refetching_clears_the_old_evidence_and_queues_a_crawl(client, member, moderator, monkeypatch):
submission = DomainSubmission.objects.create(name="example.org", submitted_by=member)
DomainEvidence.objects.create(domain="example.org", state=DomainEvidence.State.READY)