From fca812928e901739714ea2dcc9c0335e9b8d96a3 Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Wed, 7 Dec 2016 15:14:22 -0500 Subject: [PATCH] #724: Exempt API views from LoginRequiredMiddleware to enable basic HTTP authentication when LOGIN_REQUIRED is true --- netbox/netbox/settings.py | 2 ++ netbox/utilities/middleware.py | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/netbox/netbox/settings.py b/netbox/netbox/settings.py index 34d856f2e..b479420bd 100644 --- a/netbox/netbox/settings.py +++ b/netbox/netbox/settings.py @@ -185,6 +185,8 @@ SECRETS_MIN_PUBKEY_SIZE = 2048 REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',) } +if LOGIN_REQUIRED: + REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'] = ('rest_framework.permissions.IsAuthenticated',) # Swagger settings (API docs) SWAGGER_SETTINGS = { diff --git a/netbox/utilities/middleware.py b/netbox/utilities/middleware.py index e37c1fcca..2bd25b00c 100644 --- a/netbox/utilities/middleware.py +++ b/netbox/utilities/middleware.py @@ -2,6 +2,7 @@ from django.http import HttpResponseRedirect from django.conf import settings +BASE_PATH = getattr(settings, 'BASE_PATH', False) LOGIN_REQUIRED = getattr(settings, 'LOGIN_REQUIRED', False) @@ -11,5 +12,8 @@ class LoginRequiredMiddleware: """ def process_request(self, request): if LOGIN_REQUIRED and not request.user.is_authenticated(): - if request.path_info != settings.LOGIN_URL: + # Redirect unauthenticated requests to the login page. API requests are exempt from redirection as the API + # performs its own authentication. + api_path = '/{}api/'.format(BASE_PATH) + if not request.path_info.startswith(api_path) and request.path_info != settings.LOGIN_URL: return HttpResponseRedirect('{}?next={}'.format(settings.LOGIN_URL, request.path_info))