combo/combo/apps/wcs/templatetags/wcs.py

59 lines
2.0 KiB
Python

# combo - content management system
# Copyright (C) 2020 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import urllib.parse
from django import template
from django.conf import settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.html import escape
from django.utils.safestring import mark_safe
from combo.utils import aes_hex_encrypt
from combo.utils.misc import is_url_from_known_service
register = template.Library()
@register.filter
def format_text(field, value):
if field.get('pre'):
return mark_safe('<pre>%s</pre>' % escape(value))
return mark_safe('<p>' + '\n'.join([(escape(x) or '</p><p>') for x in value.splitlines()]) + '</p>')
@register.simple_tag(takes_context=True)
def make_public_url(context, url):
if not url or not is_url_from_known_service(url) or not urllib.parse.urlparse(url).netloc:
return url
if hasattr(context, 'request'):
request = context.request
else:
request = context.get('request')
if request is None:
return url
if not request.session.session_key:
request.session.cycle_key()
session_key = request.session.session_key
return reverse(
'wcs-redirect-crypto-url',
kwargs={
'session_key': session_key,
'crypto_url': aes_hex_encrypt(settings.SECRET_KEY, force_bytes(url)),
},
)