1
This repository has been archived on 2023-03-26. You can view files and clone it, but cannot push or open issues or pull requests.
website-2020-spike/website/common/templatetags/sri.py
Jake Howard 2d7dea438f
Add SRI for static assets
Will extract out into a library someday
2020-05-02 13:48:44 +01:00

52 lines
1.3 KiB
Python

# 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"<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)}/>")