from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth import authenticate from .serializers import UserSerializer, LoginSerializer from rest_framework.permissions import AllowAny class SignUpView(APIView): permission_classes = [AllowAny] """ User sign-up view """ def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() # Generate tokens for the new user refresh = RefreshToken.for_user(user) return Response({ "message": "User created successfully", "refresh": str(refresh), "access": str(refresh.access_token), }, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class SignInView(APIView): permission_classes = [AllowAny] """ User sign-in view """ def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): email = serializer.validated_data['email'] password = serializer.validated_data['password'] user = authenticate(email=email, password=password) if user: refresh = RefreshToken.for_user(user) return Response({ "refresh": str(refresh), "access": str(refresh.access_token), }, status=status.HTTP_200_OK) return Response({"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)