csp_nonce: Add nonce to script tags loading minified JS.

This commit is contained in:
Aditya Bansal
2018-04-16 15:59:53 +05:30
parent e9f2efedb5
commit ae398dc48b
3 changed files with 8 additions and 6 deletions

View File

@@ -35,7 +35,7 @@
{% else %}
{% stylesheet 'app' %}
{% endif %}
{{ minified_js('app')|safe }}
{{ minified_js('app', csp_nonce)|safe }}
{{ render_bundle('translations') }}

View File

@@ -9,8 +9,9 @@ from django.template.base import Parser, Token
register = Library()
class MinifiedJSNode(Node):
def __init__(self, sourcefile: str) -> None:
def __init__(self, sourcefile: str, csp_nonce: str) -> None:
self.sourcefile = sourcefile
self.csp_nonce = csp_nonce
def render(self, context: Dict[str, Any]) -> str:
if settings.DEBUG:
@@ -24,6 +25,7 @@ class MinifiedJSNode(Node):
else:
scripts = [settings.JS_SPECS[self.sourcefile]['output_filename']]
script_urls = [staticfiles_storage.url(script) for script in scripts]
script_tags = ['<script type="text/javascript" src="%s" charset="utf-8"></script>'
% url for url in script_urls]
script_tags = [('<script type="text/javascript" nonce="%s"'
' src="%s" charset="utf-8"></script>') % (self.csp_nonce, url)
for url in script_urls]
return '\n'.join(script_tags)

View File

@@ -10,9 +10,9 @@ from django.template import TemplateSyntaxError
from zerver.templatetags.minified_js import MinifiedJSNode
def minified_js(sourcefile: str) -> Text:
def minified_js(sourcefile: str, csp_nonce: str) -> Text:
if sourcefile not in settings.JS_SPECS:
raise TemplateSyntaxError(
"Invalid argument: no JS file %s".format(sourcefile))
return MinifiedJSNode(sourcefile).render({})
return MinifiedJSNode(sourcefile, csp_nonce).render({})