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 | import random
from django.http import HttpResponseRedirect
from django.conf import settings
extensions = (
".do",
".pl",
".py",
".asp",
".cfm",
".cgi",
".dll",
".htm",
".jsp",
".xml",
".exe",
".php",
".aspx",
".html",
".php3",
".php4",
".shtml",
".action",
)
indexes = (
"/index",
"/main",
)
class RandomFileExtensionMiddleware(object):
"""
A middleware that replaces the request path automatically with a random
file extension to make you feel nostalgic for old crufty URLs. This
will respect settings.APPEND_SLASH when it converts the request path back
to normal.
"""
def _is_valid_extension(self, path):
for i, ext in enumerate(extensions):
if path.endswith(ext):
return True
return False
def _is_valid_index(self, path):
for i, index in enumerate(indexes):
if path.startswith(index):
return True
return False
def process_request(self, request):
if request.path == "/":
request.path = random.choice(indexes) + random.choice(extensions)
return HttpResponseRedirect(request.build_absolute_uri())
elif request.path.endswith("/"):
request.path = request.path[:-1] + random.choice(extensions)
return HttpResponseRedirect(request.build_absolute_uri())
elif self._is_valid_extension(request.path):
if self._is_valid_index(request.path):
request.path = "/"
else:
path = request.path.split("/")
path[-1] = "".join(path[-1].split(".")[:-1])
if settings.APPEND_SLASH:
path[-1] = path[-1] + '/'
request.path = "/".join(path)
|
Comments