diff --git a/django/thunderstore/api/cyberstorm/views/user.py b/django/thunderstore/api/cyberstorm/views/user.py new file mode 100644 index 000000000..be10d1679 --- /dev/null +++ b/django/thunderstore/api/cyberstorm/views/user.py @@ -0,0 +1,47 @@ +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.api.utils import conditional_swagger_auto_schema +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", + ), ]