6
6
from django .views .decorators .csrf import csrf_exempt , csrf_view_exempt
7
7
from django .core .context_processors import csrf
8
8
from django .contrib .sessions .middleware import SessionMiddleware
9
- from django .utils .html import escape
10
9
from django .utils .importlib import import_module
11
10
from django .conf import settings
12
11
from django .template import RequestContext , Template
13
12
14
13
# Response/views used for CsrfResponseMiddleware and CsrfViewMiddleware tests
15
14
def post_form_response ():
16
- resp = HttpResponse (content = """
17
- <html><body><form method="post"><input type="text" /></form></body></html>
15
+ resp = HttpResponse (content = u """
16
+ <html><body><h1> \u00a1 Unicode!< form method="post"><input type="text" /></form></body></html>
18
17
""" , mimetype = "text/html" )
19
18
return resp
20
19
@@ -58,8 +57,9 @@ def is_secure(self):
58
57
59
58
class CsrfMiddlewareTest (TestCase ):
60
59
# The csrf token is potentially from an untrusted source, so could have
61
- # characters that need escaping
62
- _csrf_id = "<1>"
60
+ # characters that need dealing with.
61
+ _csrf_id_cookie = "<1>\xc2 \xa1 "
62
+ _csrf_id = "1"
63
63
64
64
# This is a valid session token for this ID and secret key. This was generated using
65
65
# the old code that we're to be backwards-compatible with. Don't use the CSRF code
@@ -74,7 +74,7 @@ def _get_GET_no_csrf_cookie_request(self):
74
74
75
75
def _get_GET_csrf_cookie_request (self ):
76
76
req = TestingHttpRequest ()
77
- req .COOKIES [settings .CSRF_COOKIE_NAME ] = self ._csrf_id
77
+ req .COOKIES [settings .CSRF_COOKIE_NAME ] = self ._csrf_id_cookie
78
78
return req
79
79
80
80
def _get_POST_csrf_cookie_request (self ):
@@ -104,7 +104,7 @@ def _get_POST_session_request_no_token(self):
104
104
return req
105
105
106
106
def _check_token_present (self , response , csrf_id = None ):
107
- self .assertContains (response , "name='csrfmiddlewaretoken' value='%s'" % escape (csrf_id or self ._csrf_id ))
107
+ self .assertContains (response , "name='csrfmiddlewaretoken' value='%s'" % (csrf_id or self ._csrf_id ))
108
108
109
109
# Check the post processing and outgoing cookie
110
110
def test_process_response_no_csrf_cookie (self ):
@@ -290,6 +290,17 @@ def test_token_node_no_csrf_cookie(self):
290
290
resp = token_view (req )
291
291
self .assertEquals (u"" , resp .content )
292
292
293
+ def test_token_node_empty_csrf_cookie (self ):
294
+ """
295
+ Check that we get a new token if the csrf_cookie is the empty string
296
+ """
297
+ req = self ._get_GET_no_csrf_cookie_request ()
298
+ req .COOKIES [settings .CSRF_COOKIE_NAME ] = ""
299
+ CsrfViewMiddleware ().process_view (req , token_view , (), {})
300
+ resp = token_view (req )
301
+
302
+ self .assertNotEqual (u"" , resp .content )
303
+
293
304
def test_token_node_with_csrf_cookie (self ):
294
305
"""
295
306
Check that CsrfTokenNode works when a CSRF cookie is set
0 commit comments