Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add app-handoff endpoint
Roland Geiderbfbc35044860
diff --git a/wger/core/templates/user/app_auth_handoff.html b/wger/core/templates/user/app_auth_handoff.htmlnew file mode 100644index 000000000..fe7987d8a--- /dev/null+++ b/wger/core/templates/user/app_auth_handoff.html@@ -0,0 +1,27 @@+{% load i18n %}<!DOCTYPE html>+<html lang="{{ LANGUAGE_CODE|default:'en' }}">+<head>+ <meta charset="utf-8">+ <meta http-equiv="refresh" content="0;url={{ return_uri }}">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>{% translate "Return to app" %}</title>+ <style>+ body { font-family: sans-serif; max-width: 32rem; margin: 4rem auto; padding: 0 1rem; text-align: center; }+ a.btn { display: inline-block; padding: 0.75rem 1.5rem; background: #1976d2; color: #fff; text-decoration: none; border-radius: 4px; margin-top: 1rem; }+ </style>+</head>+<body>+ <p>{% translate "Returning to the wger app…" %}</p>+ <p>+ {% blocktranslate trimmed %}+ If nothing happens, tap the button below. Make sure the wger app+ is installed on this device.+ {% endblocktranslate %}+ </p>+ <p>+ <a class="btn" href="{{ return_uri }}">+ {% translate "Tap to return to app" %}+ </a>+ </p>+</body>+</html>diff --git a/wger/core/tests/test_app_auth_handoff.py b/wger/core/tests/test_app_auth_handoff.pynew file mode 100644index 000000000..7c7768409--- /dev/null+++ b/wger/core/tests/test_app_auth_handoff.py@@ -0,0 +1,61 @@+# 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+from urllib.parse import (+ parse_qs,+ urlparse,+)++# Django+from django.urls import reverse++# wger+from wger.core.tests.base_testcase import WgerTestCase+++class AppAuthHandoffTestCase(WgerTestCase):+ """+ Tests for the /user/app-auth/ web-handoff view that mints a long-lived+ refresh token and redirects to a custom URL scheme.+ """++ def test_anonymous_user_is_redirected_to_login(self):+ response = self.client.get(reverse('core:user:app-auth-handoff'))+ self.assertEqual(response.status_code, 302)+ self.assertIn('login', response['Location'])++ def test_authenticated_user_gets_redirect_page(self):+ self.user_login('test')+ response = self.client.get(reverse('core:user:app-auth-handoff'))+ self.assertEqual(response.status_code, 200)+ # Meta-refresh carries the custom-scheme URL.+ self.assertContains(response, 'http-equiv="refresh"')+ self.assertContains(response, 'wger://app-auth#token=')++ def test_token_is_in_fragment_not_query(self):+ self.user_login('test')+ response = self.client.get(reverse('core:user:app-auth-handoff'))+ content = response.content.decode()+ # Extract the return_uri from the meta-refresh content attribute.+ start = content.index('0;url=') + len('0;url=')+ end = content.index('"', start)+ return_uri = content[start:end]+ parsed = urlparse(return_uri)+ self.assertEqual(parsed.scheme, 'wger')+ # Fragment carries the token; query is empty.+ self.assertEqual(parsed.query, '')+ self.assertTrue(parsed.fragment.startswith('token='))+ self.assertGreater(len(parsed.fragment), len('token='))+diff --git a/wger/core/urls.py b/wger/core/urls.pyindex 4e63ebdce..d6ccbc250 100644--- a/wger/core/urls.py+++ b/wger/core/urls.py@@ -75,6 +75,7 @@ patterns_user = [path('registration', user.WgerSignupView.as_view(), name='registration'),path('preferences', user.preferences, name='preferences'),path('api-key', user.api_key, name='api-key'),+ path('app-auth/', user.app_auth_handoff, name='app-auth-handoff'),path('demo-entries', misc.demo_entries, name='demo-entries'),path('<int:pk>/activate', user.UserActivateView.as_view(), name='activate'),path('<int:pk>/deactivate', user.UserDeactivateView.as_view(), name='deactivate'),diff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex d92eb1bed..af2e2d8a2 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -16,6 +16,7 @@# Standard Libraryimport logging+from urllib.parse import quote# Djangofrom django.conf import settings@@ -118,6 +119,15 @@ from wger.weight.models import WeightEntrylogger = logging.getLogger(__name__)+# Session key used to carry a freshly minted refresh token across the+# post-redirect step on the api-key page. The token is shown once and then+# immediately popped.+_NEW_REFRESH_TOKEN_SESSION_KEY = '_wger_new_long_lived_refresh_token'+++# Custom URL scheme registered by the flutter app in Info.plist, AndroidManifest.xml, etc.+_APP_AUTH_SCHEME = 'wger'+@login_required()def delete(request, user_pk=None):"""@@ -518,10 +528,30 @@ def api_key(request):return render(request, 'user/api_key.html', context)-# Session key used to carry a freshly minted refresh token across the-# post-redirect step on the api-key page. The token is shown once and then-# immediately popped.-_NEW_REFRESH_TOKEN_SESSION_KEY = '_wger_new_long_lived_refresh_token'+@login_required+def app_auth_handoff(request):+ """+ Browser-side endpoint that mints a long-lived headless refresh token for+ the authenticated user and redirects to a custom URL scheme so the wger+ mobile app can pick it up.++ The user must already be authenticated; @login_required redirects through+ the normal allauth login flow first+ """+ token = mint_long_lived_refresh_token(+ request.user,+ settings.HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN,+ )++ # Token goes in the URL fragment, not the query string, so it never lands+ # in server access logs or referer headers. Refresh-token rotation is+ # the backstop against the one remaining leak surface (browser history).+ return_uri = f'{_APP_AUTH_SCHEME}://app-auth#token={quote(token, safe="")}'+ return render(+ request,+ 'user/app_auth_handoff.html',+ {'return_uri': return_uri},+ )class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, DetailView):