Skip to content

Commit

Permalink
Add custom filter for signing thumbor urls
Browse files Browse the repository at this point in the history
  • Loading branch information
cheeplusplus committed Jan 12, 2024
1 parent 6f27057 commit 1a93f46
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions sssg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import frontmatter
import urllib.request
from typing import Generator, Optional
from .filters import thumbor_signed


class BuildError(Exception):
Expand Down Expand Up @@ -47,6 +48,7 @@ def __init__(self, source_dir: str):

self.jinja = Environment(loader=FileSystemLoader(template_paths))
self.jinja.filters["markdown"] = lambda text: Markup(self.md.convert(text))
self.jinja.filters["thumbor_signed"] = lambda text: thumbor_signed(text)

def read_metadata(self, content: str) -> tuple[str, dict[str, str]]:
'''Attempt to read metadata from a file.'''
Expand Down
25 changes: 25 additions & 0 deletions sssg/filters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import base64
import hashlib
import hmac
import os


def thumbor_signed(url: str):
use_key: str | None = None
if "SSSG_THUMBOR_KEY" in os.environ:
use_key = os.environ["SSSG_THUMBOR_KEY"]
if not use_key:
print("SSSG_THUMBOR_KEY not found, falling back to unsafe")
return "unsafe/" + url

return (
base64.urlsafe_b64encode(
hmac.new(
use_key.encode("utf-8"),
url.encode("utf-8"),
hashlib.sha1,
).digest()
).decode("utf-8")
+ "/"
+ url
)

0 comments on commit 1a93f46

Please sign in to comment.