Coverage for netbox/graphql/views.py: 32%

28 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 18:35 +0000

1from django.conf import settings 

2from django.contrib.auth.views import redirect_to_login 

3from django.http import HttpResponseForbidden, HttpResponseNotFound 

4from django.urls import reverse 

5from django.views.decorators.csrf import csrf_exempt 

6from rest_framework.exceptions import AuthenticationFailed 

7from strawberry.django.views import GraphQLView 

8 

9from netbox.api.authentication import TokenAuthentication 

10from netbox.config import get_config 

11 

12 

13class NetBoxGraphQLView(GraphQLView): 

14 """ 

15 Extends strawberry's GraphQLView to support DRF's token-based authentication. 

16 """ 

17 

18 @csrf_exempt 

19 def dispatch(self, request, *args, **kwargs): 

20 config = get_config() 

21 

22 # Enforce GRAPHQL_ENABLED 

23 if not config.GRAPHQL_ENABLED: 

24 return HttpResponseNotFound("The GraphQL API is not enabled.") 

25 

26 # Attempt to authenticate the user using a DRF token, if provided 

27 if not request.user.is_authenticated: 

28 authenticator = TokenAuthentication() 

29 try: 

30 auth_info = authenticator.authenticate(request) 

31 if auth_info is not None: 

32 request.user = auth_info[0] # User object 

33 except AuthenticationFailed as exc: 

34 return HttpResponseForbidden(exc.detail) 

35 

36 # Enforce LOGIN_REQUIRED 

37 if settings.LOGIN_REQUIRED and not request.user.is_authenticated: 

38 if request.accepts("text/html"): 

39 return redirect_to_login(reverse('graphql')) 

40 return HttpResponseForbidden("No credentials provided.") 

41 

42 return super().dispatch(request, *args, **kwargs)