Self hosted FLOSS fitness/workout, nutrition and weight tracker
Activate the user's timezone for token-authenticated requests
Roland Geider635323ace990
diff --git a/settings/settings_global.py b/settings/settings_global.pyindex c5daf046b..5211bb495 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -495,14 +495,16 @@ REST_FRAMEWORK = {# JSON only, endpoints taking a file set MultiPartParser themselves.'DEFAULT_PARSER_CLASSES': ('rest_framework.parsers.JSONParser',),'DEFAULT_AUTHENTICATION_CLASSES': (+ # The token-based classes activate the user's timezone, which the+ # middleware only manages for session requests; see timezone_auth'rest_framework.authentication.SessionAuthentication',- 'rest_framework.authentication.TokenAuthentication',+ 'wger.utils.timezone_auth.TimezoneTokenAuthentication','wger.utils.headless_auth.HeadlessJWTAuthentication',# Also uses Bearer, but with opaque tokens, so it has to run before# simplejwt, which raises instead of passing the token on. Placed after# the headless class so app requests don't pay for the token lookup.'wger.utils.oidc_auth.OidcTokenAuthentication',- 'rest_framework_simplejwt.authentication.JWTAuthentication',+ 'wger.utils.timezone_auth.TimezoneJWTAuthentication',),'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',diff --git a/wger/core/tests/test_api_timezone.py b/wger/core/tests/test_api_timezone.pynew file mode 100644index 000000000..7aca25d84--- /dev/null+++ b/wger/core/tests/test_api_timezone.py@@ -0,0 +1,76 @@+# 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 datetime+import zoneinfo++# Django+from django.contrib.auth.models import User+from django.urls import reverse++# Third Party+from rest_framework import status+from rest_framework.authtoken.models import Token++# wger+from wger.core.tests.base_testcase import WgerTestCase+from wger.manager.models import WorkoutSession+++class ApiTimezoneActivationTestCase(WgerTestCase):+ """+ Token-authenticated requests run in the requester's profile timezone++ The middleware only sees the session user, so the token classes activate+ the zone themselves once DRF has resolved the credentials; a date filter+ answers the same whichever way the caller logged in.+ """++ def setUp(self):+ super().setUp()+ self.user = User.objects.get(username='test')+ self.token, _ = Token.objects.get_or_create(user=self.user)++ def get(self, url, params):+ return self.client.get(url, params, HTTP_AUTHORIZATION=f'Token {self.token.key}')++ def test_date_filter_resolves_in_the_profile_zone(self):+ profile = self.user.userprofile+ profile.time_zone = 'Pacific/Auckland'+ profile.save()++ session = WorkoutSession.objects.create(+ user=self.user,+ routine_id=3,+ datetime_start=datetime.datetime(+ 2025, 3, 12, 7, 0, tzinfo=zoneinfo.ZoneInfo('Pacific/Auckland')+ ),+ )++ response = self.get(+ reverse('workoutsession-list'),+ {'datetime_start__date': '2025-03-12'},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ ids = [entry['id'] for entry in response.json()['results']]+ self.assertIn(str(session.id), ids)++ def test_a_token_outliving_the_profile_still_authenticates(self):+ self.user.userprofile.delete()++ response = self.get(reverse('workoutsession-list'), {})++ self.assertEqual(response.status_code, status.HTTP_200_OK)diff --git a/wger/utils/headless_auth.py b/wger/utils/headless_auth.pyindex 4070f97e1..e1f304f04 100644--- a/wger/utils/headless_auth.py+++ b/wger/utils/headless_auth.py@@ -25,6 +25,9 @@ from allauth.headless.tokens.strategies.jwt.strategy import JWTTokenStrategyfrom drf_spectacular.extensions import OpenApiAuthenticationExtensionfrom rest_framework.exceptions import AuthenticationFailed+# wger+from wger.utils.timezone_auth import activate_user_timezone+class HeadlessJWTAuthentication(JWTTokenAuthentication):"""@@ -38,9 +41,12 @@ class HeadlessJWTAuthentication(JWTTokenAuthentication):def authenticate(self, request):try:- return super().authenticate(request)+ result = super().authenticate(request)except AuthenticationFailed:return None+ if result is not None:+ activate_user_timezone(result[0])+ return resultdef authenticate_credentials(self, key):user, payload = super().authenticate_credentials(key)diff --git a/wger/utils/oidc_auth.py b/wger/utils/oidc_auth.pyindex 4905872b8..7ca54eb74 100644--- a/wger/utils/oidc_auth.py+++ b/wger/utils/oidc_auth.py@@ -30,6 +30,7 @@ from rest_framework.exceptions import PermissionDeniedfrom rest_framework.permissions import SAFE_METHODS# wger+from wger.utils.timezone_auth import activate_user_timezonefrom wger.utils.url import make_absolute_url@@ -92,6 +93,7 @@ class OidcTokenAuthentication(TokenAuthentication):code='insufficient_scope',)+ activate_user_timezone(user)return user, tokendiff --git a/wger/utils/timezone_auth.py b/wger/utils/timezone_auth.pynew file mode 100644index 000000000..a71b14f98--- /dev/null+++ b/wger/utils/timezone_auth.py@@ -0,0 +1,66 @@+# 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.core.exceptions import ObjectDoesNotExist+from django.utils import timezone++# Third Party+from drf_spectacular.contrib.rest_framework_simplejwt import SimpleJWTScheme+from rest_framework.authentication import TokenAuthentication+from rest_framework_simplejwt.authentication import JWTAuthentication+++def activate_user_timezone(user) -> None:+ """+ Activates the user's timezone for the rest of the request++ TimezoneMiddleware runs before DRF resolves token credentials and only+ sees the session user, so a token-authenticated request would otherwise+ run in the instance zone: the same date filter would answer differently+ depending on how the caller logged in.+ """+ # Best effort, rendering comfort must never break authentication: a JWT+ # can outlive its user's profile+ try:+ timezone.activate(user.userprofile.zone_info)+ except ObjectDoesNotExist:+ timezone.deactivate()+++class TimezoneActivationMixin:+ """Activates the authenticated user's timezone, see activate_user_timezone"""++ def authenticate(self, request):+ result = super().authenticate(request)+ if result is not None:+ activate_user_timezone(result[0])+ return result+++class TimezoneTokenAuthentication(TimezoneActivationMixin, TokenAuthentication):+ pass+++class TimezoneJWTAuthentication(TimezoneActivationMixin, JWTAuthentication):+ pass+++class TimezoneJWTScheme(SimpleJWTScheme):+ """+ Keeps the jwtAuth entry in the schema: the simplejwt extension targets the+ original class and does not match subclasses+ """++ target_class = 'wger.utils.timezone_auth.TimezoneJWTAuthentication'