Created
May 25, 2023 20:15
-
-
Save CyberAstronaut101/e12936aee754d63d051429ece5e71783 to your computer and use it in GitHub Desktop.
Python code for generating signed urls for Cloudflare Image API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import hmac | |
import hashlib | |
from urllib.parse import urlparse, parse_qs, urlencode, urlunparse | |
# Given test private URL for private image we need to sign | |
KEY = 'KEY-FROM-CF-IMAGE-DAHSBOARD' | |
PRIVATE_URL = 'https://imagedelivery.net/abc123/abc123/public' | |
EXPIRATION = 60 * 60 * 24 # 24 hours in seconds | |
def buffer_to_hex(buffer): | |
return ''.join(format(x, '02x') for x in buffer) | |
def generate_signed_url(url): | |
url = urlparse(url) | |
# Attach expiration time to the url | |
expiry = int(time.time()) + EXPIRATION | |
query = dict(parse_qs(url.query)) | |
query.update({'exp': expiry}) | |
string_to_sign = url.path + '?' + urlencode(query, doseq=True) | |
print("signing string: " + string_to_sign) | |
# Generate the signature | |
mac = hmac.new(KEY.encode(), string_to_sign.encode(), hashlib.sha256) | |
sig = buffer_to_hex(mac.digest()) | |
# Attach it to the `url` | |
query.update({'sig': sig}) | |
url = url._replace(query=urlencode(query, doseq=True)) | |
return urlunparse(url) | |
def fetch_image_delivery_url(event_request_url): | |
url = urlparse(event_request_url) | |
image_delivery_url = url.path[1:].replace( | |
'https:/imagedelivery.net', 'https://imagedelivery.net') | |
return generate_signed_url(event_request_url) | |
# Test it with a URL | |
signed_url = fetch_image_delivery_url(PRIVATE_URL) | |
print(signed_url) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment