Ticket #15493: csrf_migration_helper_parsing.diff

File csrf_migration_helper_parsing.diff, 2.1 KB (added by John Hensley, 13 years ago)

Patch to find the CSRF token anywhere in the form.

  • extras/csrf_migration_helper.py

    diff --git a/extras/csrf_migration_helper.py b/extras/csrf_migration_helper.py
    index 6416193..6aaf6b4 100644
    a b  
    4141#   loaders are out of the picture, because there is no way to ask them to
    4242#   return all templates.
    4343#
    44 # - If you put the {% csrf_token %} tag on the same line as the <form> tag it
    45 #   will be detected, otherwise it will be assumed that the form does not have
    46 #   the token.
    47 #
    4844# - It's impossible to programmatically determine which forms should and should
    4945#   not have the token added.  The developer must decide when to do this,
    5046#   ensuring that the token is only added to internally targetted forms.
    python csrf_migration_helper.py [--settings=path.to.your.settings] /path/to/pyth  
    138134
    139135_POST_FORM_RE = \
    140136    re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
     137_FORM_CLOSE_RE = re.compile(r'</form\s*>')
    141138_TOKEN_RE = re.compile('\{% csrf_token')
    142139
    143140def get_template_dirs():
    class Template(object):  
    190187        Get information about any POST forms in the template.
    191188        Returns [(linenumber, csrf_token added)]
    192189        """
    193         matches = []
     190        forms = {}
     191        form_line = 0
    194192        for ln, line in enumerate(self.content.split("\n")):
    195             m = _POST_FORM_RE.search(line)
    196             if m is not None:
    197                 matches.append((ln + 1, _TOKEN_RE.search(line) is not None))
    198         return matches
     193            if not form_line and _POST_FORM_RE.search(line):
     194                # record the form with no CSRF token yet
     195                form_line = ln + 1
     196                forms[form_line] = False
     197            if form_line and _TOKEN_RE.search(line):
     198                # found the CSRF token
     199                forms[form_line] = True
     200                form_line = 0
     201            if form_line and _FORM_CLOSE_RE.search(line):
     202                # no token found by form closing tag
     203                form_line = 0
     204
     205        return forms.items()
    199206
    200207    def includes_template(self, t):
    201208        """
Back to Top