Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Start adding the allauth headless app for API authentication

Roland Geider0473afe7c65d
diff --git a/settings/main.py b/settings/main.py
index 4010299a6..09a261ff0 100644
--- a/settings/main.py
+++ b/settings/main.py
@@ -290,6 +290,10 @@ if not _SIGNING_KEY or (_SIGNING_KEY in _DEFAULT_KEYS and not DEBUG):
)
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
+
#
# https://docs.djangoproject.com/en/4.1/ref/csrf/
#
diff --git a/settings/settings_global.py b/settings/settings_global.py
index 5bdce9f1b..481c58c65 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -125,6 +125,7 @@ INSTALLED_APPS = [
'allauth',
'allauth.account',
'allauth.mfa',
+ 'allauth.headless',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
@@ -270,6 +271,7 @@ MFA_PASSKEY_LOGIN_ENABLED = True
MFA_PASSKEY_SIGNUP_ENABLED = False
#
+<<<<<<< HEAD
# Social account providers
#
SOCIALACCOUNT_PROVIDERS = {
@@ -287,6 +289,19 @@ SOCIALACCOUNT_PROVIDERS = {
ACCOUNT_LOGOUT_ON_GET = True
SOCIALACCOUNT_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).
+#
+# The web frontend continues to use the regular allauth views, so only the
+# 'app' client is enabled.
+#
+HEADLESS_CLIENTS = ('app',)
+HEADLESS_TOKEN_STRATEGY = 'allauth.headless.tokens.strategies.jwt.strategy.JWTTokenStrategy'
+# 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)
#
# Login
@@ -453,6 +468,7 @@ REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
+ 'wger.utils.headless_auth.HeadlessJWTAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_FILTER_BACKENDS': (
diff --git a/wger/core/tests/test_headless.py b/wger/core/tests/test_headless.py
new file mode 100644
index 000000000..7db363eaf
--- /dev/null
+++ b/wger/core/tests/test_headless.py
@@ -0,0 +1,76 @@
+# -*- coding: utf-8 -*-
+
+# 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/>.
+
+# Standard Library
+import json
+
+# wger
+from wger.core.tests.base_testcase import WgerTestCase
+
+
+class HeadlessSmokeTestCase(WgerTestCase):
+ """
+ End-to-end smoke test for the allauth.headless surface:
+
+ - the public `config` endpoint responds with the headless capability
+ descriptor (proves the URL mount is correct);
+ - a headless login mints a JWT access token (proves JWTTokenStrategy is
+ wired up correctly);
+ - that JWT authenticates a regular `/api/v2/` request via
+ ``HeadlessJWTAuthentication`` (proves the DRF bridge works).
+ """
+
+ def test_config_endpoint(self):
+ response = self.client.get('/_allauth/app/v1/config')
+ self.assertEqual(response.status_code, 200)
+ body = response.json()
+ self.assertEqual(body['status'], 200)
+
+ def test_login_mints_jwt_and_authenticates_drf(self):
+ response = self.client.post(
+ '/_allauth/app/v1/auth/login',
+ data=json.dumps({'username': 'test', 'password': 'testtest'}),
+ content_type='application/json',
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ meta = response.json()['meta']
+ self.assertTrue(meta['is_authenticated'])
+ access_token = meta['access_token']
+ self.assertTrue(access_token)
+
+ # Use the JWT against a regular /api/v2/ endpoint. A fresh client avoids
+ # the session cookie SessionAuthentication would otherwise consume.
+ self.client.logout()
+ response = self.client.get(
+ '/api/v2/workoutsession/',
+ HTTP_AUTHORIZATION=f'Bearer {access_token}',
+ )
+ self.assertEqual(response.status_code, 200)
+
+ def test_invalid_jwt_does_not_break_auth_chain(self):
+ """
+ A malformed Bearer token must not raise AuthenticationFailed in our
+ wrapper, the DRF auth chain has to fall through so the next class
+ (e.g. SimpleJWT during the sunset window) still gets a turn.
+ The final response is a permission rejection (403), not a 401 from a
+ terminated chain.
+ """
+ response = self.client.get(
+ '/api/v2/workoutsession/',
+ HTTP_AUTHORIZATION='Bearer not-a-real-token',
+ )
+ self.assertIn(response.status_code, (401, 403))
diff --git a/wger/urls.py b/wger/urls.py
index 98bd80fe3..9c03d560b 100644
--- a/wger/urls.py
+++ b/wger/urls.py
@@ -301,6 +301,8 @@ urlpatterns = i18n_patterns(
urlpatterns += [
path('i18n/', include('django.conf.urls.i18n')),
path('robots.txt', TextTemplateView.as_view(template_name='robots.txt'), name='robots'),
+ # allauth.headless — REST auth API consumed by the Flutter app.
+ path('_allauth/', include('allauth.headless.urls')),
# API
path(
'api/v2/exercise-submission/',
diff --git a/wger/utils/headless_auth.py b/wger/utils/headless_auth.py
new file mode 100644
index 000000000..cf74ee6f3
--- /dev/null
+++ b/wger/utils/headless_auth.py
@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+
+# 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/>.
+
+# Third Party
+from allauth.headless.contrib.rest_framework.authentication import JWTTokenAuthentication
+from rest_framework.exceptions import AuthenticationFailed
+
+
+class HeadlessJWTAuthentication(JWTTokenAuthentication):
+ """
+ Lenient variant of allauth's JWTTokenAuthentication.
+
+ Returns ``None`` for tokens that don't validate as a headless JWT instead of
+ raising. ``Authorization: Bearer`` is shared with ``rest_framework_simplejwt``
+ raising would abort the DRF auth chain and stop the next class from getting a
+ chance at the token.
+ """
+
+ def authenticate(self, request):
+ try:
+ return super().authenticate(request)
+ except AuthenticationFailed:
+ return None