Self hosted FLOSS fitness/workout, nutrition and weight tracker
Enforce email uniqueness validation
Roland Geider85e12a613712
diff --git a/wger/core/api/serializers.py b/wger/core/api/serializers.pyindex a7e3e4335..db4c6c584 100644--- a/wger/core/api/serializers.py+++ b/wger/core/api/serializers.py@@ -24,6 +24,10 @@ from django.http import HttpRequest# Third Partyfrom allauth.account.models import EmailAddress+from allauth.account.utils import (+ filter_users_by_email,+ user_email,+)from lingua import LanguageDetectorBuilderfrom rest_framework import serializersfrom rest_framework.fields import empty@@ -47,7 +51,7 @@ class UserprofileSerializer(serializers.ModelSerializer):Workout session serializer"""- email = serializers.EmailField(source='user.email', read_only=True)+ email = serializers.EmailField(source='user.email', required=False)username = serializers.CharField(source='user.username', read_only=True)date_joined = serializers.DateTimeField(source='user.date_joined', read_only=True)email_verified = serializers.BooleanField(source='is_verified', read_only=True)@@ -88,6 +92,34 @@ class UserprofileSerializer(serializers.ModelSerializer):'num_days_weight_reminder',)+ def validate_email(self, value):+ if not value:+ return value+ user = self.context['request'].user++ # Re-submitting one's own email is fine+ if value.lower() == (user.email or '').lower():+ return value++ # Uniqueness across `User.email` and allauth's `EmailAddress` table+ if any(u.pk != user.pk for u in filter_users_by_email(value)):+ raise serializers.ValidationError('A user with this email already exists.')+ return value++ def update(self, instance, validated_data):+ new_email = validated_data.pop('user', {}).get('email')+ instance = super().update(instance, validated_data)++ user = instance.user+ if new_email and new_email.lower() != (user.email or '').lower():+ user_email(user, new_email)+ user.save()+ EmailAddress.objects.add_email(+ self.context['request'], user, new_email, confirm=True,+ )++ return instance+class UserLoginSerializer(serializers.ModelSerializer):"""Serializer to map to User model in relation to api user"""@@ -126,12 +158,7 @@ class UserLoginSerializer(serializers.ModelSerializer):class UserRegistrationSerializer(serializers.ModelSerializer):- email = serializers.EmailField(- required=False,- validators=[- UniqueValidator(queryset=User.objects.all()),- ],- )+ email = serializers.EmailField(required=False)username = serializers.CharField(required=True,validators=[UniqueValidator(queryset=User.objects.all())],@@ -142,6 +169,13 @@ class UserRegistrationSerializer(serializers.ModelSerializer):model = Userfields = ('username', 'email', 'password')+ def validate_email(self, value):+ # Case-insensitive uniqueness across both User.email and the allauth+ # EmailAddress table (which holds secondary addresses too)+ if value and filter_users_by_email(value):+ raise serializers.ValidationError('A user with this email already exists.')+ return value+def create(self, validated_data):user = User.objects.create(username=validated_data['username'])user.set_password(validated_data['password'])diff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex 11f45b77d..2ea1e469e 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -126,26 +126,10 @@ class UserProfileViewSet(viewsets.ModelViewSet):return self.list(request, *args, **kwargs)def create(self, request, *args, **kwargs):- data = request.data- serializer = self.serializer_class(request.user.userprofile, data=data)- if serializer.is_valid():- serializer.save()-- # New email, update the user and reset the email verification flag- if data.get('email') and request.user.email != data['email']:- request.user.email = data['email']- request.user.save()- request.user.userprofile.save()- # adds new email if it is not already registered- EmailAddress.objects.add_email(- request,- request.user,- request.user.email,- confirm=True,- )- logger.debug('adding new email with verified flag , send verification email')-- return Response(serializer.data)+ serializer = self.get_serializer(request.user.userprofile, data=request.data)+ serializer.is_valid(raise_exception=True)+ serializer.save()+ return Response(serializer.data)def update(self, request, *args, **kwargs):return self.create(request, *args, **kwargs)diff --git a/wger/core/forms.py b/wger/core/forms.pyindex a3116f38d..a06f52ddc 100644--- a/wger/core/forms.py+++ b/wger/core/forms.py@@ -39,6 +39,7 @@ from django.utils.translation import ()# Third Party+from allauth.account.utils import filter_users_by_emailfrom crispy_forms.helper import FormHelperfrom crispy_forms.layout import (HTML,@@ -216,26 +217,21 @@ class UserEmailForm(forms.ModelForm):def clean_email(self):"""- E-mail must be unique system-wide+ E-mail must be unique system-wide.- However, this check should only be performed when the user changes- e-mail address, otherwise the uniqueness check will because it will find one user- (the current one) using the same e-mail. Only when the user changes it, do- we want to check that nobody else has that e-mail address.+ Uniqueness is checked case-insensitively across both ``User.email``+ and allauth's ``EmailAddress`` table (which also tracks secondary,+ unverified addresses)"""email = self.cleaned_data['email']if not email:return email- try:- # Performs a case-insensitive lookup- user = User.objects.get(email__iexact=email)- if user.email == self.instance.email:- return email- except User.DoesNotExist:- return email- raise ValidationError(_('This e-mail address is already in use.'))+ own_pk = self.instance.pk if self.instance and self.instance.pk else None+ if any(u.pk != own_pk for u in filter_users_by_email(email)):+ raise ValidationError(_('This e-mail address is already in use.'))+ return emailclass UserPersonalInformationForm(UserEmailForm):diff --git a/wger/core/tests/test_registration.py b/wger/core/tests/test_registration.pyindex a03250b42..4002bdb66 100644--- a/wger/core/tests/test_registration.py+++ b/wger/core/tests/test_registration.py@@ -180,6 +180,36 @@ class RegistrationTestCase(WgerTestCase):self.assertFalse(response.context['form'].is_valid())self.user_logout()+ def test_register_rejects_secondary_email_address(self):+ """+ Uniqueness must also cover allauth's ``EmailAddress`` table —+ secondary addresses owned by another user must not be claimable+ through the HTML registration form either.+ """+ admin = User.objects.get(username='admin')+ EmailAddress.objects.create(+ user=admin,+ email='[email protected]',+ primary=False,+ verified=False,+ )++ registration_data = {+ 'username': 'newuser',+ 'password1': 'quai8fai7Zae',+ 'password2': 'quai8fai7Zae',+ 'email': '[email protected]',+ 'g-recaptcha-response': 'PASSED',+ }+ count_before = User.objects.count()+ response = self.client.post(reverse('core:user:registration'), registration_data)++ # A passing form would 302-redirect after creating the user; the+ # rejection path re-renders the page with the form context.+ self.assertEqual(response.status_code, 200)+ self.assertFalse(response.context['form'].is_valid())+ self.assertEqual(User.objects.count(), count_before)+@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')def test_registration_sends_verification_email(self):"""@@ -332,6 +362,48 @@ class ApiRegistrationTestCase(WgerTestCase):# Assertself.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)+ def test_post_unsuccessfully_registration_email_case_insensitive(self):+ """+ Email collisions must be detected case-insensitively — Django's+ password reset filters with ``email__iexact``, so registering+ ``[email protected]`` while ``[email protected]`` exists would+ still cause cross-account reset delivery.+ """+ response = self.client.post(+ reverse('api_register'),+ {+ 'username': 'restapi',+ 'email': '[email protected]',+ 'password': 'AekaiLe0ga',+ },+ )++ self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)++ def test_post_unsuccessfully_registration_email_in_emailaddress_table(self):+ """+ Uniqueness must also cover allauth's ``EmailAddress`` table —+ secondary addresses owned by another user must not be claimable.+ """+ admin = User.objects.get(username='admin')+ EmailAddress.objects.create(+ user=admin,+ email='[email protected]',+ primary=False,+ verified=False,+ )++ response = self.client.post(+ reverse('api_register'),+ {+ 'username': 'restapi',+ 'email': '[email protected]',+ 'password': 'AekaiLe0ga',+ },+ )++ self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)+def test_post_valid_data_registration_deactivated(self):"""When the registration is deactivated no users can be registered via the API"""diff --git a/wger/core/tests/test_verification.py b/wger/core/tests/test_verification.pyindex 4a5c6ff64..951cd4e05 100644--- a/wger/core/tests/test_verification.py+++ b/wger/core/tests/test_verification.py@@ -13,6 +13,7 @@# You should have received a copy of the GNU Affero General Public License# Standard Library+import jsonimport loggingimport re@@ -24,7 +25,10 @@ from django.urls import reverse# Third Partyfrom allauth.account.models import EmailAddress-from rest_framework.status import HTTP_200_OK+from rest_framework.status import (+ HTTP_200_OK,+ HTTP_400_BAD_REQUEST,+)# wgerfrom wger.core.tests.base_testcase import WgerTestCase@@ -187,3 +191,109 @@ class EmailVerificationFromAPITestCase(WgerTestCase):# No email was sentself.assertEqual(len(mail.outbox), 0)+++@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')+class UserProfileEmailUpdateTestCase(WgerTestCase):+ """+ Tests that updating the email address through the user profile API+ enforces format and uniqueness validation. Without it, an attacker+ could claim another user's email and poison password-reset delivery.+ """++ URL = '/api/v2/userprofile/'++ def _post(self, payload):+ return self.client.post(+ self.URL,+ data=json.dumps(payload),+ content_type='application/json',+ )++ def test_email_collision_is_rejected(self):+ """+ Claiming another user's email must fail with 400.+ """+ self.user_login('test')+ admin_email = User.objects.get(username='admin').email or '[email protected]'+ # Make sure admin has a known email so the collision is meaningful+ admin = User.objects.get(username='admin')+ admin.email = '[email protected]'+ admin.save()++ response = self._post({'email': '[email protected]'})+ self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)+ self.assertNotEqual(+ User.objects.get(username='test').email,+ '[email protected]',+ )++ def test_email_collision_case_insensitive(self):+ """+ Email comparison must be case-insensitive — Django's password reset+ already filters with ``email__iexact``.+ """+ self.user_login('test')+ admin = User.objects.get(username='admin')+ admin.email = '[email protected]'+ admin.save()++ response = self._post({'email': '[email protected]'})+ self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)++ def test_invalid_email_format_is_rejected(self):+ self.user_login('test')++ response = self._post({'email': 'not-an-email'})+ self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)+ self.assertNotEqual(+ User.objects.get(username='test').email,+ 'not-an-email',+ )++ def test_unique_email_is_accepted(self):+ """+ Sanity: a fresh, well-formed email passes validation and updates+ the user record.+ """+ self.user_login('test')++ response = self._post({'email': '[email protected]'})+ self.assertEqual(response.status_code, HTTP_200_OK)+ self.assertEqual(+ User.objects.get(username='test').email,+ '[email protected]',+ )++ def test_unchanged_email_is_accepted(self):+ """+ Re-posting one's own email must not trigger a uniqueness error.+ """+ self.user_login('test')+ own_email = User.objects.get(username='test').email++ response = self._post({'email': own_email})+ self.assertEqual(response.status_code, HTTP_200_OK)++ def test_collision_with_secondary_email_address_is_rejected(self):+ """+ Uniqueness must also cover the allauth ``EmailAddress`` table —+ i.e. addresses that another user has registered as a secondary+ (non-primary) address. Otherwise an attacker could claim such an+ address as their primary ``User.email``.+ """+ admin = User.objects.get(username='admin')+ EmailAddress.objects.create(+ user=admin,+ email='[email protected]',+ primary=False,+ verified=False,+ )++ self.user_login('test')+ response = self._post({'email': '[email protected]'})+ self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)+ self.assertNotEqual(+ User.objects.get(username='test').email,+ '[email protected]',+ )