Self hosted FLOSS fitness/workout, nutrition and weight tracker
Improve handling of emails in our auth backend
Roland Geider407a0aab0cb2
diff --git a/wger/utils/helpers.py b/wger/utils/helpers.pyindex ecc6f5bd3..0e53c28f9 100644--- a/wger/utils/helpers.py+++ b/wger/utils/helpers.py@@ -20,14 +20,15 @@ import decimalimport jsonimport loggingimport os-import randomimport re+import secretsimport stringfrom decimal import Decimalfrom functools import wrapsfrom typing import Any# Django+from django.contrib.auth.backends import ModelBackendfrom django.contrib.auth.models import Userfrom django.core.files import Filefrom django.core.files.temp import NamedTemporaryFile@@ -43,22 +44,33 @@ from wger.utils.images import validate_image_static_no_animationlogger = logging.getLogger(__name__)-class EmailAuthBackend:- def authenticate(self, request, username=None, password=None):- try:- user = User.objects.get(email=username)- if user.check_password(password):- return user- return None- except User.DoesNotExist:+class EmailAuthBackend(ModelBackend):+ """+ Authenticates against the email address instead of the username.++ Subclasses ModelBackend so the is_active check (user_can_authenticate) and+ the timing-attack mitigation are inherited rather than reimplemented;+ get_user (which also rejects inactive users) comes for free.+ """++ def authenticate(self, request, username=None, password=None, **kwargs):+ if not username or password is None:return None- def get_user(self, user_id):- try:- return User.objects.get(pk=user_id)- except User.DoesNotExist:+ # email has no DB-level unique constraint, so the lookup can match+ # more than one row. Treat an ambiguous match as a failed login+ # instead of raising MultipleObjectsReturned+ users = list(User.objects.filter(email__iexact=username)[:2])+ if len(users) != 1:+ # Run the hasher once anyway to keep the timing close to a real hit+ User().set_password(password)return None+ user = users[0]+ if user.check_password(password) and self.user_can_authenticate(user):+ return user+ return None+class DecimalJsonEncoder(json.JSONEncoder):"""@@ -110,11 +122,10 @@ def password_generator(length=15)::return: the generated password"""chars = string.ascii_letters + string.digits- random.seed = os.urandom(1024)for char in ('I', '1', 'l', 'O', '0', 'o'):chars = chars.replace(char, '')- return ''.join(random.choice(chars) for i in range(length))+ return ''.join(secrets.choice(chars) for _ in range(length))def check_access(request_user, username=None):@@ -172,7 +183,7 @@ def random_string(length=32):"""Generates a random string"""- return ''.join(random.choice(string.ascii_uppercase) for i in range(length))+ return ''.join(secrets.choice(string.ascii_uppercase) for _ in range(length))class BaseImageMixin:diff --git a/wger/utils/tests/test_helpers.py b/wger/utils/tests/test_helpers.pynew file mode 100644index 000000000..76e93e7a1--- /dev/null+++ b/wger/utils/tests/test_helpers.py@@ -0,0 +1,99 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Standard Library+import secrets+from unittest import mock++# Django+from django.contrib.auth.models import User+from django.test import SimpleTestCase++# wger+from wger.core.tests.base_testcase import WgerTestCase+from wger.utils.helpers import (+ EmailAuthBackend,+ password_generator,+)+++class EmailAuthBackendTestCase(WgerTestCase):+ """+ Tests the email-based authentication backend+ """++ def setUp(self):+ super().setUp()+ self.backend = EmailAuthBackend()++ def test_authenticates_with_correct_email_and_password(self):+ user = User.objects.create_user('alice', '[email protected]', 'secret-pw')+ self.assertEqual(+ self.backend.authenticate(None, username='[email protected]', password='secret-pw'),+ user,+ )++ def test_email_match_is_case_insensitive(self):+ """Login must work regardless of the casing of the stored email address."""+ user = User.objects.create_user('bob', '[email protected]', 'secret-pw')+ self.assertEqual(+ self.backend.authenticate(None, username='[email protected]', password='secret-pw'),+ user,+ )++ def test_wrong_password_is_rejected(self):+ User.objects.create_user('carol', '[email protected]', 'secret-pw')+ self.assertIsNone(+ self.backend.authenticate(None, username='[email protected]', password='wrong-pw')+ )++ def test_inactive_user_is_rejected(self):+ """A deactivated account must not be able to log in via its email address."""+ user = User.objects.create_user('dave', '[email protected]', 'secret-pw')+ user.is_active = False+ user.save()+ self.assertIsNone(+ self.backend.authenticate(None, username='[email protected]', password='secret-pw')+ )++ def test_duplicate_email_does_not_raise(self):+ """email is not unique at the DB level — an ambiguous match must fail cleanly."""+ User.objects.create_user('eve1', '[email protected]', 'secret-pw')+ User.objects.create_user('eve2', '[email protected]', 'secret-pw')+ self.assertIsNone(+ self.backend.authenticate(None, username='[email protected]', password='secret-pw')+ )++ def test_blank_username_does_not_match_emailless_users(self):+ """Guest users have an empty email — a blank login must not match them."""+ User.objects.create_user('frank', '', 'secret-pw')+ self.assertIsNone(self.backend.authenticate(None, username='', password='secret-pw'))+ self.assertIsNone(self.backend.authenticate(None, username=None, password='secret-pw'))+++class PasswordGeneratorTestCase(SimpleTestCase):+ """+ Tests the password generator+ """++ def test_uses_cryptographically_secure_choice(self):+ """Generated passwords must come from the secrets CSPRNG, not the random module."""+ with mock.patch('secrets.choice', wraps=secrets.choice) as mock_choice:+ password_generator()+ mock_choice.assert_called()++ def test_respects_length_and_excludes_ambiguous_chars(self):+ password = password_generator(20)+ self.assertEqual(len(password), 20)+ self.assertFalse(set(password) & set('I1lO0o'))