1
Fork 0

Replace SRI template tag with package

This commit is contained in:
Jake Howard 2020-05-02 20:28:19 +01:00
parent 72d88dc7cf
commit b0faca2f21
Signed by: jake
GPG key ID: 57AFB45680EDD477
5 changed files with 6 additions and 55 deletions

View file

@ -4,3 +4,4 @@ whitenoise==5.0.1
brotli==1.0.7
django-environ==0.4.5
gunicorn ==20.0.4
django-sri==0.1.2

View file

@ -15,8 +15,8 @@
<title>{% block title %}{% endblock %} :: TheOrangeOne</title>
{% sri_css "css/font-awesome.min.css" %}
{% sri_css "css/index.css" %}
{% sri "css/font-awesome.min.css" %}
{% sri "css/index.css" %}
</head>
<body class="{{ view_name }}">
@ -51,8 +51,8 @@
{% endblock %}
{% sri_js "js/materialize.min.js" %}
{% sri_js "js/index.js" %}
{% sri "js/materialize.min.js" %}
{% sri "js/index.js" %}
{% block extrascripts %}{% endblock %}
</body>

View file

@ -1,51 +0,0 @@
# 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 = {
"src": static(url),
"type": "text/javascript",
"integrity": generate_sha256(path),
"crossorigin": "anonymous",
}
return mark_safe(f"<script {attrs_to_str(attrs)}></script>")
@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"<link {attrs_to_str(attrs)}/>")

View file

@ -38,6 +38,7 @@ INSTALLED_APPS = [
"whitenoise.runserver_nostatic",
"django.contrib.staticfiles",
"debug_toolbar",
"sri",
"website.common",
]