Skip to content

Commit

Permalink
make external rich_text links target blank
Browse files Browse the repository at this point in the history
  • Loading branch information
felixrindt committed Dec 12, 2024
1 parent 1727bcc commit 27e68cc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
30 changes: 29 additions & 1 deletion ephios/extra/templatetags/rich_text.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from urllib.parse import urlparse

import bleach
import markdown
from bleach.linkifier import DEFAULT_CALLBACKS
from django import template
from django.conf import settings
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.safestring import mark_safe

register = template.Library()
Expand Down Expand Up @@ -63,12 +68,35 @@ def markdown_compile(source, excluded_tags=""):
)


def safelink_callback(attrs, new=False):
"""
Links to a different domain should open with target=_blank
"""
url = attrs.get((None, "href"), None)
if url is None:
return attrs
if url.startswith("mailto:") or url.startswith("tel:"):
return attrs
if not url_has_allowed_host_and_scheme(
url,
allowed_hosts=[
urlparse(settings.GET_SITE_URL()).netloc,
],
):
attrs[None, "target"] = "_blank"
attrs[None, "rel"] = "noopener"
return attrs


@register.filter
def rich_text(text: str, excluded_tags=""):
"""
Processes markdown and cleans HTML in a text input.
"""
text = str(text)
linker = bleach.Linker(parse_email=True)
linker = bleach.Linker(
parse_email=True,
callbacks=DEFAULT_CALLBACKS + [safelink_callback],
)
body_md = linker.linkify(markdown_compile(text, excluded_tags=excluded_tags))
return mark_safe(body_md)
8 changes: 8 additions & 0 deletions tests/extra/test_rich_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from ephios.extra.templatetags.rich_text import rich_text


def test_rich_text():
assert (
rich_text("https://xkcd.com")
== '<p><a href="https://xkcd.com" rel="noopener" target="_blank">https://xkcd.com</a></p>'
)

0 comments on commit 27e68cc

Please sign in to comment.