-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware.py
45 lines (35 loc) · 1.11 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
# Enabling this middleware you can force browsers with good SSL support to use
# HTTPS, while making it optional for other legacy applications with limited or
# no SSL support.
from django.http import HttpResponseRedirect
from django.conf import settings
import re
browser_strings = [
'Firefox',
'Iceweasel',
'Chrome',
'Opera',
'Trident',
'Safari',
'Konqueror',
]
re_http = re.compile(r'^http:')
def is_a_browser(user_agent):
return any(browser in user_agent
for browser in browser_strings)
class ForceHTTPSOnBrowsersMiddleware(object):
def process_request(self, request):
# Disable on DEBUG
if settings.DEBUG:
return
# Skip if the request is already HTTPS
if request.is_secure():
return
# Only redirect GET requests
if request.method != 'GET':
return
user_agent = request.META.get('HTTP_USER_AGENT', '')
if is_a_browser(user_agent):
url = request.build_absolute_uri()
url = re_http.sub('https:', url)
return HttpResponseRedirect(url)