Martin von Löwis avatar Martin von Löwis committed a7cfbeb

Port sanitize to 3k.

Comments (0)

Files changed (1)

django/middleware/csrf.py

 against request forgeries from other sites.
 """
 
+import sys
 import itertools
 import re
 import random
 from django.utils.cache import patch_vary_headers
 from django.utils.hashcompat import md5_constructor
 from django.utils.safestring import mark_safe
+from django.utils.py3 import b
 
 _POST_FORM_RE = \
     re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
 def _sanitize_token(token):
     # Allow only alphanum, and ensure we return a 'str' for the sake of the post
     # processing middleware.
-    token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore')))
+    if isinstance(token, unicode):
+        token = token.encode('ascii', 'ignore')
+    token = re.sub(b('[^a-zA-Z0-9]'), b(''), token)
     if token == "":
         # In case the cookie has been truncated to nothing at some point.
         return _get_new_csrf_key()
     else:
-        return token
+        if sys.version_info < (3,):
+            return token
+        else:
+            return token.decode('ascii')
 
 
 class CsrfViewMiddleware(object):
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.