Self hosted FLOSS fitness/workout, nutrition and weight tracker
Serve the user profile as the singleton it is
Roland Geider6b40ac0c69f7
diff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex 56546f909..2deee9821 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -20,7 +20,6 @@ import logging# Djangofrom django.conf import settings-from django.contrib.auth.models import Userfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import (DataError,@@ -36,7 +35,6 @@ 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,@@ -45,11 +43,11 @@ from drf_spectacular.utils import (inline_serializer,)from rest_framework import (+ generics,status,viewsets,)from rest_framework.decorators import (- action,api_view,permission_classes,)@@ -66,6 +64,7 @@ from rest_framework.permissions import (IsAuthenticated,)from rest_framework.response import Response+from rest_framework.views import APIView# wger# The per-app powersync modules are imported for their side effect: each one@@ -93,7 +92,6 @@ from wger.core.models import (WeightUnit,)from wger.utils.headless_long_lived import mint_long_lived_refresh_token-from wger.utils.permissions import WgerPermissionfrom wger.utils.powersync import REGISTRY as POWERSYNC_REGISTRYfrom wger.version import (MIN_APP_VERSION,@@ -105,81 +103,49 @@ 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):+class UserProfileView(generics.RetrieveUpdateAPIView):"""API endpoint for the user profile- This endpoint works somewhat differently than the others since it always- returns the data for the currently logged-in user's profile. To update- the profile, use a POST request with the new data, not a PATCH.+ Every user has exactly one profile, so this endpoint has no list and no+ detail route: it always reads and writes the profile of the logged-in user.+ Updating it takes a PATCH since wger 2.7; up to 2.6 it took a POST."""- schema = UserProfileAutoSchema()serializer_class = UserprofileSerializer- permission_classes = (- IsAuthenticated,- WgerPermission,- )+ permission_classes = (IsAuthenticated,)- def get_queryset(self):- """- Only allow access to appropriate objects- """- # REST API generation- if getattr(self, 'swagger_fake_view', False):- return UserProfile.objects.none()-- return UserProfile.objects.filter(user=self.request.user)+ def get_object(self) -> UserProfile:+ return self.request.user.userprofile- @staticmethod- def get_owner_objects():- """- Return objects to check for ownership permission- """- 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- """- queryset = self.get_queryset()- serializer = self.serializer_class(queryset.first(), many=False)-- return Response(serializer.data)-- def retrieve(self, request, *args, **kwargs):- return self.list(request, *args, **kwargs)-- def create(self, request, *args, **kwargs):- serializer = self.get_serializer(request.user.userprofile, data=request.data)- serializer.is_valid(raise_exception=True)- serializer.save()- return Response(serializer.data)+ # Only way to update the profile up to wger 2.6, kept for clients that talk+ # to those servers. Deprecated instead of hidden so it reaches the schema.+ @extend_schema(+ operation_id='userprofile_update_legacy',+ deprecated=True,+ summary='Update the profile of servers up to wger 2.6',+ description=(+ 'Updates the profile of the logged-in user, exactly like PATCH does.\n\n'+ 'Use this if your client needs to work with wger 2.6 or older, which '+ 'accept only POST on this endpoint. Servers from 2.7 on accept both, '+ 'so prefer PATCH in this case.'+ ),+ request=UserprofileSerializer,+ responses={200: UserprofileSerializer},+ )+ def post(self, request, *args, **kwargs):+ return self.partial_update(request, *args, **kwargs)- def update(self, request, *args, **kwargs):- return self.create(request, *args, **kwargs)- def partial_update(self, request, *args, **kwargs):- return self.create(request, *args, **kwargs)+class VerifyEmailView(APIView):+ """+ Sends a verification email to the logged-in user+ """- @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)+ permission_classes = (IsAuthenticated,)@extend_schema(+ request=None,responses={200: inline_serializer(name='VerifyEmailResponse',@@ -191,8 +157,7 @@ class UserProfileViewSet(viewsets.ModelViewSet):),},)- @action(detail=False, methods=['post'], url_name='verify-email', url_path='verify-email')- def verify_email(self, request):+ def post(self, request):"""Verify the user's email addressdiff --git a/wger/core/tests/test_oidc_provider.py b/wger/core/tests/test_oidc_provider.pyindex 3f094629b..8c69eb79e 100644--- a/wger/core/tests/test_oidc_provider.py+++ b/wger/core/tests/test_oidc_provider.py@@ -252,7 +252,7 @@ class OidcProviderTestCase(WgerTestCase):# granted it. Log out first, otherwise SessionAuthentication answers.self.client.logout()response = self.client.get(- reverse('userprofile-list'),+ reverse('userprofile'),HTTP_AUTHORIZATION=f'Bearer {token["access_token"]}',)self.assertEqual(response.status_code, 200)@@ -525,7 +525,7 @@ class OidcProviderTestCase(WgerTestCase):def read_profile(self, token: str):return self.client.get(- reverse('userprofile-list'),+ reverse('userprofile'),HTTP_AUTHORIZATION=f'Bearer {token}',)@@ -567,7 +567,7 @@ class OidcProviderTestCase(WgerTestCase):token = self.create_access_token([SCOPE_READ])response = self.client.get(- reverse('userprofile-list'),+ reverse('userprofile'),HTTP_AUTHORIZATION=f'Bearer {token}',)@@ -606,7 +606,7 @@ class OidcProviderTestCase(WgerTestCase):token = self.create_access_token([SCOPE_READ])response = self.client.get(- reverse('userprofile-list'),+ reverse('userprofile'),HTTP_AUTHORIZATION=f'Bearer {token}',)@@ -631,7 +631,7 @@ class OidcProviderTestCase(WgerTestCase):token = self.create_access_token(['openid', 'profile', 'email'])response = self.client.get(- reverse('userprofile-list'),+ reverse('userprofile'),HTTP_AUTHORIZATION=f'Bearer {token}',)diff --git a/wger/core/tests/test_user_profile_api.py b/wger/core/tests/test_user_profile_api.pynew file mode 100644index 000000000..4ed5fa1c1--- /dev/null+++ b/wger/core/tests/test_user_profile_api.py@@ -0,0 +1,82 @@+# 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++# Django+from django.contrib.auth.models import User+from django.urls import reverse++# wger+from wger.core.tests.base_testcase import WgerTestCase+++class UserProfileApiTestCase(WgerTestCase):+ """+ Test the user profile endpoint, which serves a single object per user+ """++ def setUp(self):+ super().setUp()+ self.user_login('test')+ self.url = reverse('userprofile')++ def test_get_returns_the_callers_profile(self):+ response = self.client.get(self.url)++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()['username'], 'test')++ def test_patch_updates_the_profile(self):+ response = self.client.patch(+ self.url, data={'calories': 2500}, content_type='application/json'+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()['calories'], 2500)+ self.assertEqual(User.objects.get(username='test').userprofile.calories, 2500)++ def test_post_still_updates_the_profile(self):+ """POST is kept as a deprecated alias for clients written against the old API"""+ response = self.client.post(+ self.url, data={'calories': 2400}, content_type='application/json'+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(User.objects.get(username='test').userprofile.calories, 2400)++ def test_post_leaves_unsent_fields_alone(self):+ profile = User.objects.get(username='test').userprofile+ profile.sleep_hours = 9+ profile.save()++ self.client.post(self.url, data={'calories': 2400}, content_type='application/json')++ profile.refresh_from_db()+ self.assertEqual(profile.calories, 2400)+ self.assertEqual(profile.sleep_hours, 9)++ def test_there_is_no_detail_route(self):+ """The profile is addressed without an id, so no other one is reachable"""+ response = self.client.get(f'{self.url}1/')++ self.assertEqual(response.status_code, 404)++ def test_profiles_cannot_be_deleted(self):+ response = self.client.delete(self.url)++ self.assertEqual(response.status_code, 405)++ def test_anonymous_access_is_refused(self):+ self.client.logout()++ self.assertEqual(self.client.get(self.url).status_code, 403)diff --git a/wger/urls.py b/wger/urls.pyindex ecc77251f..2772ba076 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -136,7 +136,8 @@ router.register(r'workoutlog', manager_api_views.WorkoutLogViewSet, basename='wo# Core approuter.register(r'language', core_api_views.LanguageViewSet, basename='language')router.register(r'license', core_api_views.LicenseViewSet, basename='license')-router.register(r'userprofile', core_api_views.UserProfileViewSet, basename='userprofile')+# userprofile is not registered here: a user has exactly one profile, so it is+# a plain path without list or detail routes (see UserProfileView)router.register(r'setting-repetitionunit',core_api_views.RepetitionUnitViewSet,@@ -315,6 +316,16 @@ urlpatterns += [name='exercise-submission',),path('api/v2/check-language/', core_api_views.check_language, name='check-language'),+ path(+ 'api/v2/userprofile/',+ core_api_views.UserProfileView.as_view(),+ name='userprofile',+ ),+ path(+ 'api/v2/userprofile/verify-email/',+ core_api_views.VerifyEmailView.as_view(),+ name='userprofile-verify-email',+ ),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'),