61 lines
2.3 KiB
Python
61 lines
2.3 KiB
Python
# main/views.py
|
|
from django.contrib.auth import authenticate, login, logout
|
|
from rest_framework import status
|
|
# from rest_framework.views import APIView
|
|
from rest_framework.generics import GenericAPIView
|
|
from rest_framework.response import Response
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
from django.contrib.auth.models import User
|
|
from rest_framework.authtoken.models import Token
|
|
from rest_framework.permissions import AllowAny, IsAuthenticated
|
|
from rest_framework.authentication import TokenAuthentication
|
|
from rest_framework_simplejwt.authentication import JWTAuthentication
|
|
from rest_framework_simplejwt.tokens import RefreshToken
|
|
from .serializers import *
|
|
|
|
|
|
class UserRegistrationView(GenericAPIView):
|
|
permission_classes = (AllowAny,)
|
|
serializer_class = UserRegistrationSerializer
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
serializer = UserRegistrationSerializer(data=request.data)
|
|
serializer.is_valid(raise_exception=True)
|
|
user = serializer.save()
|
|
token = RefreshToken.for_user(user)
|
|
data = serializer.data
|
|
|
|
data["tokens"] = {"refresh": str(token),
|
|
"access": str(token.access_token)}
|
|
return Response(data, status=status.HTTP_201_CREATED)
|
|
|
|
|
|
class UserLoginView(GenericAPIView):
|
|
permission_classes = (AllowAny,)
|
|
serializer_class = UserLoginSerializer
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
serializer = self.get_serializer(data=request.data)
|
|
serializer.is_valid(raise_exception=True)
|
|
user = serializer.validated_data
|
|
serializer = CustomUserSerializer(user)
|
|
token = RefreshToken.for_user(user)
|
|
data = serializer.data
|
|
data["tokens"] = {"refresh": str(token),
|
|
"access": str(token.access_token)}
|
|
return Response(data, status=status.HTTP_200_OK)
|
|
|
|
|
|
class UserLogoutView(GenericAPIView):
|
|
permission_classes = (IsAuthenticated,)
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
try:
|
|
refresh_token = request.data("refresh")
|
|
token = RefreshToken(refresh_token)
|
|
token.blacklist()
|
|
return Response(status=status.HTTP_205_RESET_CONTENT)
|
|
except Exception as e:
|
|
print(e)
|
|
return Response(status=status.HTTP_400_BAD_REQUEST)
|