api.py 2.24 KB
import requests
from rest_framework.response import Response
from rest_framework.decorators import api_view

from django.conf import settings

import datetime

from actstream.models import actor_stream
from actstream.models import Action
from django.http import Http404
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework_json_api.views import ReadOnlyModelViewSet

from core.permissions import CustomModelPermissions
from core.serializers import ActionSerializer
from usuario.models import Usuario


@api_view(['POST'])
def recaptcha(request):
    r = requests.post(
        'https://www.google.com/recaptcha/api/siteverify',
        data={
            'secret': settings.SECRET_KEY_CAPTCHA,
            'response': request.data['captcha_value'],
        }
    )

    return Response({'captcha': r.json()})


class AuditoriaViewSet(ReadOnlyModelViewSet):
    queryset = Action.objects.all()
    permission_classes = (IsAuthenticated, CustomModelPermissions)
    serializer_class = ActionSerializer
    filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
    ordering = '-timestamp'

    def get_queryset(self):
        queryset = super().get_queryset()

        if not self.action == 'list':
            return queryset

        # en el caso de que la accion sea listar, controlar que se filtre por fecha obligatoriamente
        usuario_id = self.request.GET.get('usuario_id', None)
        fecha_desde = self.request.GET.get('fecha_desde', None)
        fecha_hasta = self.request.GET.get('fecha_hasta', None)

        if not fecha_desde:
            return queryset.none()

        if not fecha_hasta or fecha_hasta < fecha_desde:
            fecha_hasta = datetime.datetime.now()

        if usuario_id:
            try:
                usuario = get_object_or_404(Usuario, id=usuario_id)
                queryset = usuario.actor_actions.public(timestamp__date__range=(fecha_desde, fecha_hasta))
            except Http404:
                return queryset.none()
        else:
            queryset = Action.objects.public(timestamp__date__range=(fecha_desde, fecha_hasta))

        return queryset