3 from django.core.exceptions import ValidationError
4 from django.template import Template, Parser, Lexer, TOKEN_BLOCK, TOKEN_VAR, TemplateSyntaxError
5 from django.utils import simplejson as json
6 from django.utils.html import escape, mark_safe
7 from django.utils.translation import ugettext_lazy as _
9 from philo.utils import LOADED_TEMPLATE_ATTR
12 #: Tags which are considered insecure and are therefore always disallowed by secure :class:`TemplateValidator` instances.
21 def json_validator(value):
22 """Validates whether ``value`` is a valid json string."""
26 raise ValidationError(u'JSON decode error: %s' % e)
29 class TemplateValidationParser(Parser):
30 def __init__(self, tokens, allow=None, disallow=None, secure=True):
31 super(TemplateValidationParser, self).__init__(tokens)
33 allow, disallow = set(allow or []), set(disallow or [])
36 disallow |= set(INSECURE_TAGS)
38 self.allow, self.disallow, self.secure = allow, disallow, secure
40 def parse(self, parse_until=None):
41 if parse_until is None:
44 nodelist = self.create_nodelist()
46 token = self.next_token()
47 # We only need to parse var and block tokens.
48 if token.token_type == TOKEN_VAR:
49 if not token.contents:
50 self.empty_variable(token)
52 filter_expression = self.compile_filter(token.contents)
53 var_node = self.create_variable_node(filter_expression)
54 self.extend_nodelist(nodelist, var_node,token)
55 elif token.token_type == TOKEN_BLOCK:
56 if token.contents in parse_until:
57 # put token back on token list so calling code knows why it terminated
58 self.prepend_token(token)
62 command = token.contents.split()[0]
64 self.empty_block_tag(token)
66 if (self.allow and command not in self.allow) or (self.disallow and command in self.disallow):
67 self.disallowed_tag(command)
69 self.enter_command(command, token)
72 compile_func = self.tags[command]
74 self.invalid_block_tag(token, command, parse_until)
77 compiled_result = compile_func(self, token)
78 except TemplateSyntaxError, e:
79 if not self.compile_function_error(token, e):
82 self.extend_nodelist(nodelist, compiled_result, token)
86 self.unclosed_block_tag(parse_until)
90 def disallowed_tag(self, command):
91 if self.secure and command in INSECURE_TAGS:
92 raise ValidationError('Tag "%s" is not permitted for security reasons.' % command)
93 raise ValidationError('Tag "%s" is not permitted here.' % command)
96 def linebreak_iter(template_source):
97 # Cribbed from django/views/debug.py:18
99 p = template_source.find('\n')
102 p = template_source.find('\n', p+1)
103 yield len(template_source) + 1
106 class TemplateValidator(object):
108 Validates whether a string represents valid Django template code.
110 :param allow: ``None`` or an iterable of tag names which are explicitly allowed. If provided, tags whose names are not in the iterable will cause a ValidationError to be raised if they are used in the template code.
111 :param disallow: ``None`` or an iterable of tag names which are explicitly allowed. If provided, tags whose names are in the iterable will cause a ValidationError to be raised if they are used in the template code. If a tag's name is in ``allow`` and ``disallow``, it will be disallowed.
112 :param secure: If the validator is set to secure, it will automatically disallow the tag names listed in :const:`INSECURE_TAGS`. Defaults to ``True``.
115 def __init__(self, allow=None, disallow=None, secure=True):
117 self.disallow = disallow
120 def __call__(self, value):
122 self.validate_template(value)
123 except ValidationError:
126 if hasattr(e, 'source') and isinstance(e, TemplateSyntaxError):
127 origin, (start, end) = e.source
128 template_source = origin.reload()
130 for num, next in enumerate(linebreak_iter(template_source)):
131 if start >= upto and end <= next:
132 raise ValidationError(mark_safe("Template code invalid: \"%s\" (%s:%d).<br />%s" % (escape(template_source[start:end]), origin.loadname, num, e)))
134 raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e))
136 def validate_template(self, template_string):
137 # We want to tokenize like normal, then use a custom parser.
138 lexer = Lexer(template_string, None)
139 tokens = lexer.tokenize()
140 parser = TemplateValidationParser(tokens, self.allow, self.disallow, self.secure)
142 for node in parser.parse():
143 template = getattr(node, LOADED_TEMPLATE_ATTR, None)