diff --git a/docs/release-notes/version-2.11.md b/docs/release-notes/version-2.11.md index 6a8af102f..451f07a99 100644 --- a/docs/release-notes/version-2.11.md +++ b/docs/release-notes/version-2.11.md @@ -15,6 +15,7 @@ * [#6426](https://github.com/netbox-community/netbox/issues/6426) - Allow assigning virtual chassis member interfaces to LAG on VC master * [#6438](https://github.com/netbox-community/netbox/issues/6438) - Fix missing descriptions and label for device type imports and exports * [#6465](https://github.com/netbox-community/netbox/issues/6465) - Fix typo in installed plugins REST API endpoint +* [#6467](https://github.com/netbox-community/netbox/issues/6467) - Fix access to metrics on custom `BASE_PATH` when login is required * [#6468](https://github.com/netbox-community/netbox/issues/6468) - Disable ordering VLAN groups list by scope object --- diff --git a/netbox/netbox/middleware.py b/netbox/netbox/middleware.py index 1395cbd1f..d3b3dae40 100644 --- a/netbox/netbox/middleware.py +++ b/netbox/netbox/middleware.py @@ -20,17 +20,20 @@ class LoginRequiredMiddleware(object): self.get_response = get_response def __call__(self, request): + # Redirect unauthenticated requests (except those exempted) to the login page if LOGIN_REQUIRED is true if settings.LOGIN_REQUIRED and not request.user.is_authenticated: - # Redirect unauthenticated requests to the login page. API requests are exempt from redirection as the API - # performs its own authentication. Also metrics can be read without login. - api_path = reverse('api-root') - if not request.path_info.startswith((api_path, '/metrics')) and request.path_info != settings.LOGIN_URL: - return HttpResponseRedirect( - '{}?next={}'.format( - settings.LOGIN_URL, - parse.quote(request.get_full_path_info()) - ) - ) + # Determine exempt paths + exempt_paths = [ + reverse('api-root') + ] + if settings.METRICS_ENABLED: + exempt_paths.append(reverse('prometheus-django-metrics')) + + # Redirect unauthenticated requests + if not request.path_info.startswith(tuple(exempt_paths)) and request.path_info != settings.LOGIN_URL: + login_url = f'{settings.LOGIN_URL}?next={parse.quote(request.get_full_path_info())}' + return HttpResponseRedirect(login_url) + return self.get_response(request)