Self hosted FLOSS fitness/workout, nutrition and weight tracker
Properly check the validity of the "next" parameter in the login view
Roland Geiderbd825e255853
diff --git a/wger/core/tests/test_user_login.py b/wger/core/tests/test_user_login.pyindex e291e4143..2f5e9fe6f 100644--- a/wger/core/tests/test_user_login.py+++ b/wger/core/tests/test_user_login.py@@ -1,6 +1,9 @@# Standard Libraryfrom unittest import mock+# Django+from django.urls import reverse+# Third Partyfrom rest_framework import statusfrom rest_framework.exceptions import ErrorDetail@@ -81,6 +84,29 @@ class TrainerLoginTestCase(WgerTestCase):self.assertEqual(404, resp.status_code)+class WgerLoginViewRedirectTestCase(WgerTestCase):+ """+ Tests the "next" parameter handling when an already-authenticated user+ visits the login page+ """++ def test_already_logged_in_rejects_offsite_next(self):+ """An off-site "next" URL is ignored and the user lands on the dashboard"""+ self.user_login('admin')+ response = self.client.get(+ reverse('core:user:login'),+ {'next': 'https://attacker.example/phish'},+ )+ self.assertRedirects(response, reverse('core:dashboard'), fetch_redirect_response=False)++ def test_already_logged_in_allows_local_next(self):+ """A safe, same-host relative "next" URL is honoured"""+ self.user_login('admin')+ target = reverse('core:dashboard')+ response = self.client.get(reverse('core:user:login'), {'next': target})+ self.assertRedirects(response, target, fetch_redirect_response=False)++class UserApiLoginApiTestCase(BaseTestCase, ApiBaseTestCase):url = '/api/v2/login/'diff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex a405bc725..d9311dfea 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -714,7 +714,14 @@ class WgerLoginView(LoginView):def dispatch(self, request, *args, **kwargs):if request.user.is_authenticated and not request.user.userprofile.is_temporary:- return redirect(request.GET.get('next', reverse('core:dashboard')))+ next_url = request.GET.get('next')+ if next_url and url_has_allowed_host_and_scheme(+ next_url,+ allowed_hosts={request.get_host()},+ require_https=request.is_secure(),+ ):+ return redirect(next_url)+ return redirect(reverse('core:dashboard'))# Proceed with the normal login page logicreturn super().dispatch(request, *args, **kwargs)