45 lines
1.8 KiB
Python
45 lines
1.8 KiB
Python
from rest_framework.views import APIView
|
|
from rest_framework.response import Response
|
|
from rest_framework import permissions, status
|
|
from django.http import HttpRequest
|
|
from django.contrib.auth import login
|
|
from rest_framework.authentication import SessionAuthentication
|
|
from django.contrib.auth.models import User
|
|
import re
|
|
|
|
class EditView(APIView):
|
|
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
authentication_classes = (SessionAuthentication,)
|
|
|
|
def get(self, request: HttpRequest):
|
|
return Response({"username": request.user.username})
|
|
|
|
def patch(self, request: HttpRequest):
|
|
data: dict = request.data
|
|
|
|
current_password: str = data.get("current_password")
|
|
if (current_password is None):
|
|
return Response({"current_password": ["This field may not be blank."]})
|
|
|
|
user_object = request.user
|
|
|
|
if (user_object.check_password(current_password) == False):
|
|
return Response({"current_password": ["Password is wrong."]})
|
|
|
|
new_username = data.get("username", user_object.username)
|
|
if (new_username != user_object.username):
|
|
if (User.objects.filter(username=new_username).exists()):
|
|
return Response({"username": ["A user with that username already exists."]})
|
|
if (set(new_username) == {' '}):
|
|
return Response({"username": ["This field may not be blank."]})
|
|
if (re.search('^([a-z]||\@||\+||\-||\_)+$', new_username) is None):
|
|
return Response({"username":["Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters."]})
|
|
|
|
new_password: str = data.get("password")
|
|
if (new_password is not None):
|
|
user_object.set_password(new_password)
|
|
|
|
user_object.save()
|
|
|
|
return Response("data has been alterate") |