-
Notifications
You must be signed in to change notification settings - Fork 118
/
middleware.py
188 lines (161 loc) · 7.97 KB
/
middleware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import random
import re
import json
from django.http import HttpResponseRedirect
from django.template import loader, RequestContext
from django.utils.encoding import force_text
from django.utils.html import escape
from django.utils.six.moves.urllib_parse import unquote
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from fiber.app_settings import LOGIN_STRING, EXCLUDE_URLS, EDITOR, PERMISSION_CLASS
from fiber.models import ContentItem, Page
from fiber.utils.import_util import import_element, load_class
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
perms = load_class(PERMISSION_CLASS)
def is_html(response):
"""
Returns True if the response is either `text/html` or `application/xhtml+xml`
"""
content_type = response.get('Content-Type', None)
return bool(content_type and content_type.split(';')[0] in ('text/html', 'application/xhtml+xml'))
class AdminPageMiddleware(MiddlewareMixin):
LOGIN_SESSION_KEY = 'show_fiber_login'
body_re = re.compile(
r'<head>(?P<HEAD>.*)</head>(?P<AFTER_HEAD>.*)<body(?P<BODY_ATTRS>.*?)>(?P<BODY>.*)</body>',
re.DOTALL)
def __init__(self, *args, **kwargs):
super(AdminPageMiddleware, self).__init__(*args, **kwargs)
self.editor_settings = import_element(EDITOR)
def process_response(self, request, response):
# only process non-streaming html and xhtml responses
if is_html(response) and hasattr(response, 'content'):
if self.should_setup_login_session(request):
return self.setup_login_session(request)
if self.show_login(request) or self.show_admin(request, response):
return self.modify_response(request, response)
return response
def should_setup_login_session(self, request):
"""
Only set self.LOGIN_SESSION_KEY in the session when the request
- has LOGIN_STRING (defaults to @fiber) behind its request-url
"""
qs = unquote(request.META.get('QUERY_STRING', ''))
return request.path_info.endswith(LOGIN_STRING) or qs.endswith(LOGIN_STRING)
def setup_login_session(self, request):
"""
Add self.LOGIN_SESSION_KEY to the session and redirect to the the requested path without LOGIN_STRING
"""
request.session[self.LOGIN_SESSION_KEY] = True
url = request.path_info.replace(LOGIN_STRING, '')
qs = unquote(request.META.get('QUERY_STRING', ''))
if qs:
qs = '?%s' % qs.replace(LOGIN_STRING, '').rstrip('&')
return HttpResponseRedirect(''.join([url, qs]))
def show_login(self, request):
"""
Only show the Fiber login interface when the request
- is NOT performed by an admin user
- has session key self.LOGIN_SESSION_KEY = True
"""
return (not (hasattr(request, 'user') and request.user.is_staff) and
(hasattr(request, 'session') and request.session.get(self.LOGIN_SESSION_KEY)))
def show_admin(self, request, response):
"""
Only show the Fiber admin interface when the request
- is not an AJAX request
- has a response status code of 200
- is performed by an admin user
- has a user with sufficient permissions based on the Permission Class
- does not match EXCLUDE_URLS (empty by default)
"""
if request.is_ajax() or response.status_code != 200:
return False
if (hasattr(request, 'user') and request.user.is_staff) and perms.is_fiber_editor(request.user):
if EXCLUDE_URLS:
url = request.path_info.lstrip('/')
for exclude_url in EXCLUDE_URLS:
if re.search(exclude_url, url):
return False
return True
return False
def modify_response(self, request, response):
"""
Modify the response to include Fiber assets and data.
"""
fiber_data = {}
replacement = r'<head>\g<HEAD>%(header_html)s</head>\g<AFTER_HEAD><body data-fiber-data="%(fiber_data)s"\g<BODY_ATTRS>>\g<BODY></body>'
content = force_text(response.content)
if self.show_login(request):
# Only show the login window once
request.session[self.LOGIN_SESSION_KEY] = False
fiber_data['show_login'] = True
elif self.show_admin(request, response):
if self.is_django_admin(request):
fiber_data['backend'] = True
else:
fiber_data['frontend'] = True
page = Page.objects.get_by_url(request.path_info)
if page:
fiber_data['page_id'] = page.pk
# Inject admin html in body, wrap the original body content in a div.
replacement = r'<head>\g<HEAD>%(header_html)s</head>\g<AFTER_HEAD><body data-fiber-data="%(fiber_data)s"\g<BODY_ATTRS>><div id="wpr-body">\g<BODY></body>'
content = content.replace('</body>', '</div>%s</body>' % self.get_body_html(request))
# Inject header html in head.
# Add fiber-data attribute to body tag.
replacement = replacement % {
'header_html': self.get_header_html(request),
'fiber_data': escape(json.dumps(fiber_data, sort_keys=True))
}
response.content = self.body_re.sub(replacement, content)
if response.has_header('Content-Length'):
# Reset 'Content-Length' header (usually set by CommonMiddleware)
# to make sure clients read the full response body
response['Content-Length'] = str(len(response.content))
return response
def is_django_admin(self, request):
return request.path_info.startswith(reverse('admin:index'))
def get_header_html(self, request):
context = {
'editor_template_js': self.editor_settings.get('template_js'),
'editor_template_css': self.editor_settings.get('template_css'),
'BACKEND_BASE_URL': reverse('admin:index'),
'FIBER_LOGIN_URL': reverse('fiber_login'),
}
return loader.render_to_string('fiber/header.html', context, request=request)
def get_body_html(self, request):
context = {
'logout_url': self.get_logout_url(request)
}
return loader.render_to_string('fiber/admin.html', context, request=request)
def get_logout_url(self, request):
if request.META['QUERY_STRING']:
return '%s?next=%s?%s' % (reverse('admin:logout'), request.path_info, request.META['QUERY_STRING'])
else:
return '%s?next=%s' % (reverse('admin:logout'), request.path_info)
class ObfuscateEmailAddressMiddleware(MiddlewareMixin):
"""
Replaces plain email addresses with escaped addresses in (non streaming) HTML responses
"""
def process_response(self, request, response):
if is_html(response) and hasattr(response, 'content'): # Do not obfuscate non-html and streaming responses.
# http://www.lampdocs.com/blog/2008/10/regular-expression-to-extract-all-e-mail-addresses-from-a-file-with-php/
email_pattern = re.compile(
r'\b(?P<email>(mailto:)?[\w-]+(\.[\w-]+)*(\+[\w-]+)?@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]+)))\b')
response.content = email_pattern.sub(self.replace_email, force_text(response.content))
if response.has_header('Content-Length'):
# Reset 'Content-Length' header (usually set by CommonMiddleware)
# to make sure clients read the full response body
response['Content-Length'] = str(len(response.content))
return response
def replace_email(self, matches):
email = matches.group('email')
return matches.group().replace(email, self.encode_email(email))
def encode_email(self, email):
formats = '&#{:d};', '&#x{:x};'
return ''.join(random.choice(formats).format(ord(c)) for c in email)