Self hosted FLOSS fitness/workout, nutrition and weight tracker
Fix response types in the OpenAPI schema
Roland Geider81cc564c28e7
diff --git a/settings/settings_global.py b/settings/settings_global.pyindex cd508d969..0cbbeb758 100644--- a/settings/settings_global.py+++ b/settings/settings_global.py@@ -513,6 +513,14 @@ SPECTACULAR_SETTINGS = {'SWAGGER_UI_FAVICON_HREF': 'SIDECAR','REDOC_DIST': 'SIDECAR','COMPONENT_SPLIT_REQUEST': True,+ # Both are exposed as a plain "type" field on more than one component, which+ # spectacular would otherwise name with a hash suffix (e.g. Type947Enum).+ # The names end up as class names in generated clients, so pin them.+ 'ENUM_NAME_OVERRIDES': {+ 'DayTypeEnum': 'wger.manager.models.day.DayType.choices',+ 'ExerciseTypeEnum': 'wger.manager.models.slot_entry.ExerciseType.choices',+ 'IntensityEnum': 'wger.core.models.profile.UserProfile.INTENSITY',+ },}#diff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex bbe8768c6..804f9df68 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -36,6 +36,7 @@ from django.utils.decorators import method_decoratorfrom django.views.decorators.cache import cache_page# Third Party+from drf_spectacular.openapi import AutoSchemafrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import (OpenApiParameter,@@ -53,7 +54,10 @@ from rest_framework.decorators import (permission_classes,)from rest_framework.exceptions import ValidationError as DRFValidationError-from rest_framework.fields import BooleanField+from rest_framework.fields import (+ BooleanField,+ CharField,+)from rest_framework.permissions import (AllowAny,IsAuthenticated,@@ -98,6 +102,18 @@ from wger.version import (logger = logging.getLogger(__name__)+class UserProfileAutoSchema(AutoSchema):+ """+ Keeps the list route out of spectacular's list/pagination heuristic, which+ would otherwise document the single profile object as a paginated list.+ """++ def _is_list_view(self, serializer=None):+ if getattr(self.view, 'action', None) == 'list':+ return False+ return super()._is_list_view(serializer)++class UserProfileViewSet(viewsets.ModelViewSet):"""API endpoint for the user profile@@ -107,6 +123,7 @@ class UserProfileViewSet(viewsets.ModelViewSet):the profile, use a POST request with the new data, not a PATCH."""+ schema = UserProfileAutoSchema()serializer_class = UserprofileSerializerpermission_classes = (IsAuthenticated,@@ -130,6 +147,7 @@ class UserProfileViewSet(viewsets.ModelViewSet):"""return [(User, 'user')]+ @extend_schema(operation_id='userprofile_list', responses={200: UserprofileSerializer})def list(self, request, *args, **kwargs):"""Customized list view, that returns only the current user's data@@ -154,9 +172,22 @@ class UserProfileViewSet(viewsets.ModelViewSet):def partial_update(self, request, *args, **kwargs):return self.create(request, *args, **kwargs)+ @extend_schema(responses={405: OpenApiResponse(description='Profiles cannot be deleted')})def destroy(self, request, *args, **kwargs):return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)+ @extend_schema(+ responses={+ 200: inline_serializer(+ name='VerifyEmailResponse',+ fields={+ 'status': CharField(required=False),+ 'result': CharField(required=False),+ 'message': CharField(),+ },+ ),+ },+ )@action(detail=False, methods=['post'], url_name='verify-email', url_path='verify-email')def verify_email(self, request):"""diff --git a/wger/manager/api/views.py b/wger/manager/api/views.pyindex 6513e6fcf..b939a8d35 100644--- a/wger/manager/api/views.py+++ b/wger/manager/api/views.py@@ -21,6 +21,7 @@ from django.core.cache import cachefrom django.db.models import Q# Third Party+from drf_spectacular.utils import extend_schemafrom rest_framework import viewsetsfrom rest_framework.decorators import actionfrom rest_framework.response import Response@@ -120,7 +121,8 @@ class RoutineViewSet(viewsets.ModelViewSet):"""serializer.save(user=self.request.user)- @action(detail=True, url_path='date-sequence-display')+ @extend_schema(responses={200: WorkoutDayDataDisplayModeSerializer(many=True)})+ @action(detail=True, url_path='date-sequence-display', pagination_class=None)def date_sequence_display_mode(self, request, pk):"""Return the day sequence of the routine@@ -138,7 +140,8 @@ class RoutineViewSet(viewsets.ModelViewSet):return Response(out)- @action(detail=True, url_path='date-sequence-gym')+ @extend_schema(responses={200: WorkoutDayDataGymModeSerializer(many=True)})+ @action(detail=True, url_path='date-sequence-gym', pagination_class=None)def date_sequence_gym_mode(self, request, pk):"""Return the day sequence of the routine@@ -153,6 +156,7 @@ class RoutineViewSet(viewsets.ModelViewSet):return Response(out)+ @extend_schema(responses={200: RoutineStructureSerializer})@action(detail=True)def structure(self, request, pk):"""@@ -167,7 +171,8 @@ class RoutineViewSet(viewsets.ModelViewSet):cache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])return Response(out)- @action(detail=True, url_path='logs')+ @extend_schema(responses={200: LogDisplaySerializer(many=True)})+ @action(detail=True, url_path='logs', pagination_class=None)def logs(self, request, pk):"""Returns the logs for the routine@@ -181,6 +186,7 @@ class RoutineViewSet(viewsets.ModelViewSet):cache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])return Response(out)+ @extend_schema(responses={200: LogStatsDataSerializer})@action(detail=True, url_path='stats')def stats(self, request, pk):"""@@ -334,6 +340,7 @@ class RoutineDayViewSet(WgerOwnerObjectModelViewSet):ordering_fields = '__all__'filterset_fields = ('id',+ 'routine','order','name','description',diff --git a/wger/manager/tests/test_api_config_filter.py b/wger/manager/tests/test_api_config_filter.pyindex 3b1161dcd..9edb7981d 100644--- a/wger/manager/tests/test_api_config_filter.py+++ b/wger/manager/tests/test_api_config_filter.py@@ -13,10 +13,15 @@# You should have received a copy of the GNU Affero General Public License# Django+from django.contrib.auth.models import Userfrom django.urls import reverse# wgerfrom wger.core.tests.base_testcase import WgerTestCase+from wger.manager.models import (+ Day,+ Routine,+)class ConfigFilterTestCase(WgerTestCase):@@ -34,3 +39,29 @@ class ConfigFilterTestCase(WgerTestCase):response = self.client.get(url, {'slot_entry': 1})self.assertEqual(response.data['count'], 1)self.assertEqual(response.data['results'][0]['slot_entry'], 1)+++class DayFilterTestCase(WgerTestCase):+ """+ The day endpoint must honour the ``routine`` query filter+ """++ def test_filter_by_routine(self):+ user = User.objects.get(username='admin')+ other_routine = Routine.objects.create(+ user=user,+ name='Second routine',+ start='2024-07-01',+ end='2024-08-01',+ )+ Day.objects.create(routine=other_routine, name='Other day', order=1)++ self.user_login()+ url = reverse('day-list')++ response = self.client.get(url)+ self.assertEqual(response.data['count'], 4)++ response = self.client.get(url, {'routine': 1})+ self.assertEqual(response.data['count'], 3)+ self.assertEqual({d['routine'] for d in response.data['results']}, {1})diff --git a/wger/utils/headless_auth.py b/wger/utils/headless_auth.pyindex aef352ab6..4070f97e1 100644--- a/wger/utils/headless_auth.py+++ b/wger/utils/headless_auth.py@@ -22,6 +22,7 @@ from django.contrib.auth import get_user_modelfrom allauth.headless.contrib.rest_framework.authentication import JWTTokenAuthenticationfrom allauth.headless.tokens.strategies.jwt import internalfrom allauth.headless.tokens.strategies.jwt.strategy import JWTTokenStrategy+from drf_spectacular.extensions import OpenApiAuthenticationExtensionfrom rest_framework.exceptions import AuthenticationFailed@@ -60,6 +61,27 @@ class HeadlessJWTAuthentication(JWTTokenAuthentication):return user, payload+class HeadlessJWTScheme(OpenApiAuthenticationExtension):+ """+ Schema entry for HeadlessJWTAuthentication.++ Without this, drf-spectacular derives the name from the TokenAuthentication+ base class and collides with DRF's own "tokenAuth", documenting the wrong+ "Token" prefix for this Bearer-based class.+ """++ target_class = 'wger.utils.headless_auth.HeadlessJWTAuthentication'+ name = 'headlessJwtAuth'++ def get_security_definition(self, auto_schema):+ return {+ 'type': 'http',+ 'scheme': 'bearer',+ 'bearerFormat': 'JWT',+ 'description': 'Access token issued by the allauth headless endpoints',+ }++class WgerJWTTokenStrategy(JWTTokenStrategy):"""Hardened variant of allauth's JWTTokenStrategy.