Replace bleach with nh3

This commit is contained in:
Stefan Wehrmeyer 2025-06-25 09:11:44 +02:00
parent 374f6f762e
commit 3ca4fc247d
2 changed files with 20 additions and 31 deletions

View file

@ -1,22 +1,18 @@
import copy import copy
import nh3
from django import forms from django import forms
from django.conf import settings from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.utils import timezone from django.utils import timezone
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
import bleach
from bleach.linkifier import Linker
from tinymce.widgets import TinyMCE
from froide.helper.widgets import BootstrapSelect from froide.helper.widgets import BootstrapSelect
from tinymce.widgets import TinyMCE
from .models import GovernmentPlan, GovernmentPlanUpdate, PlanRating, PlanStatus from .models import GovernmentPlan, GovernmentPlanUpdate, PlanRating, PlanStatus
BLEACH_OPTIONS = { ALLOWED_TAGS = [
"tags": [
"a", "a",
"strong", "strong",
"b", "b",
@ -30,13 +26,7 @@ BLEACH_OPTIONS = {
"h4", "h4",
"h5", "h5",
"blockquote", "blockquote",
] ]
}
def set_link_attrs(attrs, new=False):
attrs[(None, "rel")] = "noopener"
return attrs
class BleachField(forms.CharField): class BleachField(forms.CharField):
@ -49,9 +39,8 @@ class BleachField(forms.CharField):
""" """
if value in self.empty_values: if value in self.empty_values:
return self.empty_value return self.empty_value
cleaned = bleach.clean(value, **BLEACH_OPTIONS) cleaned_html = nh3.clean(value, tags=ALLOWED_TAGS, link_rel="noopener")
linker = Linker(callbacks=[set_link_attrs]) return mark_safe(cleaned_html)
return mark_safe(linker.linkify(cleaned))
class GovernmentPlanForm(forms.ModelForm): class GovernmentPlanForm(forms.ModelForm):

View file

@ -22,7 +22,7 @@ dependencies = [
"django-filer", "django-filer",
"psycopg[binary]", "psycopg[binary]",
"django-admin-sortable2", "django-admin-sortable2",
"bleach", "nh3",
"django-tinymce", "django-tinymce",
"django-oauth-toolkit", "django-oauth-toolkit",
"django-mfa3", "django-mfa3",