Last active
August 2, 2022 00:29
-
-
Save bryanchow/45db1ce979b1aae75c996e3e90e6f72c to your computer and use it in GitHub Desktop.
Generate an expiring URL compatible with Nginx's http_secure_link_module.
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
# https://gist.github.com/bryanchow/45db1ce979b1aae75c996e3e90e6f72c | |
import time | |
from datetime import datetime, timedelta | |
from hashlib import md5 | |
from base64 import b64encode | |
from urllib.parse import urlencode | |
def make_secure_link(url, secret, minutes=5): | |
""" | |
Given a URL and a shared secret, generate an expiring URL compatible with | |
Nginx's http_secure_link_module. | |
http://nginx.org/en/docs/http/ngx_http_secure_link_module.html | |
""" | |
expiry_time = datetime.now() + timedelta(minutes=minutes) | |
timestamp = str(int(time.mktime(expiry_time.timetuple()))) | |
token = ( | |
b64encode( | |
md5("".join([secret, url, timestamp]).encode()).digest() | |
) | |
.decode() | |
.replace("+", "-") | |
.replace("/", "_") | |
.replace("=", "") | |
) | |
return "?".join((url, urlencode(dict(st=token, e=timestamp)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment