From 4f2cfa1f117c1e56e0bf0d95b7c0d10b3d789e7e Mon Sep 17 00:00:00 2001 From: Oksamies Date: Fri, 8 Dec 2023 20:16:45 +0200 Subject: [PATCH] Add UserDeleteView --- .../thunderstore/api/cyberstorm/views/user.py | 46 +++++++++++++++++++ django/thunderstore/api/urls.py | 6 +++ 2 files changed, 52 insertions(+) create mode 100644 django/thunderstore/api/cyberstorm/views/user.py diff --git a/django/thunderstore/api/cyberstorm/views/user.py b/django/thunderstore/api/cyberstorm/views/user.py new file mode 100644 index 000000000..8fbf665bb --- /dev/null +++ b/django/thunderstore/api/cyberstorm/views/user.py @@ -0,0 +1,46 @@ +from django.contrib.auth import get_user_model +from rest_framework import serializers +from rest_framework.exceptions import PermissionDenied, ValidationError +from rest_framework.response import Response +from rest_framework.views import APIView + +from thunderstore.social.views import DeleteAccountForm + +User = get_user_model() + + +class CyberstormUserDeleteRequestSerialiazer(serializers.Serializer): + verification = serializers.CharField( + max_length=User._meta.get_field("username").max_length + ) + + +class CyberstormUserDeleteResponseSerialiazer(serializers.Serializer): + username = serializers.CharField() + + +class UserDeleteAPIView(APIView): + @conditional_swagger_auto_schema( + request_body=CyberstormUserDeleteRequestSerialiazer, + responses={200: CyberstormUserDeleteResponseSerialiazer}, + operation_id="cyberstorm.user.delete", + tags=["cyberstorm"], + ) + def post(self, request, username, format=None): + serializer = CyberstormUserDeleteRequestSerialiazer(data=request.data) + serializer.is_valid(raise_exception=True) + if request.user.username != username: + raise PermissionDenied("You can only delete your own account") + form = DeleteAccountForm( + user=request.user, + data=request.data, + ) + if form.is_valid(): + request.user.delete() + return Response( + CyberstormUserDeleteResponseSerialiazer( + {"username": request.user.username} + ).data + ) + else: + raise ValidationError(form.errors) diff --git a/django/thunderstore/api/urls.py b/django/thunderstore/api/urls.py index 5b777b6f6..c091e512b 100644 --- a/django/thunderstore/api/urls.py +++ b/django/thunderstore/api/urls.py @@ -11,6 +11,7 @@ TeamMembersAPIView, TeamServiceAccountsAPIView, ) +from thunderstore.api.cyberstorm.views.user import UserDeleteAPIView cyberstorm_urls = [ path( @@ -58,4 +59,9 @@ TeamServiceAccountsAPIView.as_view(), name="cyberstorm.team.service-accounts", ), + path( + "user//delete/", + UserDeleteAPIView.as_view(), + name="cyberstorm.user.delete", + ), ]