diff --git a/api/src/backend/api/specs/v1.yaml b/api/src/backend/api/specs/v1.yaml index 7dc3af2104..e43b6ba516 100644 --- a/api/src/backend/api/specs/v1.yaml +++ b/api/src/backend/api/specs/v1.yaml @@ -5381,8 +5381,8 @@ paths: description: '' delete: operationId: users_destroy - description: Remove a user account from the system. - summary: Delete a user account + description: Remove the current user account from the system. + summary: Delete the user account parameters: - in: path name: id diff --git a/api/src/backend/api/tests/test_views.py b/api/src/backend/api/tests/test_views.py index c175334f15..da50c8ca91 100644 --- a/api/src/backend/api/tests/test_views.py +++ b/api/src/backend/api/tests/test_views.py @@ -261,6 +261,16 @@ class TestUserViewSet: assert response.status_code == status.HTTP_204_NO_CONTENT assert not User.objects.filter(id=create_test_user.id).exists() + def test_users_destroy_other_user( + self, authenticated_client, create_test_user, users_fixture + ): + user = users_fixture[2] + response = authenticated_client.delete( + reverse("user-detail", kwargs={"pk": str(user.id)}) + ) + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert User.objects.filter(id=create_test_user.id).exists() + def test_users_destroy_invalid_user(self, authenticated_client, create_test_user): another_user = User.objects.create_user( password="otherpassword", email="other@example.com" @@ -268,7 +278,7 @@ class TestUserViewSet: response = authenticated_client.delete( reverse("user-detail", kwargs={"pk": another_user.id}) ) - assert response.status_code == status.HTTP_404_NOT_FOUND + assert response.status_code == status.HTTP_400_BAD_REQUEST assert User.objects.filter(id=another_user.id).exists() @pytest.mark.parametrize( diff --git a/api/src/backend/api/v1/views.py b/api/src/backend/api/v1/views.py index 67728a65dc..2f40e90fbc 100644 --- a/api/src/backend/api/v1/views.py +++ b/api/src/backend/api/v1/views.py @@ -277,8 +277,8 @@ class SchemaView(SpectacularAPIView): ), destroy=extend_schema( tags=["User"], - summary="Delete a user account", - description="Remove a user account from the system.", + summary="Delete the user account", + description="Remove the current user account from the system.", ), me=extend_schema( tags=["User"], @@ -342,6 +342,12 @@ class UserViewSet(BaseUserViewset): status=status.HTTP_200_OK, ) + def destroy(self, request, *args, **kwargs): + if kwargs["pk"] != str(self.request.user.id): + raise ValidationError("Only the current user can be deleted.") + + return super().destroy(request, *args, **kwargs) + @extend_schema( parameters=[ OpenApiParameter(