Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Remove the /api/v2/register/ endpoint as well

Roland Geider5c2707b00097
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0f696e48e..9344377b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -74,9 +74,9 @@ The type for the ID for Measurement and MeasurementCategory was changed from int
to string (UUID). This was made to allow for clients to generate IDs locally and affects
`/api/v2/measurement-category/` and `/api/v2/measurement/`.
-**`/api/v2/login/` endpoint removed.** This endpoint returned a permanent token
-If you want to generate a new token, visit the "API key" page in the user settings
-and paste it into scripts.
+**`/api/v2/login/` and `/api/v2/register/` endpoints removed.** These endpoints returned
+a permanent token, use the allauth ones instead (JWT based). If you still need a permanent
+one, visit the "API key" page in the user settings and paste it into scripts.
**`/api/v2/token` endpoint removed.** Exchanging username + password for a JWT
pair via this endpoint bypassed 2FA. To get tokens, either use
diff --git a/settings/settings_global.py b/settings/settings_global.py
index fe9faed00..4bb716537 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -474,7 +474,6 @@ REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': ['rest_framework.throttling.ScopedRateThrottle'],
'DEFAULT_THROTTLE_RATES': {
'login': '10/min',
- 'registration': '5/min',
# Ingredient endpoints — protect the multi-million-row table from
# crawlers and older sync clients. Throttling is per-IP for anonymous
diff --git a/wger/core/api/serializers.py b/wger/core/api/serializers.py
index 72065f016..be84c24d3 100644
--- a/wger/core/api/serializers.py
+++ b/wger/core/api/serializers.py
@@ -16,15 +16,9 @@
# Standard Library
import logging
-# Django
-from django.contrib.auth.models import User
-from django.contrib.auth.password_validation import validate_password
-
# Third Party
-from allauth.account.utils import filter_users_by_email
from lingua import LanguageDetectorBuilder
from rest_framework import serializers
-from rest_framework.validators import UniqueValidator
# wger
from wger.core.models import (
@@ -88,35 +82,6 @@ class UserprofileSerializer(serializers.ModelSerializer):
)
-class UserRegistrationSerializer(serializers.ModelSerializer):
- email = serializers.EmailField(required=False)
- username = serializers.CharField(
- required=True,
- validators=[UniqueValidator(queryset=User.objects.all())],
- )
- password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
-
- class Meta:
- model = User
- fields = ('username', 'email', 'password')
-
- def validate_email(self, value):
- # Case-insensitive uniqueness across both User.email and the allauth
- # EmailAddress table (which holds secondary addresses too)
- if value and filter_users_by_email(value):
- raise serializers.ValidationError('A user with this email already exists.')
- return value
-
- def create(self, validated_data):
- user = User.objects.create(username=validated_data['username'])
- user.set_password(validated_data['password'])
- if validated_data.get('email'):
- user.email = validated_data['email']
- user.save()
-
- return user
-
-
class LanguageSerializer(serializers.ModelSerializer):
"""
Language serializer
diff --git a/wger/core/api/views.py b/wger/core/api/views.py
index 7832103be..823eb2174 100644
--- a/wger/core/api/views.py
+++ b/wger/core/api/views.py
@@ -29,7 +29,6 @@ from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
# Third Party
-from allauth.account.models import EmailAddress
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
OpenApiParameter,
@@ -46,10 +45,7 @@ from rest_framework.decorators import (
api_view,
permission_classes,
)
-from rest_framework.fields import (
- BooleanField,
- CharField,
-)
+from rest_framework.fields import BooleanField
from rest_framework.permissions import (
AllowAny,
IsAuthenticated,
@@ -73,7 +69,6 @@ from wger.core.api.serializers import (
RepetitionUnitSerializer,
RoutineWeightUnitSerializer,
UserprofileSerializer,
- UserRegistrationSerializer,
)
from wger.core.models import (
Language,
@@ -82,7 +77,6 @@ from wger.core.models import (
UserProfile,
WeightUnit,
)
-from wger.utils.api_token import create_token
from wger.utils.permissions import WgerPermission
from wger.utils.powersync import REGISTRY as POWERSYNC_REGISTRY
from wger.version import (
@@ -271,53 +265,6 @@ class RequiredServerVersionView(viewsets.ViewSet):
return Response(str(MIN_SERVER_VERSION))
-class UserAPIRegistrationViewSet(viewsets.ViewSet):
- """
- API endpoint
- """
-
- # permission_classes = (AllowRegisterUser,)
- serializer_class = UserRegistrationSerializer
- throttle_scope = 'registration'
-
- def get_queryset(self):
- """
- Only allow access to appropriate objects
- """
- return UserProfile.objects.filter(user=self.request.user)
-
- @extend_schema(
- parameters=[],
- responses={
- status.HTTP_200_OK: inline_serializer(
- name='loginSerializer',
- fields={'token': CharField()},
- ),
- },
- )
- def post(self, request):
- if not settings.WGER_SETTINGS['ALLOW_REGISTRATION']:
- return Response(
- {'message': 'Registration is not allowed on this instance'},
- status=status.HTTP_200_OK,
- )
-
- data = request.data
- serializer = self.serializer_class(data=data)
- serializer.is_valid(raise_exception=True)
- user = serializer.save()
- # user.userprofile.added_by = request.user
- user.userprofile.save()
- token = create_token(user)
-
- EmailAddress.objects.add_email(request, user, user.email, confirm=True)
-
- return Response(
- {'message': 'api user successfully registered', 'token': token.key},
- status=status.HTTP_201_CREATED,
- )
-
-
class LanguageViewSet(viewsets.ReadOnlyModelViewSet):
"""
API endpoint for the languages used in the application
diff --git a/wger/core/tests/test_headless.py b/wger/core/tests/test_headless.py
index 7db363eaf..f806629d3 100644
--- a/wger/core/tests/test_headless.py
+++ b/wger/core/tests/test_headless.py
@@ -18,6 +18,9 @@
# Standard Library
import json
+# Django
+from django.contrib.auth.models import User
+
# wger
from wger.core.tests.base_testcase import WgerTestCase
@@ -61,6 +64,46 @@ class HeadlessSmokeTestCase(WgerTestCase):
)
self.assertEqual(response.status_code, 200)
+ def test_signup_respects_allow_registration_setting(self):
+ """
+ With ``ALLOW_REGISTRATION=False`` the WgerAccountAdapter must report
+ the site as closed for signup, so the headless signup endpoint
+ rejects the request and no user is created.
+ """
+ signup_data = {
+ 'username': 'headlessnew',
+ 'email': '[email protected]',
+ 'password': 'AekaiLe0ga',
+ }
+
+ with self.settings(
+ WGER_SETTINGS={
+ 'USE_RECAPTCHA': False,
+ 'ALLOW_GUEST_USERS': True,
+ 'ALLOW_REGISTRATION': False,
+ 'MIN_ACCOUNT_AGE_TO_TRUST': 21,
+ }
+ ):
+ count_before = User.objects.count()
+ response = self.client.post(
+ '/_allauth/app/v1/auth/signup',
+ data=json.dumps(signup_data),
+ content_type='application/json',
+ )
+ self.assertEqual(response.status_code, 403, response.content)
+ self.assertEqual(User.objects.count(), count_before)
+
+ # Sanity-check the opposite path: with registration enabled the same
+ # payload creates a user via the headless endpoint.
+ count_before = User.objects.count()
+ response = self.client.post(
+ '/_allauth/app/v1/auth/signup',
+ data=json.dumps(signup_data),
+ content_type='application/json',
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(User.objects.count(), count_before + 1)
+
def test_invalid_jwt_does_not_break_auth_chain(self):
"""
A malformed Bearer token must not raise AuthenticationFailed in our
diff --git a/wger/core/tests/test_registration.py b/wger/core/tests/test_registration.py
index f104dcaf9..af5959566 100644
--- a/wger/core/tests/test_registration.py
+++ b/wger/core/tests/test_registration.py
@@ -25,12 +25,6 @@ from django.urls import reverse
# Third Party
from allauth.account.models import EmailAddress
-from rest_framework.authtoken.models import Token
-from rest_framework.status import (
- HTTP_200_OK,
- HTTP_201_CREATED,
- HTTP_400_BAD_REQUEST,
-)
# wger
from wger.core.tests.base_testcase import WgerTestCase
@@ -264,184 +258,6 @@ class RegistrationTestCase(WgerTestCase):
self.assertEqual(count_before, count_after)
-class ApiRegistrationTestCase(WgerTestCase):
- def test_post_valid_api_user_creation(self):
- """Successfully register a user via the REST API"""
-
- # Act
- count_before = User.objects.count()
- response = self.client.post(
- reverse('api_register'),
- {'username': 'restapi', 'email': '[email protected]', 'password': 'AekaiLe0ga'},
- )
- count_after = User.objects.count()
-
- # Assert
- self.assertEqual(response.status_code, HTTP_201_CREATED)
- token = Token.objects.get(user__username='restapi')
- self.assertEqual(response.data['message'], 'api user successfully registered')
- self.assertEqual(response.data['token'], token.key)
- self.assertEqual(count_after, count_before + 1)
-
- @override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend')
- def test_api_registration_sends_verification_email(self):
- """Tests that a verification email is sent when registering via the API"""
-
- response = self.client.post(
- reverse('api_register'),
- {'username': 'restapi_email', 'email': '[email protected]', 'password': 'AekaiLe0ga'},
- )
- self.assertEqual(response.status_code, HTTP_201_CREATED)
-
- # A verification email was sent
- self.assertEqual(len(mail.outbox), 1)
- self.assertIn('[email protected]', mail.outbox[0].to)
-
- # An EmailAddress entry was created with verified=False
- user = User.objects.get(username='restapi_email')
- email_obj = EmailAddress.objects.get(user=user)
- self.assertEqual(email_obj.email, '[email protected]')
- self.assertFalse(email_obj.verified)
-
- def test_post_valid_api_user_creation_no_email(self):
- """Successfully register a user via the REST API without providing an email"""
-
- # Act
- count_before = User.objects.count()
- response = self.client.post(
- reverse('api_register'),
- {'username': 'restapi', 'password': 'AekaiLe0ga'},
- )
- count_after = User.objects.count()
-
- # Assert
- self.assertEqual(response.status_code, HTTP_201_CREATED)
- token = Token.objects.get(user__username='restapi')
- self.assertEqual(response.data['message'], 'api user successfully registered')
- self.assertEqual(response.data['token'], token.key)
- self.assertEqual(count_after, count_before + 1)
-
- def test_post_unsuccessfully_registration_no_username(self):
- """Test unsuccessful registration (weak password)"""
-
- # Act
- response = self.client.post(
- reverse('api_register'),
- {'password': 'AekaiLe0ga'},
- )
-
- # Assert
- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
-
- def test_post_unsuccessfully_registration_invalid_email(self):
- """Test unsuccessful registration (invalid email)"""
-
- # Act
- response = self.client.post(
- reverse('api_register'),
- {'username': 'restapi', 'email': 'example.com', 'password': 'AekaiLe0ga'},
- )
-
- # Assert
- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
-
- def test_post_unsuccessfully_registration_invalid_email_2(self):
- """Test unsuccessful registration (email already exists)"""
-
- # Act
- response = self.client.post(
- reverse('api_register'),
- {'username': 'restapi', 'email': '[email protected]', 'password': 'AekaiLe0ga'},
- )
-
- # Assert
- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
-
- def test_post_unsuccessfully_registration_email_case_insensitive(self):
- """
- Email collisions must be detected case-insensitively — Django's
- password reset filters with ``email__iexact``, so registering
- ``[email protected]`` while ``[email protected]`` exists would
- still cause cross-account reset delivery.
- """
- response = self.client.post(
- reverse('api_register'),
- {
- 'username': 'restapi',
- 'email': '[email protected]',
- 'password': 'AekaiLe0ga',
- },
- )
-
- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
-
- def test_post_unsuccessfully_registration_email_in_emailaddress_table(self):
- """
- Uniqueness must also cover allauth's ``EmailAddress`` table —
- secondary addresses owned by another user must not be claimable.
- """
- admin = User.objects.get(username='admin')
- EmailAddress.objects.create(
- user=admin,
- primary=False,
- verified=False,
- )
-
- response = self.client.post(
- reverse('api_register'),
- {
- 'username': 'restapi',
- 'email': '[email protected]',
- 'password': 'AekaiLe0ga',
- },
- )
-
- self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
-
- def test_post_valid_data_registration_deactivated(self):
- """When the registration is deactivated no users can be registered via the API"""
-
- with self.settings(
- WGER_SETTINGS={
- 'ALLOW_GUEST_USERS': False,
- 'ALLOW_REGISTRATION': False,
- }
- ):
- # Act
- count_before = User.objects.count()
- response = self.client.post(
- reverse('api_register'),
- {'username': 'restapi', 'email': '[email protected]', 'password': 'AekaiLe0ga'},
- )
- count_after = User.objects.count()
-
- # Assert
- self.assertEqual(response.status_code, HTTP_200_OK)
- self.assertEqual(count_before, count_after)
-
- def test_post_invalid_data_registration_deactivated(self):
- """When the registration is deactivated the data sent is ignored"""
-
- with self.settings(
- WGER_SETTINGS={
- 'ALLOW_GUEST_USERS': False,
- 'ALLOW_REGISTRATION': False,
- }
- ):
- # Act
- count_before = User.objects.count()
- response = self.client.post(
- reverse('api_register'),
- {'foo': 'bar', 'bar': True, 'answer': 42},
- )
- count_after = User.objects.count()
-
- # Assert
- self.assertEqual(response.status_code, HTTP_200_OK)
- self.assertEqual(count_before, count_after)
-
-
class CreateUserCommand(WgerTestCase):
def setUp(self):
super(CreateUserCommand, self).setUp()
diff --git a/wger/urls.py b/wger/urls.py
index ca38336a9..86bdf7588 100644
--- a/wger/urls.py
+++ b/wger/urls.py
@@ -309,11 +309,6 @@ urlpatterns += [
),
path('api/v2/check-language/', core_api_views.check_language, name='check-language'),
path('api/v2/', include(router.urls)),
- path(
- 'api/v2/register/',
- core_api_views.UserAPIRegistrationViewSet.as_view({'post': 'post'}),
- name='api_register',
- ),
path('api/v2/token/refresh', TokenRefreshView.as_view(), name='token_refresh'),
path('api/v2/token/verify', TokenVerifyView.as_view(), name='token_verify'),
# Others