I would like to know best approach in obfuscating sensitive data in Markdown (wagtail-markdown) or any other custom fields. The use case is to prevent bot scrapping for email and phone number on legally required Impressum pages in Germany.
So far I have tried I one of the email encoders online and pasting the output in Markdown but that's just parsed as text in the end. Also I have seen Wagtail documentation mentioning to register a rewrite handler , but that is tied to RichTextField types. How can I do that same workflow work with any text field? What is the best approach overall?
You could convert your email address to unicode then use it with javascript:location to create the link (presuming you want a link, but similar process for other uses).
Code:
import re
email = "somebody@somewhere.com"
uni = (re.sub('.', lambda x: r'\u%04X' % ord(x.group()), email))
mailto = (f"javascript:location='mailto:{uni}';void0")
print(mailto)
Output:
javascript:location='mailto:\u0073\u006F\u006D\u0065\u0062\u006F\u0064\u0079\u0040\u0073\u006F\u006D\u0065\u0077\u0068\u0065\u0072\u0065\u002E\u0063\u006F\u006D';void0
Template:
<a href="{{ mailto }}">Contact</a>
Rendered:
<a href="javascript:location='mailto:\u0073\u006F\u006D\u0065\u0062\u006F\u0064\u0079\u0040\u0073\u006F\u006D\u0065\u0077\u0068\u0065\u0072\u0065\u002E\u0063\u006F\u006D';void0">Contact</a>
The unicode is rendered back to ascii in the client mail app
If you want to actually display the email/phone, there's not much to do about that that I could think of other than using PIL to generate on-the-fly png's with the info embedded.
Try this...
Template tag/filter
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
register = template.Library()
def obfuscate_string(value):
return ''.join(['&#{0:s};'.format(str(ord(char))) for char in value])
@register.filter
@stringfilter
def obfuscate(value):
return mark_safe(obfuscate_string(value))
@register.filter
@stringfilter
def obfuscate_mailto(value, text=False):
mail = obfuscate_string(value)
if text:
link_text = text
# Detect subject lines
if ';' in text:
args = text.split(';')
link_text = args[0]
subject = args[1]
mail = mail + '?subject=' + subject
else:
link_text = mail
return mark_safe('<a href="{0:s}{1:s}">{2:s}</a>'.format(
obfuscate_string('mailto:'), mail, link_text))
Template
{% load i18n email_obfuscator %}
{{ some_email|obfuscate_mailto }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.