Self hosted FLOSS fitness/workout, nutrition and weight tracker
Enable login redirection and improve authentication handling
Roland Geider3413420c2be9
diff --git a/wger/core/middleware.py b/wger/core/middleware.pyindex c3b51d2ca..84e3f107d 100644--- a/wger/core/middleware.py+++ b/wger/core/middleware.py@@ -23,8 +23,12 @@ from django.contrib.auth import (login,logout,)+from django.urls import reversefrom django.utils.deprecation import MiddlewareMixin+# wger+from wger.utils.helpers import remove_language_code+logger = logging.getLogger(__name__)User = get_user_model()@@ -38,6 +42,10 @@ class AuthProxyHeaderMiddleware(MiddlewareMixin):- AUTH_PROXY_TRUSTED_IPS: List of IPs allowed to set the header."""+ def __init__(self, get_response=None):+ super().__init__(get_response)+ self.login_url_path = remove_language_code(reverse('core:user:login'))+def process_request(self, request):header_key = getattr(settings, 'AUTH_PROXY_HEADER', None)trusted_ips = set(getattr(settings, 'AUTH_PROXY_TRUSTED_IPS', []))@@ -49,6 +57,12 @@ class AuthProxyHeaderMiddleware(MiddlewareMixin):# )return None+ # Only handle requests to the login page.+ # Here the user will be logged in using the proxy headers and redirected to the original page.+ if remove_language_code(request.path_info) != self.login_url_path:+ # logger.debug(f'AuthProxyMiddleware: not request to login page. Skipping.')+ return None+# Get the client IP address.# Use REMOTE_ADDR as it's the direct connection IP (should be the proxy).client_ip = request.META.get('REMOTE_ADDR')@@ -78,7 +92,6 @@ class AuthProxyHeaderMiddleware(MiddlewareMixin):# If user is already authenticated and matches the header, do nothing.if request.user.is_authenticated:-if request.user.get_username() == username:return Nonediff --git a/wger/core/tests/test_auth_proxy_middleware.py b/wger/core/tests/test_auth_proxy_middleware.pyindex 2ee8a2088..b54719d08 100644--- a/wger/core/tests/test_auth_proxy_middleware.py+++ b/wger/core/tests/test_auth_proxy_middleware.py@@ -45,9 +45,7 @@ class AuthProxyMiddlewareTests(TestCase):password='password123',)self.protected_url = reverse('core:dashboard')-- self.login_url = reverse('core:user:login')[3:]- """Login URL without the /en/ part"""+ self.login_url = reverse('core:user:login')# Helper to make requests with specific IP and headerdef make_request(self, ip_addr, header_value=None):@@ -55,20 +53,19 @@ class AuthProxyMiddlewareTests(TestCase):if header_value:headers[PROXY_HEADER_KEY] = header_value- # Use REMOTE_ADDR to spoof the IP- self.client.get(self.protected_url, REMOTE_ADDR=ip_addr, **headers)- return self.client.get(self.protected_url)+ return self.client.get(self.protected_url, REMOTE_ADDR=ip_addr, follow=True, **headers)@override_settings(AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],AUTH_PROXY_HEADER=PROXY_HEADER_KEY,+ WGER_SETTINGS={'ALLOW_GUEST_USERS': False},)def test_success_trusted_ip_existing_user(self):response = self.make_request(TRUSTED_IP, USERNAME)self.assertEqual(response.status_code, 200)# Check if the correct user is logged into the session- self.assertEqual(int(self.client.session['_auth_user_id']), self.existing_user.pk)+ self.assertEqual(int(self.client.session.get('_auth_user_id', 0)), self.existing_user.pk)@override_settings(AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],@@ -88,43 +85,42 @@ class AuthProxyMiddlewareTests(TestCase):@override_settings(AUTH_PROXY_HEADER=PROXY_HEADER_KEY,AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],- WGER_SETTINGS={'ALLOW_GUEST_USERS': False}+ WGER_SETTINGS={'ALLOW_GUEST_USERS': False},)def test_failure_untrusted_ip_header_present(self):"""Should redirect to login because the middleware shouldn't authenticate"""-response = self.make_request(UNTRUSTED_IP, USERNAME)- self.assertEqual(response.status_code, 302)- self.assertTrue(response.url.startswith(self.login_url))+ self.assertEqual(response.status_code, 200)+ self.assertTrue(response.request['PATH_INFO'].startswith(self.login_url))self.assertNotIn('_auth_user_id', self.client.session)@override_settings(AUTH_PROXY_HEADER=PROXY_HEADER_KEY,AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],- WGER_SETTINGS={'ALLOW_GUEST_USERS': False}+ WGER_SETTINGS={'ALLOW_GUEST_USERS': False},)def test_failure_trusted_ip_header_missing(self):"""Should redirect to login"""response = self.make_request(TRUSTED_IP, header_value=None)- self.assertEqual(response.status_code, 302)- self.assertTrue(response.url.startswith(self.login_url))+ self.assertEqual(response.status_code, 200)+ self.assertTrue(response.request['PATH_INFO'].startswith(self.login_url))self.assertNotIn('_auth_user_id', self.client.session)@override_settings(AUTH_PROXY_HEADER=PROXY_HEADER_KEY,AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],AUTH_PROXY_CREATE_UNKNOWN_USER=False,- WGER_SETTINGS={'ALLOW_GUEST_USERS': False}+ WGER_SETTINGS={'ALLOW_GUEST_USERS': False},)def test_failure_trusted_ip_new_user_creation_disabled(self):self.assertFalse(User.objects.filter(username=NEW_USER_VALUE).exists())response = self.make_request(TRUSTED_IP, NEW_USER_VALUE)# Should redirect to login- self.assertEqual(response.status_code, 302)- self.assertTrue(response.url.startswith(self.login_url))+ self.assertEqual(response.status_code, 200)+ self.assertTrue(response.request['PATH_INFO'].startswith(self.login_url))# Verify user was NOT createdself.assertFalse(User.objects.filter(username=NEW_USER_VALUE).exists())@@ -133,17 +129,17 @@ class AuthProxyMiddlewareTests(TestCase):@override_settings(AUTH_PROXY_TRUSTED_IPS=[TRUSTED_IP],AUTH_PROXY_HEADER='HTTP_X_DIFFERENT_USER',- WGER_SETTINGS={'ALLOW_GUEST_USERS': False}+ WGER_SETTINGS={'ALLOW_GUEST_USERS': False},)def test_alternate_header_name(self):# Request using the *correctly* configured header name- self.client.get(+ response = self.client.get(self.protected_url,REMOTE_ADDR=TRUSTED_IP,HTTP_X_DIFFERENT_USER=USERNAME,+ follow=True,)- response_correct = self.client.get(self.protected_url)- self.assertEqual(response_correct.status_code, 200)+ self.assertEqual(response.status_code, 200)self.assertEqual(int(self.client.session['_auth_user_id']), self.existing_user.pk)# Clear session before next request@@ -154,8 +150,9 @@ class AuthProxyMiddlewareTests(TestCase):self.protected_url,REMOTE_ADDR=TRUSTED_IP,HTTP_X_REMOTE_USER=USERNAME,+ follow=True,)- response_wrong2 = self.client.get(self.protected_url)- self.assertEqual(response_wrong1.status_code, 302)- self.assertEqual(response_wrong2.status_code, 302)+ response_wrong2 = self.client.get(self.protected_url, follow=True)+ self.assertEqual(response_wrong1.status_code, 200)+ self.assertEqual(response_wrong2.status_code, 200)self.assertNotIn('_auth_user_id', self.client.session)diff --git a/wger/core/urls.py b/wger/core/urls.pyindex 65dc5faca..5f7b67c8a 100644--- a/wger/core/urls.py+++ b/wger/core/urls.py@@ -34,7 +34,6 @@ from wger.core.views import (weight_units,)-# sub patterns for languagespatterns_language = [path(@@ -68,7 +67,10 @@ patterns_language = [patterns_user = [path('login',- views.LoginView.as_view(template_name='user/login.html', authentication_form=UserLoginForm),+ user.WgerLoginView.as_view(+ template_name='user/login.html',+ authentication_form=UserLoginForm,+ ),name='login',),path('logout', user.logout, name='logout'),diff --git a/wger/core/views/react.py b/wger/core/views/react.pyindex 10bf7e575..91d1e452e 100644--- a/wger/core/views/react.py+++ b/wger/core/views/react.py@@ -13,7 +13,7 @@# You should have received a copy of the GNU Affero General Public License# Django-from django.http import HttpResponseForbidden+from django.contrib.auth.views import redirect_to_loginfrom django.views.generic import TemplateView@@ -39,6 +39,6 @@ class ReactView(TemplateView):Only logged-in users are allowed to access this page"""if self.login_required and not request.user.is_authenticated:- return HttpResponseForbidden('You are not allowed to access this page')+ return redirect_to_login(request.path)return super().dispatch(request, *args, **kwargs)diff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex 67f943873..9a253fb2d 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -17,6 +17,15 @@# Standard Libraryimport logging+# Third Party+from crispy_forms.helper import FormHelper+from crispy_forms.layout import (+ ButtonHolder,+ Column,+ Layout,+ Row,+ Submit,+)# Djangofrom django.conf import settingsfrom django.contrib import messages@@ -44,6 +53,7 @@ from django.http import ()from django.shortcuts import (get_object_or_404,+ redirect,render,)from django.template.context_processors import csrf@@ -62,16 +72,6 @@ from django.views.generic import (RedirectView,UpdateView,)--# Third Party-from crispy_forms.helper import FormHelper-from crispy_forms.layout import (- ButtonHolder,- Column,- Layout,- Row,- Submit,-)from django_email_verification import send_emailfrom rest_framework.authtoken.models import Token@@ -81,7 +81,6 @@ from wger.core.forms import (PasswordConfirmationForm,RegistrationForm,RegistrationFormNoCaptcha,- UserLoginForm,UserPersonalInformationForm,UserPreferencesForm,)@@ -104,7 +103,6 @@ from wger.utils.generic_views import (from wger.utils.language import load_languagefrom wger.weight.models import WeightEntry-logger = logging.getLogger(__name__)@@ -536,8 +534,8 @@ class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, De)context['routine_data'] = outcontext['weight_entries'] = WeightEntry.objects.filter(user=self.object).order_by('-date')[- :5- ]+ :5+ ]context['nutrition_plans'] = NutritionPlan.objects.filter(user=self.object).order_by('-creation_date')[:5]@@ -648,3 +646,18 @@ def confirm_email(request):)return HttpResponseRedirect(reverse('core:dashboard'))+++class WgerLoginView(LoginView):+ """+ If the user is already logged in and there's a "next" parameter in the URL,+ redirect there. Otherwise, proceed with the normal login logic from Django+ """++ def dispatch(self, request, *args, **kwargs):+ next_url = request.GET.get('next', reverse('core:dashboard'))+ if request.user.is_authenticated:+ return redirect(next_url)++ # Proceed with the normal login page logic+ return super().dispatch(request, *args, **kwargs)diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex 828a2ab80..ba6b2f874 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -30,7 +30,6 @@ from wger.nutrition.views import (unit_ingredient,)-# sub patterns for nutritional planspatterns_plan = [path(@@ -136,7 +135,7 @@ patterns_unit_ingredient = [patterns_bmi = [path('',- ReactView.as_view(),+ ReactView.as_view(login_required=True),name='view',),]diff --git a/wger/utils/helpers.py b/wger/utils/helpers.pyindex a0e9e99e3..32ec86227 100644--- a/wger/utils/helpers.py+++ b/wger/utils/helpers.py@@ -21,6 +21,7 @@ import jsonimport loggingimport osimport random+import reimport stringfrom decimal import Decimalfrom functools import wraps@@ -34,7 +35,6 @@ from django.shortcuts import get_object_or_404from django.utils.encoding import force_bytesfrom django.utils.http import urlsafe_base64_encode-logger = logging.getLogger(__name__)@@ -192,3 +192,12 @@ class BaseImage:if not generate_uuid:image.uuid = json_data['uuid']return image+++def remove_language_code(path):+ """+ Removes optional language code at the start of a path+ """++ pattern = r'^/[a-z]{2}(?=/)'+ return re.sub(pattern, '', path)diff --git a/wger/utils/tests/test_remove_language_code.py b/wger/utils/tests/test_remove_language_code.pynew file mode 100644index 000000000..95715fa26--- /dev/null+++ b/wger/utils/tests/test_remove_language_code.py@@ -0,0 +1,33 @@+# 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++# Django+from django.test import TestCase++# wger+from wger.utils.helpers import remove_language_code+++class TestRemoveLanguageCode(TestCase):+ def test_remove_code(self):+ self.assertEqual(+ remove_language_code('/de/some/url/'),+ '/some/url/',+ )++ def test_no_language(self):+ self.assertEqual(+ remove_language_code('/api/v2/endpoint'),+ '/api/v2/endpoint',+ )