from django.shortcuts import render # Create your views here. from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework import status from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth import get_user_model, authenticate from .serializers import RegisterSerializer, UserProfileSerializer User = get_user_model() class RegisterView(APIView): """POST /api/register — creates a new user and returns JWT tokens""" permission_classes = [AllowAny] def post(self, request): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() refresh = RefreshToken.for_user(user) return Response({ 'user': UserProfileSerializer(user).data, 'access': str(refresh.access_token), 'refresh': str(refresh), }, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LoginView(APIView): """POST /api/login — validates credentials and returns JWT tokens""" permission_classes = [AllowAny] def post(self, request): email = request.data.get('email') password = request.data.get('password') if not email or not password: return Response( {'error': 'Email and password are required'}, status=status.HTTP_400_BAD_REQUEST ) user = authenticate(request, username=email, password=password) if user is None: return Response( {'error': 'Invalid email or password'}, status=status.HTTP_401_UNAUTHORIZED ) refresh = RefreshToken.for_user(user) return Response({ 'user': UserProfileSerializer(user).data, 'access': str(refresh.access_token), 'refresh': str(refresh), }) class ProfileView(APIView): """GET /api/profile — returns the logged in user's profile""" permission_classes = [IsAuthenticated] def get(self, request): serializer = UserProfileSerializer(request.user) return Response(serializer.data)