Last active
August 29, 2015 14:04
-
-
Save evansd/b09e69257c888f942aee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import json | |
| import re | |
| from django import template | |
| from django.utils.safestring import mark_safe | |
| register = template.Library() | |
| # Use a regex to do character replacements so we can do them in a single pass | |
| REPLACEMENTS = {'<': r'\u003c', '&': r'\u0026', '>': r'\u003e'} | |
| REPLACE_RE = re.compile('|'.join(map(re.escape, REPLACEMENTS.keys()))) | |
| def replace(match): | |
| return REPLACEMENTS[match.group(0)] | |
| def escape_json(json_string): | |
| return REPLACE_RE.sub(replace, json_string) | |
| @register.filter | |
| def safe_json(data, indent=None): | |
| """ | |
| Serialize data as JSON and escape the resulting string so that it can be | |
| safely included in a `<script>` element in an HTML or XHTML document | |
| Escaped sequences are based on the recommendations here: | |
| http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements | |
| https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet | |
| < : should be escaped in all contexts | |
| & : only relevant for XHTML documents | |
| > : only relevant within CDATA blocks or HTML comments | |
| As these sequences can only occur within strings in JSON, we can safely replace | |
| them with unicode escape sequences. | |
| """ | |
| json_string = json.dumps(data, indent=indent) | |
| return mark_safe(escape_json(json_string)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment