diff --git a/templates/base.html b/templates/base.html index fd25d68..a9c4747 100644 --- a/templates/base.html +++ b/templates/base.html @@ -1,4 +1,5 @@ {% load static %} +{% load sri %} @@ -13,8 +14,10 @@ {% block title %}{% endblock %} :: TheOrangeOne - - + + {% sri_css "css/font-awesome.min.css" %} + {% sri_css "css/index.css" %} +
@@ -47,8 +50,9 @@ {% endblock %} - - + + {% sri_js "js/materialize.min.js" %} + {% sri_js "js/index.js" %} {% block extrascripts %}{% endblock %} diff --git a/website/common/templatetags/__init__.py b/website/common/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/website/common/templatetags/sri.py b/website/common/templatetags/sri.py new file mode 100644 index 0000000..3582ded --- /dev/null +++ b/website/common/templatetags/sri.py @@ -0,0 +1,51 @@ +# Based off https://github.com/claudep/django/commit/89aa4c04dbffcbafc05c3e2053b2262be8de4d3d + +import base64 +import hashlib +import os +from functools import lru_cache + +from django import template +from django.conf import settings +from django.templatetags.static import static +from django.utils.safestring import mark_safe + +register = template.Library() + + +@lru_cache +def generate_sha256(path): + with open(path, "r") as f: + body = f.read() + digest = hashlib.sha256(body.encode()).digest() + sha = base64.b64encode(digest).decode() + return "sha256-{}".format(sha) + + +def attrs_to_str(attrs): + return " ".join('{}="{}"'.format(k, v) for k, v in attrs.items()) + + +@register.simple_tag +def sri_js(url): + path = os.path.join(settings.STATIC_ROOT, url) + attrs = { + "href": static(url), + "type": "text/javascript", + "integrity": generate_sha256(path), + "crossorigin": "anonymous", + } + return mark_safe(f"") + + +@register.simple_tag +def sri_css(url): + path = os.path.join(settings.STATIC_ROOT, url) + attrs = { + "href": static(url), + "type": "text/css", + "rel": "stylesheet", + "integrity": generate_sha256(path), + "crossorigin": "anonymous", + } + return mark_safe(f"")