2015-01-28 20:35:27 +08:00
|
|
|
from django.conf import settings
|
2017-02-25 14:48:20 +08:00
|
|
|
from django.http import HttpResponse
|
2015-11-07 23:12:37 +08:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2013-05-18 23:43:21 +08:00
|
|
|
|
2018-04-09 01:35:24 +08:00
|
|
|
from .utils import get_view_name
|
|
|
|
|
2013-10-31 23:42:28 +08:00
|
|
|
|
2015-11-07 23:12:37 +08:00
|
|
|
class XViewMiddleware(MiddlewareMixin):
|
2013-05-18 23:43:21 +08:00
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Add an X-View header to internal HEAD requests.
|
2013-05-18 23:43:21 +08:00
|
|
|
"""
|
|
|
|
def process_view(self, request, view_func, view_args, view_kwargs):
|
|
|
|
"""
|
|
|
|
If the request method is HEAD and either the IP is internal or the
|
2019-10-22 20:30:52 +08:00
|
|
|
user is a logged-in staff member, return a response with an x-view
|
2017-01-25 04:31:57 +08:00
|
|
|
header indicating the view function. This is used to lookup the view
|
|
|
|
function for an arbitrary page.
|
2013-05-18 23:43:21 +08:00
|
|
|
"""
|
|
|
|
assert hasattr(request, 'user'), (
|
|
|
|
"The XView middleware requires authentication middleware to be "
|
2019-10-22 19:01:14 +08:00
|
|
|
"installed. Edit your MIDDLEWARE setting to insert "
|
|
|
|
"'django.contrib.auth.middleware.AuthenticationMiddleware'."
|
2015-11-07 23:12:37 +08:00
|
|
|
)
|
2013-05-18 23:43:21 +08:00
|
|
|
if request.method == 'HEAD' and (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS or
|
|
|
|
(request.user.is_active and request.user.is_staff)):
|
2017-02-25 14:48:20 +08:00
|
|
|
response = HttpResponse()
|
2018-04-09 01:35:24 +08:00
|
|
|
response['X-View'] = get_view_name(view_func)
|
2013-05-18 23:43:21 +08:00
|
|
|
return response
|