from rest_framework import viewsets, permissions, status from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from django.contrib.auth import authenticate from rest_framework_simplejwt.tokens import RefreshToken from .models import Todo from .serializers import TodoSerializer, UserSerializer import logging logger = logging.getLogger(__name__) @api_view(['POST']) @permission_classes([permissions.AllowAny]) def register_user(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() refresh = RefreshToken.for_user(user) return Response({ 'token': str(refresh.access_token), }) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) @permission_classes([permissions.AllowAny]) def login_user(request): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user: refresh = RefreshToken.for_user(user) return Response({ 'token': str(refresh.access_token), }) return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) class TodoViewSet(viewsets.ModelViewSet): serializer_class = TodoSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): print(f"user query: {self.request.user.username}") logger.info(f"query by user: {self.request.user.username}") return Todo.objects.filter(user=self.request.user) def perform_create(self, serializer): todo = serializer.save(user=self.request.user) serializer.save(user=self.request.user) print(f"New todo added - Title: '{todo.title}' by user: {self.request.user.username}") logger.info(f"New todo added - Title: '{todo.title}' by user: {self.request.user.username}")