Newer
Older
GestionHoteleriaApi / apps / user / views.py
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import Group
from requests import Response
from rest_framework import viewsets, permissions, status
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.views import APIView

from apps.user.models import Gender, User, Region
from apps.user.serializer import GenderSerializer, UserSerializer, GroupSerializer, RegionSerializer2


class GenderViewSet(viewsets.ModelViewSet):
    queryset = Gender.objects.all()
    serializer_class = GenderSerializer


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


class RegionViewSet(viewsets.ModelViewSet):
    queryset = Region.objects.filter(govern=None)
    serializer_class = RegionSerializer2
    permission_classes = [permissions.AllowAny]


class RegionGovernViewSet(viewsets.ModelViewSet):
    queryset = Region.objects.all()
    serializer_class = RegionSerializer2
    permission_classes = [permissions.AllowAny]


class CustomAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'user_id': user.pk,
            'groups': [u.id for u in user.groups.all()]
        })


class Logout(APIView):
    # permission_classes = [permissions.IsAuthenticated]

    @staticmethod
    def post(request):
        request.user.auth_token.delete()
        return Response(status=status.HTTP_200_OK)