Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #14565 - No csrf_token on 404 page.

This solution doesn't have the negative side-effects of [14356].

git-svn-id: http://code.djangoproject.com/svn/django/trunk@14377 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 90ac02300e754bdc1a2658ef21737c28fc522148 1 parent 144ab88
Luke Plant authored October 28, 2010
36  django/middleware/csrf.py
@@ -88,18 +88,22 @@ class CsrfViewMiddleware(object):
88 88
     This middleware should be used in conjunction with the csrf_token template
89 89
     tag.
90 90
     """
  91
+    # The _accept and _reject methods currently only exist for the sake of the
  92
+    # requires_csrf_token decorator.
  93
+    def _accept(self, request):
  94
+        # Avoid checking the request twice by adding a custom attribute to
  95
+        # request.  This will be relevant when both decorator and middleware
  96
+        # are used.
  97
+        request.csrf_processing_done = True
  98
+        return None
  99
+
  100
+    def _reject(self, request, reason):
  101
+        return _get_failure_view()(request, reason=reason)
  102
+
91 103
     def process_view(self, request, callback, callback_args, callback_kwargs):
92 104
         if getattr(request, 'csrf_processing_done', False):
93 105
             return None
94 106
 
95  
-        reject = lambda s: _get_failure_view()(request, reason=s)
96  
-        def accept():
97  
-            # Avoid checking the request twice by adding a custom attribute to
98  
-            # request.  This will be relevant when both decorator and middleware
99  
-            # are used.
100  
-            request.csrf_processing_done = True
101  
-            return None
102  
-
103 107
         # If the user doesn't have a CSRF cookie, generate one and store it in the
104 108
         # request, so it's available to the view.  We'll store it in a cookie when
105 109
         # we reach the response.
@@ -128,7 +132,7 @@ def accept():
128 132
                 # the creation of CSRF cookies, so that everything else continues to
129 133
                 # work exactly the same (e.g. cookies are sent etc), but before the
130 134
                 # any branches that call reject()
131  
-                return accept()
  135
+                return self._accept(request)
132 136
 
133 137
             if request.is_ajax():
134 138
                 # .is_ajax() is based on the presence of X-Requested-With.  In
@@ -153,7 +157,7 @@ def accept():
153 157
                 #      allowing the cross-domain POST request.
154 158
                 #
155 159
                 # So in all cases, it is safe to allow these requests through.
156  
-                return accept()
  160
+                return self._accept(request)
157 161
 
158 162
             if request.is_secure():
159 163
                 # Suppose user visits http://example.com/
@@ -179,7 +183,7 @@ def accept():
179 183
                             'request': request,
180 184
                         }
181 185
                     )
182  
-                    return reject(REASON_NO_REFERER)
  186
+                    return self._reject(request, REASON_NO_REFERER)
183 187
 
184 188
                 # The following check ensures that the referer is HTTPS,
185 189
                 # the domains match and the ports match - the same origin policy.
@@ -192,7 +196,7 @@ def accept():
192 196
                             'request': request,
193 197
                         }
194 198
                     )
195  
-                    return reject(reason)
  199
+                    return self._reject(request, reason)
196 200
 
197 201
             # If the user didn't already have a CSRF cookie, then fall back to
198 202
             # the Django 1.1 method (hash of session ID), so a request is not
@@ -212,7 +216,7 @@ def accept():
212 216
                             'request': request,
213 217
                         }
214 218
                     )
215  
-                    return reject(REASON_NO_COOKIE)
  219
+                    return self._reject(request, REASON_NO_COOKIE)
216 220
             else:
217 221
                 csrf_token = request.META["CSRF_COOKIE"]
218 222
 
@@ -227,7 +231,7 @@ def accept():
227 231
                             'request': request,
228 232
                         }
229 233
                     )
230  
-                    return reject(REASON_NO_CSRF_COOKIE)
  234
+                    return self._reject(request, REASON_NO_CSRF_COOKIE)
231 235
                 else:
232 236
                     logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path),
233 237
                         extra={
@@ -235,9 +239,9 @@ def accept():
235 239
                             'request': request,
236 240
                         }
237 241
                     )
238  
-                    return reject(REASON_BAD_TOKEN)
  242
+                    return self._reject(request, REASON_BAD_TOKEN)
239 243
 
240  
-        return accept()
  244
+        return self._accept(request)
241 245
 
242 246
     def process_response(self, request, response):
243 247
         if getattr(response, 'csrf_processing_done', False):
16  django/views/decorators/csrf.py
@@ -14,6 +14,22 @@
14 14
 using the decorator multiple times, is harmless and efficient.
15 15
 """
16 16
 
  17
+
  18
+class _EnsureCsrfToken(CsrfViewMiddleware):
  19
+    # We need this to behave just like the CsrfViewMiddleware, but not reject
  20
+    # requests.
  21
+    def _reject(self, request, reason):
  22
+        return None
  23
+
  24
+
  25
+requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken)
  26
+requires_csrf_token.__name__ = 'requires_csrf_token'
  27
+csrf_protect.__doc__ = """
  28
+Use this decorator on views that need a correct csrf_token available to
  29
+RequestContext, but without the CSRF protection that csrf_protect
  30
+enforces.
  31
+"""
  32
+
17 33
 def csrf_response_exempt(view_func):
18 34
     """
19 35
     Modifies a view function so that its response is exempt
8  django/views/defaults.py
... ...
@@ -1,6 +1,11 @@
1 1
 from django import http
  2
+from django.views.decorators.csrf import requires_csrf_token
2 3
 from django.template import Context, RequestContext, loader
3 4
 
  5
+
  6
+# This can be called when CsrfViewMiddleware.process_view has not run, therefore
  7
+# need @requires_csrf_token in case the template needs {% csrf_token %}.
  8
+@requires_csrf_token
4 9
 def page_not_found(request, template_name='404.html'):
5 10
     """
6 11
     Default 404 handler.
@@ -13,6 +18,8 @@ def page_not_found(request, template_name='404.html'):
13 18
     t = loader.get_template(template_name) # You need to create a 404.html template.
14 19
     return http.HttpResponseNotFound(t.render(RequestContext(request, {'request_path': request.path})))
15 20
 
  21
+
  22
+@requires_csrf_token
16 23
 def server_error(request, template_name='500.html'):
17 24
     """
18 25
     500 error handler.
@@ -23,6 +30,7 @@ def server_error(request, template_name='500.html'):
23 30
     t = loader.get_template(template_name) # You need to create a 500.html template.
24 31
     return http.HttpResponseServerError(t.render(Context({})))
25 32
 
  33
+
26 34
 def shortcut(request, content_type_id, object_id):
27 35
     # TODO: Remove this in Django 2.0.
28 36
     # This is a legacy view that depends on the contenttypes framework.
10  tests/regressiontests/csrf_tests/tests.py
@@ -4,7 +4,7 @@
4 4
 from django.test import TestCase
5 5
 from django.http import HttpRequest, HttpResponse
6 6
 from django.middleware.csrf import CsrfMiddleware, CsrfViewMiddleware
7  
-from django.views.decorators.csrf import csrf_exempt, csrf_view_exempt
  7
+from django.views.decorators.csrf import csrf_exempt, csrf_view_exempt, requires_csrf_token
8 8
 from django.core.context_processors import csrf
9 9
 from django.contrib.sessions.middleware import SessionMiddleware
10 10
 from django.utils.importlib import import_module
@@ -331,6 +331,14 @@ def test_get_token_for_exempt_view(self):
331 331
         resp = token_view(req)
332 332
         self._check_token_present(resp)
333 333
 
  334
+    def test_get_token_for_requires_csrf_token_view(self):
  335
+        """
  336
+        Check that get_token works for a view decorated solely with requires_csrf_token
  337
+        """
  338
+        req = self._get_GET_csrf_cookie_request()
  339
+        resp = requires_csrf_token(token_view)(req)
  340
+        self._check_token_present(resp)
  341
+
334 342
     def test_token_node_with_new_csrf_cookie(self):
335 343
         """
336 344
         Check that CsrfTokenNode works when a CSRF cookie is created by
17  tests/regressiontests/views/tests/defaults.py
@@ -9,6 +9,8 @@
9 9
 class DefaultsTests(TestCase):
10 10
     """Test django views in django/views/defaults.py"""
11 11
     fixtures = ['testdata.json']
  12
+    non_existing_urls = ['/views/non_existing_url/', # this is in urls.py
  13
+                         '/views/other_non_existing_url/'] # this NOT in urls.py
12 14
 
13 15
     def test_shortcut_with_absolute_url(self):
14 16
         "Can view a shortcut for an Author object that has a get_absolute_url method"
@@ -49,12 +51,21 @@ def test_bad_content_type(self):
49 51
 
50 52
     def test_page_not_found(self):
51 53
         "A 404 status is returned by the page_not_found view"
52  
-        non_existing_urls = ['/views/non_existing_url/', # this is in urls.py
53  
-                             '/views/other_non_existing_url/'] # this NOT in urls.py
54  
-        for url in non_existing_urls:
  54
+        for url in self.non_existing_urls:
55 55
             response = self.client.get(url)
56 56
             self.assertEquals(response.status_code, 404)
57 57
 
  58
+    def test_csrf_token_in_404(self):
  59
+        """
  60
+        The 404 page should have the csrf_token available in the context
  61
+        """
  62
+        # See ticket #14565
  63
+        for url in self.non_existing_urls:
  64
+            response = self.client.get(url)
  65
+            csrf_token = response.context['csrf_token']
  66
+            self.assertNotEqual(str(csrf_token), 'NOTPROVIDED')
  67
+            self.assertNotEqual(str(csrf_token), '')
  68
+
58 69
     def test_server_error(self):
59 70
         "The server_error view raises a 500 status"
60 71
         response = self.client.get('/views/server_error/')

0 notes on commit 90ac023

Please sign in to comment.
Something went wrong with that request. Please try again.