Last active
January 3, 2017 00:26
-
-
Save agusmakmun/b78a713f5387fe4405368239a031d43c to your computer and use it in GitHub Desktop.
Django Custom safe excludes from dangerous XSS Injection. Answered from: http://stackoverflow.com/a/41434870/6396981
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
from bs4 import BeautifulSoup | |
from django import template | |
from django.utils.html import escape | |
register = template.Library() | |
INVALID_TAGS = ['script',] | |
def clean_html(value): | |
soup = BeautifulSoup(value) | |
for tag in soup.findAll(True): | |
if tag.name in INVALID_TAGS: | |
#tag.hidden = True # you also can hidden it | |
tag.replaceWith(escape(tag)) | |
return soup.renderContents() | |
# clean_html('<h1>This is heading</h1> and this xss injection <script>location.reload()</script>') | |
# <html><body><h1>This is heading</h1> and this xss injection <script>location.reload()</script></body></html> | |
@register.filter | |
def safe_exclude(text): | |
# egg: {{ post.description|safe_exclude|safe }} | |
return clean_html(text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment