Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add endpoint to issue refresh tokens over the API
Roland Geider45a02e4929ba
diff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex 823eb2174..84b61f8e6 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -77,6 +77,7 @@ from wger.core.models import (UserProfile,WeightUnit,)+from wger.utils.headless_long_lived import mint_long_lived_refresh_tokenfrom wger.utils.permissions import WgerPermissionfrom wger.utils.powersync import REGISTRY as POWERSYNC_REGISTRYfrom wger.version import (@@ -328,6 +329,24 @@ def check_language(request):return Response({'result': True})+@api_view(['POST'])+@permission_classes([IsAuthenticated])+def issue_refresh_token(request):+ """+ Temporary endpoint for issuing refresh tokens for authenticated users.++ This endpoint is used to allow users of the mobile app to seamlessly move from+ permanent tokens to JWT ones.++ TODO: remove one version after the iniial offline-mode release+ """+ refresh_token = mint_long_lived_refresh_token(+ request.user,+ settings.HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN,+ )+ return Response({'refresh_token': refresh_token})++@api_view()@permission_classes([IsAuthenticated])def get_powersync_token(request):diff --git a/wger/core/tests/api/test_issue_refresh_token.py b/wger/core/tests/api/test_issue_refresh_token.pynew file mode 100644index 000000000..ede4b0c54--- /dev/null+++ b/wger/core/tests/api/test_issue_refresh_token.py@@ -0,0 +1,123 @@+# 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+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# Django+from django.contrib.auth.models import User+from django.contrib.sessions.models import Session++# Third Party+from rest_framework.authtoken.models import Token+from rest_framework.test import APIClient++# wger+from wger.core.tests.base_testcase import WgerTestCase+from wger.utils.headless_long_lived import LONG_LIVED_FLAG+++class IssueRefreshTokenApiTestCase(WgerTestCase):+ """+ Tests the ``/api/v2/issue-refresh-token`` endpoint that lets clients holding+ a legacy DRF API token migrate to the headless JWT auth surface without+ re-prompting the user for credentials.+ """++ url = '/api/v2/issue-refresh-token'++ def test_drf_token_mints_a_usable_refresh_token(self):+ """+ Happy path: POST with ``Authorization: Token <key>`` returns a+ refresh token that the existing ``/tokens/refresh`` endpoint+ accepts and exchanges for a full access bundle. This is the exact+ round-trip the Flutter migration flow runs on first launch.+ """+ user = User.objects.get(username='test')+ legacy_token, _ = Token.objects.get_or_create(user=user)++ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f'Token {legacy_token.key}')+ mint_response = client.post(self.url)++ self.assertEqual(mint_response.status_code, 200)+ refresh_token = mint_response.json().get('refresh_token')+ self.assertIsInstance(refresh_token, str)+ self.assertTrue(refresh_token)++ # The minted refresh token has to round-trip through the existing+ # exchange endpoint without us having to know its internal shape.+ anon = APIClient()+ exchange = anon.post(+ '/_allauth/app/v1/tokens/refresh',+ data={'refresh_token': refresh_token},+ format='json',+ )+ self.assertEqual(exchange.status_code, 200)+ body = exchange.json()+ self.assertIn('access_token', body['data'])++ def test_session_is_tagged_as_long_lived(self):+ """+ The minted refresh token is backed by a dedicated session row with+ the long-lived flag set, so the user can see and revoke it from+ the "API sessions" list on the api-key page later. Without this+ marker the row would look like a regular browser session.+ """+ user = User.objects.get(username='test')+ legacy_token, _ = Token.objects.get_or_create(user=user)++ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f'Token {legacy_token.key}')+ response = client.post(self.url)+ self.assertEqual(response.status_code, 200)++ long_lived = [s for s in Session.objects.all() if s.get_decoded().get(LONG_LIVED_FLAG)]+ self.assertEqual(len(long_lived), 1)++ def test_unauthenticated_request_is_rejected(self):+ """+ No credentials means no refresh token. The endpoint must not leak+ information about whether a user exists; a 401/403 is enough.+ """+ response = APIClient().post(self.url)+ self.assertIn(response.status_code, (401, 403))++ def test_invalid_drf_token_is_rejected(self):+ """+ A garbage DRF token must not mint a refresh token. The+ ``IsAuthenticated`` permission catches this because the auth+ chain finds no matching ``Token`` row.+ """+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION='Token not-a-real-token-key')+ response = client.post(self.url)+ self.assertIn(response.status_code, (401, 403))++ def test_get_is_not_allowed(self):+ """+ Token minting is a state-changing action — a GET request must not+ be routed to the view. Matches the same defence the web+ ``api-key`` view has against attacker-embedded links / images that+ could otherwise rotate tokens silently.+ """+ user = User.objects.get(username='test')+ legacy_token, _ = Token.objects.get_or_create(user=user)++ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f'Token {legacy_token.key}')+ response = client.get(self.url)++ self.assertEqual(response.status_code, 405)+ # No long-lived session must have been created for this user.+ long_lived = [s for s in Session.objects.all() if s.get_decoded().get(LONG_LIVED_FLAG)]+ self.assertEqual(long_lived, [])diff --git a/wger/urls.py b/wger/urls.pyindex f52e21d0a..b1832b7e8 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -310,6 +310,11 @@ urlpatterns += [path('api/v2/', include(router.urls)),path('api/v2/token/refresh', TokenRefreshView.as_view(), name='token_refresh'),path('api/v2/token/verify', TokenVerifyView.as_view(), name='token_verify'),+ path(+ 'api/v2/issue-refresh-token',+ core_api_views.issue_refresh_token,+ name='issue_refresh_token',+ ),# Otherspath('api/v2/version/',