misc: add |with_auth filter tag, to add basic HTTP auth to URL (#80394)
gitea/publik-django-templatetags/pipeline/head This commit looks good Details

This commit is contained in:
Frédéric Péters 2023-09-30 13:34:54 +02:00
parent 063f03c491
commit e1e6d17d2f
2 changed files with 22 additions and 0 deletions

View File

@ -17,6 +17,7 @@
import collections
import datetime
import math
import urllib.parse
from decimal import Decimal
from decimal import DivisionByZero as DecimalDivisionByZero
from decimal import InvalidOperation as DecimalInvalidOperation
@ -250,3 +251,10 @@ def list_(value):
return list(value)
else:
return [value]
@register.filter
def with_auth(value, arg):
parsed_url = urllib.parse.urlparse(value)
new_netloc = '%s@%s' % (arg, parsed_url.netloc.rsplit('@', 1)[-1])
return urllib.parse.urlunparse(parsed_url._replace(netloc=new_netloc))

View File

@ -436,3 +436,17 @@ def test_convert_as_list_with_add():
assert tmpl.render(Context({'foo': 12, 'bar': 'ab'})) == '12, ab'
assert html.unescape(tmpl.render(Context({'foo': [1, 2], 'bar': {'a': 'b'}}))) == "1, 2, {'a': 'b'}"
assert html.unescape(tmpl.render(Context({'foo': {'a': 'b'}, 'bar': ['a', 'b']}))) == "{'a': 'b'}, a, b"
def test_with_auth():
context = Context({'service_url': 'https://www.example.net/api/whatever?x=y'})
assert (
Template('{{ service_url|with_auth:"username:password" }}').render(context)
== 'https://username:password@www.example.net/api/whatever?x=y'
)
context = Context({'service_url': 'https://a:b@www.example.net/api/whatever?x=y'})
assert (
Template('{{ service_url|with_auth:"username:password" }}').render(context)
== 'https://username:password@www.example.net/api/whatever?x=y'
)