from django.contrib.auth import get_user_model
from rest_framework import views, viewsets, permissions
from rest_framework.response import Response

from api import serializers
from webapp import models


class ArticleViewset(viewsets.ModelViewSet):
    queryset = models.Article.objects.all()
    serializer_class = serializers.ArticleSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return []

        return super().get_permissions()


class UserViewset(viewsets.ModelViewSet):
    queryset = get_user_model().objects.all()
    serializer_class = serializers.UserSerializer


class LogoutAPIView(views.APIView):
    permission_classes = []

    def post(self, request, *args, **kwargs):
        user = request.user

        if user.is_authenticated:
            user.auth_token.delete()

        return Response({'status': 'ok'})
