sms: allow templated urls (#46778)

This commit is contained in:
Valentin Deniaud 2021-07-28 15:36:48 +02:00
parent fa678935a1
commit bee6b57876
5 changed files with 72 additions and 4 deletions

View File

@ -70,15 +70,26 @@ def get_local_hobo_dict():
def get_installed_services_dict():
from hobo.utils import TemplateError, get_templated_url
from .models import Variable
hobo_service = []
hobo_dict = get_local_hobo_dict()
if hobo_dict:
hobo_service.append(hobo_dict)
variables = {}
for v in Variable.objects.filter(service_pk__isnull=True):
if v.name in ('sms_url',):
try:
variables[v.name] = get_templated_url(v.value, context=getattr(settings, 'TEMPLATE_VARS', {}))
except TemplateError:
pass
else:
variables[v.name] = v.json
return {
'services': hobo_service + [x.as_dict() for x in get_installed_services()],
'variables': {v.name: v.json for v in Variable.objects.filter(service_pk__isnull=True)},
'variables': variables,
}

View File

@ -14,12 +14,15 @@
# 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/>.
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.utils.translation import ugettext_lazy as _
from hobo.utils import TemplateError, get_templated_url
class SMSForm(forms.Form):
sms_url = forms.URLField(label=_('SMS URL'), help_text=_('URL that can receive POST data to send SMS.'))
sms_url = forms.CharField(label=_('SMS URL'), help_text=_('URL that can receive POST data to send SMS.'))
sms_sender = forms.CharField(
label=_('Sender'),
max_length=11,
@ -30,3 +33,11 @@ class SMSForm(forms.Form):
'Sender name or phone number. It must neither exceed 11 characters nor contain special characters.'
),
)
def clean_sms_url(self):
value = self.cleaned_data['sms_url']
try:
get_templated_url(value)
except TemplateError as e:
raise ValidationError(_('Invalid template: %(error)s'), params={'error': e})
return value

View File

@ -1,12 +1,38 @@
from django.conf import settings
from django.template import Context, Template, TemplateSyntaxError, VariableDoesNotExist
from mellon.adapters import DefaultAdapter
from hobo.environment.models import Authentic
class MellonAdapter(DefaultAdapter):
def get_identity_providers_setting(self):
from hobo.environment.models import Authentic
try:
self_idp = Authentic.objects.get(use_as_idp_for_self=True)
except Authentic.DoesNotExist:
return []
return [{'METADATA_URL': self_idp.get_saml_idp_metadata_url()}]
class TemplateError(Exception):
def __init__(self, msg, params=()):
self.msg = msg
self.params = params
def __str__(self):
return self.msg % self.params
def get_templated_url(url, context=None):
if '{{' not in url and '{%' not in url:
return url
template_vars = getattr(settings, 'TEMPLATE_VARS', {})
if context:
template_vars.update(context)
template_vars = Context(template_vars, use_l10n=False)
try:
return Template(url).render(template_vars)
except VariableDoesNotExist as e:
raise TemplateError(e.msg, e.params)
except TemplateSyntaxError:
raise TemplateError('syntax error')

View File

@ -10,6 +10,7 @@ from test_manager import login
from webtest import Upload
from hobo.environment.models import AVAILABLE_SERVICES, Combo, Passerelle, ServiceBase, Variable
from hobo.environment.utils import get_installed_services_dict
from hobo.profile.models import AttributeDefinition
pytestmark = pytest.mark.django_db
@ -432,3 +433,17 @@ def test_export_import_view(app, admin_user):
assert Variable.objects.count() == 2
assert AttributeDefinition.objects.count() == 12
assert Variable.objects.get(name='foo').label == 'bar'
def test_services_dict_templated_url(settings):
settings.TEMPLATE_VARS = {'passerelle_url': 'http://example.com/'}
variable = Variable.objects.create(name='sms_url', value='{{passerelle_url}}send/')
Variable.objects.create(name='foo', value='bar')
hobo_dict = get_installed_services_dict()
assert hobo_dict['variables'] == {'sms_url': 'http://example.com/send/', 'foo': 'bar'}
variable.value = '{{invalid{syntax}}send/'
variable.save()
hobo_dict = get_installed_services_dict()
assert hobo_dict['variables'] == {'foo': 'bar'}

View File

@ -17,3 +17,8 @@ def test_sms_view(app, admin_user):
resp.form['sms_sender'] = 'Entr\'ouvert'
resp = resp.form.submit()
assert 'Only alphanumeric' in resp.text
resp.form['sms_sender'] = 'Sender Name'
resp.form['sms_url'] = '{{syntax{error}}'
resp = resp.form.submit()
assert 'Invalid template' in resp.text