From 151f2cae6f9dd48a54a8d1e0f61758b62fab9307 Mon Sep 17 00:00:00 2001 From: Oliver Date: Thu, 12 May 2022 10:45:30 +1000 Subject: [PATCH] Do not redirect requests for media / static / api / js files - For these paths, just return a 401 - This is necessary to stop unauthorized calls to the API or to request media files from redirecting to the login page --- InvenTree/InvenTree/middleware.py | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/InvenTree/InvenTree/middleware.py b/InvenTree/InvenTree/middleware.py index 91cfefc6d6..b6550379e2 100644 --- a/InvenTree/InvenTree/middleware.py +++ b/InvenTree/InvenTree/middleware.py @@ -1,9 +1,12 @@ -from django.shortcuts import HttpResponseRedirect -from django.urls import reverse_lazy, Resolver404 -from django.shortcuts import redirect -from django.urls import include, re_path +# -*- coding: utf-8 -*- + from django.conf import settings from django.contrib.auth.middleware import PersistentRemoteUserMiddleware +from django.http import HttpResponse +from django.shortcuts import HttpResponseRedirect +from django.shortcuts import redirect +from django.urls import reverse_lazy, Resolver404 +from django.urls import include, re_path import logging @@ -82,11 +85,23 @@ class AuthRequiredMiddleware(object): reverse_lazy('admin:logout'), ] - if path not in urls and not path.startswith('/api/'): + # Do not redirect requests to any of these paths + paths_ignore = [ + '/api/', + '/js/', + '/media/', + '/static/', + ] + + if path not in urls and not any([path.startswith(p) for p in paths_ignore]): # Save the 'next' parameter to pass through to the login view return redirect('{}?next={}'.format(reverse_lazy('account_login'), request.path)) + else: + # Return a 401 (Unauthorized) response code for this request + return HttpResponse('Unauthorized', status=401) + response = self.get_response(request) return response