2022-11-11 21:02:43 -08:00
|
|
|
import bleach
|
2022-11-13 18:03:43 -08:00
|
|
|
from bleach.linkifier import LinkifyFilter
|
2022-11-11 21:02:43 -08:00
|
|
|
from django.utils.safestring import mark_safe
|
|
|
|
|
|
|
|
|
2022-11-13 18:03:43 -08:00
|
|
|
def allow_a(tag: str, name: str, value: str):
|
|
|
|
if name in ["href", "title", "class"]:
|
|
|
|
return True
|
|
|
|
elif name == "rel":
|
|
|
|
# Only allow rel attributes with a small subset of values
|
|
|
|
# (we're defending against, for example, rel=me)
|
|
|
|
rel_values = value.split()
|
|
|
|
if all(v in ["nofollow", "noopener", "noreferrer", "tag"] for v in rel_values):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2022-11-11 21:02:43 -08:00
|
|
|
def sanitize_post(post_html: str) -> str:
|
|
|
|
"""
|
|
|
|
Only allows a, br, p and span tags, and class attributes.
|
|
|
|
"""
|
2022-11-13 18:03:43 -08:00
|
|
|
cleaner = bleach.Cleaner(
|
|
|
|
tags=["a", "br", "p", "span"],
|
|
|
|
attributes={ # type:ignore
|
|
|
|
"a": allow_a,
|
|
|
|
"p": ["class"],
|
|
|
|
"span": ["class"],
|
|
|
|
},
|
|
|
|
filters=[LinkifyFilter],
|
2022-11-11 21:02:43 -08:00
|
|
|
)
|
2022-11-13 18:03:43 -08:00
|
|
|
return mark_safe(cleaner.clean(post_html))
|