Changeset 2900
- Timestamp:
- 05/11/06 17:32:47 (2 years ago)
- Files:
-
- django/trunk/django/contrib/csrf/middleware.py (modified) (4 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/trunk/django/contrib/csrf/middleware.py
r2899 r2900 10 10 import md5 11 11 import re 12 import itertools 12 13 13 14 _ERROR_MSG = "<h1>403 Forbidden</h1><p>Cross Site Request Forgery detected. Request aborted.</p>" … … 20 21 def _make_token(session_id): 21 22 return md5.new(settings.SECRET_KEY + session_id).hexdigest() 22 23 23 24 class CsrfMiddleware(object): 24 25 """Django middleware that adds protection against Cross Site … … 58 59 59 60 return None 60 61 61 62 def process_response(self, request, response): 62 63 csrf_token = None … … 75 76 76 77 if csrf_token is not None and \ 77 response['Content-Type'].split(';')[0] in _HTML_TYPES: 78 78 response['Content-Type'].split(';')[0] in _HTML_TYPES: 79 80 # ensure we don't add the 'id' attribute twice (HTML validity) 81 idattributes = itertools.chain(("id='csrfmiddlewaretoken'",), 82 itertools.repeat('')) 83 def add_csrf_field(match): 84 """Returns the matched <form> tag plus the added <input> element""" 85 return match.group() + "<div style='display:none;'>" + \ 86 "<input type='hidden' " + idattributes.next() + \ 87 " name='csrfmiddlewaretoken' value='" + csrf_token + \ 88 "' /></div>" 89 79 90 # Modify any POST forms 80 extra_field = "<div style='display:none;'>" + \ 81 "<input type='hidden' id='csrfmiddlewaretoken' name='csrfmiddlewaretoken' value='" + \ 82 csrf_token + "' /></div>" 83 response.content = _POST_FORM_RE.sub('\\1' + extra_field, response.content) 91 response.content = _POST_FORM_RE.sub(add_csrf_field, response.content) 84 92 return response
