Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Rework the user profile endpoint

Roland Geider5012481b1d8a
diff --git a/wger/core/api/serializers.py b/wger/core/api/serializers.py
index fd70aae50..1584cd5c4 100644
--- a/wger/core/api/serializers.py
+++ b/wger/core/api/serializers.py
@@ -39,11 +39,14 @@ class UserprofileSerializer(serializers.ModelSerializer):
Workout session serializer
"""
+ email = serializers.EmailField(source="user.email", read_only=True)
+ username = serializers.EmailField(source="user.username", read_only=True)
+
class Meta:
model = UserProfile
fields = [
- 'id',
- 'user',
+ 'username',
+ 'email',
'email_verified',
'gym',
'is_temporary',
diff --git a/wger/core/api/views.py b/wger/core/api/views.py
index cb8077f9e..9b75fd682 100644
--- a/wger/core/api/views.py
+++ b/wger/core/api/views.py
@@ -58,10 +58,7 @@ from wger.core.models import (
WeightUnit,
)
from wger.utils.api_token import create_token
-from wger.utils.permissions import (
- UpdateOnlyPermission,
- WgerPermission,
-)
+from wger.utils.permissions import WgerPermission
logger = logging.getLogger(__name__)
@@ -69,11 +66,14 @@ logger = logging.getLogger(__name__)
class UserProfileViewSet(viewsets.ModelViewSet):
"""
- API endpoint for workout objects
+ 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.
"""
- is_private = True
serializer_class = UserprofileSerializer
- permission_classes = (WgerPermission, UpdateOnlyPermission)
+ permission_classes = (WgerPermission, )
def get_queryset(self):
"""
@@ -87,6 +87,63 @@ class UserProfileViewSet(viewsets.ModelViewSet):
"""
return [(User, 'user')]
+ def list(self, request, *args, **kwargs):
+ """
+ Customized list view, that returns only the current user's data
+ """
+ queryset = self.get_queryset()
+ print(queryset.first())
+ 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):
+ data = request.data
+ serializer = self.serializer_class(request.user.userprofile, data=data)
+ if serializer.is_valid():
+ serializer.save()
+
+ # New email, update the user and reset the email verification flag
+ if request.user.email != data['email']:
+ request.user.email = data['email']
+ request.user.save()
+ request.user.userprofile.email_verified = False
+ request.user.userprofile.save()
+ logger.debug('resetting verified flag')
+
+ return Response(serializer.data)
+
+ 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)
+
+ def destroy(self, request, *args, **kwargs):
+ return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
+
+ @action(detail=False, url_name='verify-email', url_path='verify-email')
+ def verify_email(self, request):
+ """
+ Return the username
+ """
+
+ profile = request.user.userprofile
+ if profile.email_verified:
+ return Response({'status': 'verified',
+ 'message': 'This email is already verified'})
+
+ send_email(request.user)
+ return Response(
+ {'status': 'sent',
+ 'message': f'A verification email was sent to {request.user.email}'})
+
+
+class UserViewSet(viewsets.ModelViewSet):
+
@action(detail=True)
def username(self, request, pk: int):
"""
diff --git a/wger/core/static/js/wger-core.js b/wger/core/static/js/wger-core.js
index fe38f8cc1..3d5d44be3 100644
--- a/wger/core/static/js/wger-core.js
+++ b/wger/core/static/js/wger-core.js
@@ -108,15 +108,10 @@ function wgerSetupSortable() {
function setProfileField(field, newValue) {
var dataDict = {};
dataDict[field] = newValue;
- $.get('/api/v2/userprofile', function () {
- }).done(function (userprofile) {
- //console.log('Updating profile field "' + field + '" to value: ' + newValue);
- $.ajax({
- url: '/api/v2/userprofile/' + userprofile.results[0].id + '/',
- type: 'PATCH',
+ $.post({
+ url: '/api/v2/userprofile/',
data: dataDict
});
- });
}
/*
@@ -131,32 +126,12 @@ function getProfileField(field) {
type: 'GET',
async: false,
success: function (userprofile) {
- result = userprofile.results[0][field];
+ result = userprofile.results[field];
}
});
return result;
}
-/*
- Get the current user's username.
- Do not use with anonymous users!
- Synchronous request, use sparingly!
- */
-function wgerGetUsername() {
- var userId;
- var result;
- userId = getProfileField('user');
- result = null;
- $.ajax({
- url: '/api/v2/userprofile/' + userId + '/username/',
- type: 'GET',
- async: false,
- success: function (user) {
- result = user.username;
- }
- });
- return result;
-}
function wgerToggleComments() {
$('#exercise-comments-toggle').click(function (e) {
diff --git a/wger/core/templates/email_verification/confirm_template.html b/wger/core/templates/email_verification/confirm_template.html
index ce3915c7d..2b18d0af7 100644
--- a/wger/core/templates/email_verification/confirm_template.html
+++ b/wger/core/templates/email_verification/confirm_template.html
@@ -15,8 +15,8 @@
{# #}
{% block content %}
{% if success %}
- {% blocktranslate trimmed %}
- {{ user.username }}, your email was verified
+ {% blocktranslate trimmed with username=user.username %}
+ {{ username }}, your email was verified
{% endblocktranslate %}
{% else %}
{% translate "Error, invalid verification token" %}