api_views: prevent crash with statistics and old DRF (#49447)

This commit is contained in:
Valentin Deniaud 2020-12-16 14:36:14 +01:00
parent 230cec28eb
commit 511d1d222e
2 changed files with 13 additions and 2 deletions

View File

@ -38,7 +38,7 @@ from django_rbac.utils import get_ou_model, get_role_model
import requests
from requests.exceptions import RequestException
from rest_framework import serializers, pagination
from rest_framework import serializers, pagination, VERSION as drf_version
from rest_framework.validators import UniqueTogetherValidator
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ViewSet
@ -47,7 +47,7 @@ from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import permissions, status, authentication
from rest_framework.exceptions import (PermissionDenied, AuthenticationFailed,
ValidationError)
ValidationError, NotFound)
from rest_framework.fields import CreateOnlyDefault
from authentic2.compat.drf import action
from rest_framework.authentication import SessionAuthentication
@ -1137,6 +1137,11 @@ def stat(**kwargs):
class StatisticsAPI(ViewSet):
permission_classes = (permissions.IsAuthenticated,)
def initial(self, *args, **kwargs):
super().initial(*args, **kwargs)
if drf_version < '3.9':
raise NotFound('Unavailable API (djangorestframework version too low)')
def list(self, request):
statistics = []
ous = [{'id': ou.slug, 'label': ou.name} for ou in get_ou_model().objects.all()]

View File

@ -2219,3 +2219,9 @@ def test_api_statistics(app, admin, freezer, event_type_name, event_name):
'x_labels': ['2020-02', '2020-03'],
'series': [{'label': 'Default organizational unit', 'data': [2, 2]}],
}
def test_api_statistics_no_crash_older_drf(app, admin):
headers = basic_authorization_header(admin)
expected_status = 200 if drf_version > '3.9' else 404
resp = app.get('/api/statistics/login/?time_interval=month', headers=headers, status=expected_status)