Django

Code

Changeset 2900

Show
Ignore:
Timestamp:
05/11/06 17:32:47 (2 years ago)
Author:
lukeplant
Message:

Fixed CsrfMiddleware? post processing so that it in the presence of multiple
POST <form>s, only one <input> tag is added with an id, for HTML validity.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/contrib/csrf/middleware.py

    r2899 r2900  
    1010import md5 
    1111import re 
     12import itertools 
    1213 
    1314_ERROR_MSG = "<h1>403 Forbidden</h1><p>Cross Site Request Forgery detected.  Request aborted.</p>" 
     
    2021def _make_token(session_id): 
    2122    return md5.new(settings.SECRET_KEY + session_id).hexdigest() 
    22      
     23 
    2324class CsrfMiddleware(object): 
    2425    """Django middleware that adds protection against Cross Site 
     
    5859                 
    5960        return None 
    60          
     61 
    6162    def process_response(self, request, response): 
    6263        csrf_token = None 
     
    7576             
    7677        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 
    7990            # 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) 
    8492        return response