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
This commit is contained in:
Oliver 2022-05-12 10:45:30 +10:00
parent 2652c75bda
commit 151f2cae6f

View File

@ -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