Self hosted FLOSS fitness/workout, nutrition and weight tracker
Allow users to manually generate JWT tokens
Roland Geidera21223a8077e
diff --git a/settings/main.py b/settings/main.pyindex 09a261ff0..dad42d30b 100644--- a/settings/main.py+++ b/settings/main.py@@ -293,6 +293,10 @@ SIMPLE_JWT['SIGNING_KEY'] = _SIGNING_KEY# allauth.headless JWT signs with the same secret during the sunset window# where both surfaces coexist. HS256 is configured in settings_global.py.HEADLESS_JWT_PRIVATE_KEY = _SIGNING_KEY+# Refresh-token lifetime in seconds. Mirrors the legacy REFRESH_TOKEN_LIFETIME+# env var (hours) used for SimpleJWT, so the long-lived-refresh-token page on+# the web matches the rest of the headless surface.+HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN = env.int('REFRESH_TOKEN_LIFETIME', 24 * 30 * 4) * 3600## https://docs.djangoproject.com/en/4.1/ref/csrf/diff --git a/settings/settings_global.py b/settings/settings_global.pyindex 481c58c65..85bd585e9 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -271,7 +271,6 @@ MFA_PASSKEY_LOGIN_ENABLED = TrueMFA_PASSKEY_SIGNUP_ENABLED = False#-<<<<<<< HEAD# Social account providers#SOCIALACCOUNT_PROVIDERS = {@@ -289,7 +288,8 @@ SOCIALACCOUNT_PROVIDERS = {ACCOUNT_LOGOUT_ON_GET = TrueSOCIALACCOUNT_LOGIN_ON_GET = True-=======++## allauth.headless — REST API used by the Flutter app for the full auth flow# (login + multi-step MFA challenge + email/password management).#@@ -301,7 +301,9 @@ HEADLESS_TOKEN_STRATEGY = 'allauth.headless.tokens.strategies.jwt.strategy.JWTTo# HS256 with SECRET_KEY by default; main.py mirrors SIMPLE_JWT['SIGNING_KEY']# into HEADLESS_JWT_PRIVATE_KEY so both surfaces share the same secret.HEADLESS_JWT_ALGORITHM = 'HS256'->>>>>>> 677f1ea67 (Start adding the allauth headless app for API authentication)+# 120 days, parity with the legacy SIMPLE_JWT REFRESH_TOKEN_LIFETIME default.+# main.py overrides via the REFRESH_TOKEN_LIFETIME env var (hours).+HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN = 120 * 24 * 3600## Logindiff --git a/wger/core/api/serializers.py b/wger/core/api/serializers.pyindex a53f66824..8055c28c4 100644--- a/wger/core/api/serializers.py+++ b/wger/core/api/serializers.py@@ -23,11 +23,7 @@ from django.contrib.auth.password_validation import validate_passwordfrom django.http import HttpRequest# Third Party-from allauth.account.models import EmailAddress-from allauth.account.utils import (- filter_users_by_email,- user_email,-)+from allauth.account.utils import filter_users_by_emailfrom lingua import LanguageDetectorBuilderfrom rest_framework import serializersfrom rest_framework.fields import empty@@ -51,7 +47,9 @@ class UserprofileSerializer(serializers.ModelSerializer):Workout session serializer"""- email = serializers.EmailField(source='user.email', required=False)+ # Email is read-only here; the app manages email changes through+ # allauth.headless (POST /_allauth/app/v1/account/email).+ email = serializers.EmailField(source='user.email', read_only=True)username = serializers.CharField(source='user.username', read_only=True)date_joined = serializers.DateTimeField(source='user.date_joined', read_only=True)email_verified = serializers.BooleanField(source='is_verified', read_only=True)@@ -92,37 +90,6 @@ class UserprofileSerializer(serializers.ModelSerializer):'num_days_weight_reminder',)- def validate_email(self, value):- if not value:- return value- user = self.context['request'].user-- # Re-submitting one's own email is fine- if value.lower() == (user.email or '').lower():- return value-- # Uniqueness across `User.email` and allauth's `EmailAddress` table- if any(u.pk != user.pk for u in filter_users_by_email(value)):- raise serializers.ValidationError('A user with this email already exists.')- return value-- def update(self, instance, validated_data):- new_email = validated_data.pop('user', {}).get('email')- instance = super().update(instance, validated_data)-- user = instance.user- if new_email and new_email.lower() != (user.email or '').lower():- user_email(user, new_email)- user.save()- EmailAddress.objects.add_email(- self.context['request'],- user,- new_email,- confirm=True,- )-- return instance-class UserLoginSerializer(serializers.ModelSerializer):"""Serializer to map to User model in relation to api user"""diff --git a/wger/core/templates/user/api_key.html b/wger/core/templates/user/api_key.htmlindex 756412284..5698483a2 100644--- a/wger/core/templates/user/api_key.html+++ b/wger/core/templates/user/api_key.html@@ -13,6 +13,100 @@{% endblocktranslate %}</p>+ <h4 class="mt-4">{% translate "Long-lived refresh tokens" %}</h4>++ <p>+ {% blocktranslate trimmed %}+ Refresh tokens let scripts and CLI tools talk to the wger API using+ the JWT flow without logging in interactively each time.+ {% endblocktranslate %}+ </p>++ <p>+ <button+ type="button"+ class="btn btn-block btn-light"+ hx-post="{% url 'core:user:api-key' %}"+ hx-vals='{"new_refresh_token": "true"}'+ hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'+ hx-target="body"+ hx-push-url="true"+ >+ {% translate "Generate a new refresh token" %}+ </button>+ </p>++ {% if new_refresh_token %}+ <div class="alert alert-warning">+ <strong>{% translate "Copy this token now." %}</strong>+ {% blocktranslate trimmed %}+ It is shown only once. If you lose it, generate a new one and+ revoke the old session below.+ {% endblocktranslate %}+ </div>+ <div class="card mb-4 text-white bg-success">+ <div class="card-body">+ <code class="text-white" style="word-break: break-all;">{{ new_refresh_token }}</code>+ </div>+ </div>+ {% endif %}++ {% if long_lived_sessions %}+ <p>+ {% blocktranslate trimmed with days=refresh_token_lifetime_days %}+ Refresh tokens expire {{ days }} days after they were+ generated, unless you revoke them sooner.+ {% endblocktranslate %}+ </p>++ <table class="table">+ <thead>+ <tr>+ <th>{% translate "Created" %}</th>+ <th>{% translate "Expires" %}</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ {% for session in long_lived_sessions %}+ {% with data=session.get_decoded %}+ <tr>+ <td>{{ data.wger_long_lived_refresh_created_at|default:"—" }}</td>+ <td>{{ session.expire_date|date:"Y-m-d H:i" }}</td>+ <td>+ <button+ type="button"+ class="btn btn-sm btn-outline-danger"+ hx-post="{% url 'core:user:api-key' %}"+ hx-vals='{"revoke_refresh_token": "{{ session.session_key }}"}'+ hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'+ hx-target="body"+ hx-push-url="true"+ >+ {% translate "Revoke" %}+ </button>+ </td>+ </tr>+ {% endwith %}+ {% endfor %}+ </tbody>+ </table>++ <p>+ <button+ type="button"+ class="btn btn-block btn-light"+ hx-post="{% url 'core:user:api-key' %}"+ hx-vals='{"revoke_all_refresh_tokens": "true"}'+ hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'+ hx-target="body"+ hx-push-url="true"+ >+ {% translate "Revoke all refresh tokens" %}+ </button>+ </p>+ {% endif %}+<h4 class="mt-4">{% translate "JWT sessions" %}</h4><p>diff --git a/wger/core/tests/test_apikey.py b/wger/core/tests/test_apikey.pyindex 7deb8790f..9a179a586 100644--- a/wger/core/tests/test_apikey.py+++ b/wger/core/tests/test_apikey.py@@ -13,10 +13,12 @@# You should have received a copy of the GNU Affero General Public License# Standard Library+import jsonimport logging# Djangofrom django.contrib.auth.models import User+from django.contrib.sessions.models import Sessionfrom django.urls import reverse# Third Party@@ -29,6 +31,11 @@ from rest_framework_simplejwt.token_blacklist.models import (# wgerfrom wger.core.tests.base_testcase import WgerTestCase+from wger.utils.headless_long_lived import (+ LONG_LIVED_FLAG,+ list_long_lived_sessions,+ mint_long_lived_refresh_token,+)logger = logging.getLogger(__name__)@@ -226,3 +233,155 @@ class ApiKeyTestCase(WgerTestCase):format='json',)self.assertEqual(refresh_after.status_code, 200)+++class LongLivedRefreshTokenTestCase(WgerTestCase):+ """+ Mint, list, and revoke long-lived headless JWT refresh tokens from the+ /user/api-key page.+ """++ def test_generate_shows_token_once(self):+ """+ POST ``new_refresh_token`` mints a token and the next page render+ displays it exactly once. Refreshing the page does not show it again.+ """+ self.user_login('test')++ response = self.client.post(+ reverse('core:user:api-key'),+ {'new_refresh_token': 'true'},+ )+ self.assertEqual(response.status_code, 302)++ response = self.client.get(response['Location'])+ self.assertEqual(response.status_code, 200)+ self.assertContains(response, 'Copy this token now.')+ self.assertContains(response, 'Revoke')++ # Refreshing must not show the token again.+ response = self.client.get(reverse('core:user:api-key'))+ self.assertNotContains(response, 'Copy this token now.')++ def test_generated_token_works_against_headless_refresh(self):+ """+ The minted refresh token actually validates against the headless+ token-refresh endpoint and returns a new access token.+ """+ self.user_login('test')+ user = User.objects.get(username='test')++ token = mint_long_lived_refresh_token(user, lifetime_seconds=120 * 86400)++ api = APIClient()+ response = api.post(+ reverse('headless:app:tokens:refresh'),+ data=json.dumps({'refresh_token': token}),+ content_type='application/json',+ )+ self.assertEqual(response.status_code, 200, response.content)+ body = response.json()+ self.assertIn('access_token', body['data'])++ def test_revoke_invalidates_token(self):+ """+ Revoking a long-lived session breaks the matching refresh token.+ """+ self.user_login('test')+ user = User.objects.get(username='test')++ token = mint_long_lived_refresh_token(user, lifetime_seconds=120 * 86400)+ sessions = list_long_lived_sessions(user)+ self.assertEqual(len(sessions), 1)+ session_key = sessions[0].session_key++ response = self.client.post(+ reverse('core:user:api-key'),+ {'revoke_refresh_token': session_key},+ )+ self.assertEqual(response.status_code, 302)+ self.assertEqual(list_long_lived_sessions(user), [])++ api = APIClient()+ refresh = api.post(+ reverse('headless:app:tokens:refresh'),+ data=json.dumps({'refresh_token': token}),+ content_type='application/json',+ )+ self.assertGreaterEqual(refresh.status_code, 400)++ def test_revoke_all(self):+ """+ Bulk revocation kills every long-lived session of the current user.+ """+ self.user_login('test')+ user = User.objects.get(username='test')++ for _ in range(3):+ mint_long_lived_refresh_token(user, lifetime_seconds=120 * 86400)+ self.assertEqual(len(list_long_lived_sessions(user)), 3)++ response = self.client.post(+ reverse('core:user:api-key'),+ {'revoke_all_refresh_tokens': 'true'},+ )+ self.assertEqual(response.status_code, 302)+ self.assertEqual(list_long_lived_sessions(user), [])++ def test_revoke_cannot_target_other_users_session(self):+ """+ Posting another user's session_key must not delete that user's+ long-lived session — same cross-user defense as the JWT-revoke flow.+ """+ admin = User.objects.get(username='admin')+ mint_long_lived_refresh_token(admin, lifetime_seconds=120 * 86400)+ admin_sessions = list_long_lived_sessions(admin)+ self.assertEqual(len(admin_sessions), 1)+ admin_session_key = admin_sessions[0].session_key++ self.user_login('test')+ response = self.client.post(+ reverse('core:user:api-key'),+ {'revoke_refresh_token': admin_session_key},+ )+ self.assertEqual(response.status_code, 302)++ # Admin's long-lived session is still there.+ self.assertEqual(len(list_long_lived_sessions(admin)), 1)++ def test_generate_requires_post(self):+ """+ State-changing actions must not be triggered by a GET (CSRF defense).+ """+ self.user_login('test')+ user = User.objects.get(username='test')++ response = self.client.get(+ reverse('core:user:api-key'),+ {'new_refresh_token': 'true'},+ )+ self.assertEqual(response.status_code, 200)+ self.assertEqual(list_long_lived_sessions(user), [])++ def test_browser_session_is_not_listed(self):+ """+ The user's regular browser session must not show up in the list of+ long-lived refresh tokens — only sessions tagged with+ ``LONG_LIVED_FLAG`` count.+ """+ self.user_login('test')+ user = User.objects.get(username='test')++ # The login above created a browser session; confirm it exists and is+ # *not* listed (no long-lived marker).+ self.assertEqual(list_long_lived_sessions(user), [])++ # And the marker really is what gates inclusion.+ browser_sessions = [+ s+ for s in Session.objects.all()+ if s.get_decoded().get('_auth_user_id') == str(user.pk)+ ]+ self.assertTrue(browser_sessions)+ for s in browser_sessions:+ self.assertFalse(s.get_decoded().get(LONG_LIVED_FLAG))diff --git a/wger/core/tests/test_verification.py b/wger/core/tests/test_verification.pyindex 7e5a5bd57..52e777765 100644--- a/wger/core/tests/test_verification.py+++ b/wger/core/tests/test_verification.py@@ -25,10 +25,7 @@ from django.urls import reverse# Third Partyfrom allauth.account.models import EmailAddress-from rest_framework.status import (- HTTP_200_OK,- HTTP_400_BAD_REQUEST,-)+from rest_framework.status import HTTP_200_OK# wgerfrom wger.core.tests.base_testcase import WgerTestCase@@ -193,106 +190,26 @@ class EmailVerificationFromAPITestCase(WgerTestCase):self.assertEqual(len(mail.outbox), 0)-@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')-class UserProfileEmailUpdateTestCase(WgerTestCase):+class UserProfileEmailReadOnlyTestCase(WgerTestCase):"""- Tests that updating the email address through the user profile API- enforces format and uniqueness validation. Without it, an attacker- could claim another user's email and poison password-reset delivery.+ Email is read-only on the userprofile endpoint; clients change addresses+ through the allauth.headless ``account/email`` endpoint instead."""URL = '/api/v2/userprofile/'- def _post(self, payload):- return self.client.post(- self.URL,- data=json.dumps(payload),- content_type='application/json',- )-- def test_email_collision_is_rejected(self):- """- Claiming another user's email must fail with 400.- """+ def test_email_in_payload_is_ignored(self):self.user_login('test')- # Make sure admin has a known email so the collision is meaningful- admin = User.objects.get(username='admin')- admin.email = '[email protected]'- admin.save()-- response = self._post({'email': '[email protected]'})- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)- self.assertNotEqual(- User.objects.get(username='test').email,- '[email protected]',- )+ original_email = User.objects.get(username='test').email- def test_email_collision_case_insensitive(self):- """- Email comparison must be case-insensitive — Django's password reset- already filters with ``email__iexact``.- """- self.user_login('test')- admin = User.objects.get(username='admin')- admin.email = '[email protected]'- admin.save()-- response = self._post({'email': '[email protected]'})- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)-- def test_invalid_email_format_is_rejected(self):- self.user_login('test')-- response = self._post({'email': 'not-an-email'})- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)- self.assertNotEqual(- User.objects.get(username='test').email,- 'not-an-email',+ response = self.client.post(+ self.URL,+ data=json.dumps({'email': '[email protected]'}),+ content_type='application/json',)- def test_unique_email_is_accepted(self):- """- Sanity: a fresh, well-formed email passes validation and updates- the user record.- """- self.user_login('test')-- response = self._post({'email': '[email protected]'})self.assertEqual(response.status_code, HTTP_200_OK)self.assertEqual(User.objects.get(username='test').email,- '[email protected]',- )-- def test_unchanged_email_is_accepted(self):- """- Re-posting one's own email must not trigger a uniqueness error.- """- self.user_login('test')- own_email = User.objects.get(username='test').email-- response = self._post({'email': own_email})- self.assertEqual(response.status_code, HTTP_200_OK)-- def test_collision_with_secondary_email_address_is_rejected(self):- """- Uniqueness must also cover the allauth ``EmailAddress`` table —- i.e. addresses that another user has registered as a secondary- (non-primary) address. Otherwise an attacker could claim such an- address as their primary ``User.email``.- """- admin = User.objects.get(username='admin')- EmailAddress.objects.create(- user=admin,- email='[email protected]',- primary=False,- verified=False,- )-- self.user_login('test')- response = self._post({'email': '[email protected]'})- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)- self.assertNotEqual(- User.objects.get(username='test').email,- '[email protected]',+ original_email,)diff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex e8c715a0a..d92eb1bed 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -102,6 +102,12 @@ from wger.utils.api_token import (count_active_jwt_refresh_tokens,create_token,)+from wger.utils.headless_long_lived import (+ list_long_lived_sessions,+ mint_long_lived_refresh_token,+ revoke_all_long_lived_sessions,+ revoke_long_lived_session,+)from wger.utils.generic_views import (WgerFormMixin,WgerMultiplePermissionRequiredMixin,@@ -476,12 +482,48 @@ def api_key(request):messages.success(request, _('All API sessions were revoked'))return HttpResponseRedirect(reverse('core:user:api-key'))+ # Long-lived refresh tokens (headless JWT, backed by a dedicated session).+ if request.method == 'POST' and request.POST.get('new_refresh_token'):+ new_refresh_token = mint_long_lived_refresh_token(+ request.user,+ settings.HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN,+ )+ # Carry the freshly minted token across the post-redirect step so the+ # next render can show it exactly once.+ request.session[_NEW_REFRESH_TOKEN_SESSION_KEY] = new_refresh_token+ return HttpResponseRedirect(reverse('core:user:api-key'))++ if request.method == 'POST' and request.POST.get('revoke_refresh_token'):+ if revoke_long_lived_session(request.user, request.POST['revoke_refresh_token']):+ messages.success(request, _('Refresh token was revoked'))+ return HttpResponseRedirect(reverse('core:user:api-key'))++ if request.method == 'POST' and request.POST.get('revoke_all_refresh_tokens'):+ count = revoke_all_long_lived_sessions(request.user)+ if count:+ messages.success(+ request,+ _('Revoked {count} refresh token(s)').format(count=count),+ )+ return HttpResponseRedirect(reverse('core:user:api-key'))+context['token'] = tokencontext['active_jwt_sessions'] = count_active_jwt_refresh_tokens(request.user)+ context['new_refresh_token'] = request.session.pop(_NEW_REFRESH_TOKEN_SESSION_KEY, None)+ context['long_lived_sessions'] = list_long_lived_sessions(request.user)+ context['refresh_token_lifetime_days'] = (+ settings.HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN // 86400+ )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'++class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, DetailView):"""User overview for gyms