core: use rest_framework in accounts

This commit is contained in:
2023-11-11 19:50:14 +01:00
parent eb8789aa1d
commit a7d9471d59
23 changed files with 155 additions and 245 deletions

View File

@ -1,29 +1,25 @@
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse, HttpResponse, HttpRequest
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
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from ..forms.change_password import ChangePasswordForm
from ..status_code import *
from ..serializers.change_password import ChangePasswordSerializer
class ChangePasswordView(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
class ChangePasswordView(View):
def get(self, request: HttpRequest):
return render(request, "change_password.html", ChangePasswordForm)
@method_decorator(login_required, name='dispatch')
def post(self, request: HttpRequest):
data = request.POST
form: ChangePasswordForm = ChangePasswordForm(request.POST)
if not form.is_valid():
return JsonResponse(form.errors)
new_password: str = form.cleaned_data['new_password']
user: User = request.user
user.set_password(new_password)
user.save()
return HttpResponse(USER_PASSWORD_UPDATED)
serializer = ChangePasswordSerializer(data=data)
if serializer.is_valid(raise_exception=True):
user: User = request.user
if (user.check_password(data['current_password']) == 0):
return Response({'current_password': "The password is not right."}, status=status.HTTP_200_OK)
user.set_password(data["new_password"])
return Response('password changed', status=status.HTTP_200_OK)