api.py 2.13 KB
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import mixins, viewsets, status, filters
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response

from core.permissions import CustomModelPermissions
from usuario.models import Usuario
from usuario.serializers import UsuarioSerializer, CambiarClaveSecretaSerializer, UsuarioListaSerializer
from usuario.filters import UsuarioFilter


class UsuarioViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin,
                     viewsets.GenericViewSet):
    queryset = Usuario.objects.all()
    permission_classes = (IsAuthenticated,)
    serializer_class = UsuarioSerializer
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    filterset_class = UsuarioFilter
    ordering_fields = ('last_name', 'first_name', 'cuil')
    ordering = ('last_name',)

    def get_object(self, base_method=False):
        user = self.request.user
        if base_method:
            user = super().get_object()

        return user

    def get_serializer_class(self):
        if self.action == 'list':
            return UsuarioListaSerializer

        return self.serializer_class

    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        permission_classes = self.permission_classes
        if self.action == 'list':
            permission_classes = [CustomModelPermissions]

        return [permission() for permission in permission_classes]

    @action(
        methods=('patch',),
        detail=False,
        url_path='cambiar-clave-secreta',
        parser_classes=(JSONParser,),
        serializer_class=CambiarClaveSecretaSerializer
    )
    def cambiar_clave_secreta(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_200_OK)