Self hosted FLOSS fitness/workout, nutrition and weight tracker
Replace our own EmailAuthBackend with allauth's AuthenticationBackend
Roland Geidera9b96bf7d026
diff --git a/settings/settings_global.py b/settings/settings_global.pyindex d8102825a..87eed9bd1 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -169,7 +169,7 @@ AUTHENTICATION_BACKENDS = ('axes.backends.AxesStandaloneBackend', # should be the first one in the list'wger.core.backends.AuthProxyUserBackend','django.contrib.auth.backends.ModelBackend',- 'wger.utils.helpers.EmailAuthBackend',+ 'allauth.account.auth_backends.AuthenticationBackend',)TEMPLATES = [@@ -229,6 +229,10 @@ ACCOUNT_ADAPTER = 'wger.core.account_adapter.WgerAccountAdapter'# confirmed via the verification link.ACCOUNT_CHANGE_EMAIL = True+# Allow logging in with either the username or the email address. allauth's+# authentication backend resolves the email against its EmailAddress table.+ACCOUNT_LOGIN_METHODS = {'username', 'email'}+## Login#diff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex 9b60d120d..0fc15a509 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -301,9 +301,8 @@ class UserAPILoginView(viewsets.ViewSet):serializer = self.serializer_class(data=request.data, request=request)serializer.is_valid(raise_exception=True)- # This is a bit hacky, but saving the email or username as the username- # allows us to simply use the helpers.EmailAuthBackend backend which also- # uses emails+ # The login form's username field accepts either value: allauth's+ # authentication backend resolves it as a username or an email address.username = serializer.data.get('username', serializer.data.get('email', None))data = {'username': username, 'password': serializer.data['password']}form = UserLoginForm(data=data, authenticate_on_clean=False)diff --git a/wger/core/tests/base_testcase.py b/wger/core/tests/base_testcase.pyindex 28a5c18a3..fa27ce000 100644--- a/wger/core/tests/base_testcase.py+++ b/wger/core/tests/base_testcase.py@@ -517,7 +517,7 @@ class WgerAddTestCase(WgerTestCase):if self.user_fail:for user in get_user_list(self.user_fail):- self.user_login(self.user_fail)+ self.user_login(user)self.add_object(fail=True)diff --git a/wger/core/tests/test_auth_proxy_middleware.py b/wger/core/tests/test_auth_proxy_middleware.pyindex 6f9b27887..3be20fc22 100644--- a/wger/core/tests/test_auth_proxy_middleware.py+++ b/wger/core/tests/test_auth_proxy_middleware.py@@ -21,6 +21,9 @@ from django.test import ()from django.urls import reverse+# Third Party+from allauth.account.models import EmailAddress+User = get_user_model()@@ -106,6 +109,49 @@ class AuthProxyMiddlewareTests(TestCase):self.assertEqual(new_user.first_name, 'Admin User')self.assertEqual(int(self.client.session['_auth_user_id']), new_user.pk)+ @override_settings(+ AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],+ AUTH_PROXY_HEADER=PROXY_HEADER_KEY,+ AUTH_PROXY_CREATE_UNKNOWN_USER=True,+ AUTH_PROXY_USER_EMAIL_HEADER=PROXY_EMAIL_HEADER_KEY,+ AUTH_PROXY_USER_NAME_HEADER=PROXY_NAME_HEADER_KEY,+ WGER_SETTINGS={'ALLOW_GUEST_USERS': False},+ )+ def test_new_user_gets_verified_emailaddress(self):+ """+ A user auto-created by the trusted proxy gets a verified allauth+ EmailAddress row: the proxy is the trusted identity source, so login+ by email works without a separate confirmation step.+ """+ self.make_request(+ TRUSTED_IP,+ proxy_header_value=NEW_USER_VALUE,+ email_header_value='[email protected]',+ name_header_value='Admin User',+ )+ new_user = User.objects.get(username=NEW_USER_VALUE)+ email_address = EmailAddress.objects.get(user=new_user)+ self.assertEqual(email_address.email, '[email protected]')+ self.assertTrue(email_address.primary)+ self.assertTrue(email_address.verified)++ @override_settings(+ AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],+ AUTH_PROXY_HEADER=PROXY_HEADER_KEY,+ AUTH_PROXY_CREATE_UNKNOWN_USER=True,+ AUTH_PROXY_USER_NAME_HEADER=PROXY_NAME_HEADER_KEY,+ WGER_SETTINGS={'ALLOW_GUEST_USERS': False},+ )+ def test_new_user_without_email_gets_no_emailaddress(self):+ """A proxy user created without an email header gets no row and no crash."""+ self.make_request(+ TRUSTED_IP,+ proxy_header_value=NEW_USER_VALUE,+ name_header_value='Admin User',+ )+ new_user = User.objects.get(username=NEW_USER_VALUE)+ self.assertFalse(EmailAddress.objects.filter(user=new_user).exists())+@override_settings(AUTH_PROXY_HEADER=PROXY_HEADER_KEY,AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],diff --git a/wger/core/tests/test_user_login.py b/wger/core/tests/test_user_login.pyindex e291e4143..a98e43858 100644--- a/wger/core/tests/test_user_login.py+++ b/wger/core/tests/test_user_login.py@@ -142,3 +142,37 @@ class UserApiLoginApiTestCase(BaseTestCase, ApiBaseTestCase):result['non_field_errors'],[ErrorDetail(string='Please provide an "email" or a "username"', code='invalid')],)+++class JwtTokenEmailLoginTestCase(BaseTestCase, ApiBaseTestCase):+ """+ The SimpleJWT token endpoint forwards its credential as ``username``.+ allauth's authentication backend must resolve that value as an email+ address too, so a user can obtain a JWT with either identifier.+ """++ url = '/api/v2/token'++ def test_obtain_token_with_email(self):+ response = self.client.post(+ self.url,+ {'username': '[email protected]', 'password': 'adminadmin'},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIn('access', response.data)+ self.assertIn('refresh', response.data)++ def test_obtain_token_with_username(self):+ response = self.client.post(+ self.url,+ {'username': 'admin', 'password': 'adminadmin'},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIn('access', response.data)++ def test_obtain_token_with_email_wrong_password(self):+ response = self.client.post(+ self.url,+ {'username': '[email protected]', 'password': 'wrong-password'},+ )+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)diff --git a/wger/gym/tests/test_user.py b/wger/gym/tests/test_user.pyindex cf49f57f6..34c9ef4ab 100644--- a/wger/gym/tests/test_user.py+++ b/wger/gym/tests/test_user.py@@ -23,6 +23,9 @@ from django.contrib.auth.models import (from django.contrib.contenttypes.models import ContentTypefrom django.urls import reverse+# Third Party+from allauth.account.models import EmailAddress+# wgerfrom wger.core.models import UserProfilefrom wger.core.tests.base_testcase import WgerTestCase@@ -89,6 +92,18 @@ class GymAddUserTestCase(WgerTestCase):self.user_login('general_manager1')self.add_user()+ def test_add_user_registers_email_with_allauth(self):+ """+ A member created by an admin gets an allauth EmailAddress row, so they+ can log in by email and receive the confirmation link.+ """+ self.user_login('admin')+ self.add_user()+ new_user = User.objects.get(pk=self.client.session['gym.user']['user_pk'])+ email_address = EmailAddress.objects.get(user=new_user)+ self.assertEqual(email_address.email, '[email protected]')+ self.assertFalse(email_address.verified)+def test_add_user_unauthorized(self):"""Tests adding a user an unauthorized userdiff --git a/wger/utils/helpers.py b/wger/utils/helpers.pyindex 0e53c28f9..a38cead56 100644--- a/wger/utils/helpers.py+++ b/wger/utils/helpers.py@@ -28,7 +28,6 @@ from 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@@ -44,34 +43,6 @@ from wger.utils.images import validate_image_static_no_animationlogger = logging.getLogger(__name__)-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-- # 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):"""Custom JSON encoder.diff --git a/wger/utils/tests/test_helpers.py b/wger/utils/tests/test_helpers.pyindex 76e93e7a1..b8c65cf2f 100644--- a/wger/utils/tests/test_helpers.py+++ b/wger/utils/tests/test_helpers.py@@ -17,69 +17,10 @@ import secretsfrom unittest import mock# Django-from django.contrib.auth.models import Userfrom 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'))+from wger.utils.helpers import password_generatorclass PasswordGeneratorTestCase(SimpleTestCase):