Skip to content

Instantly share code, notes, and snippets.

@zackkitzmiller
Created August 5, 2020 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zackkitzmiller/2fe1cc612cd77c31ad5e8b2ff8ea3703 to your computer and use it in GitHub Desktop.
Save zackkitzmiller/2fe1cc612cd77c31ad5e8b2ff8ea3703 to your computer and use it in GitHub Desktop.
import hashlib
from urllib.parse import urlparse, urlencode, parse_qsl, unquote
SECRET = "s3kr3t!"
# Generation:
url_to_sign = "https://example.com/verify?email=zkitzmiller@grabango.com&auth_level=4"
def generate_signature(url):
hasher = hashlib.new('sha256')
hasher.update(SECRET.encode() + url.encode())
return hasher.hexdigest()
def sign_url(url):
return url + "&sig=" + generate_signature(url)
# Verification
def verify_signature(signed_url):
# parse the url
parsed = urlparse(signed_url)
params = dict(parse_qsl(parsed.query))
# get the signature
sig = params.pop('sig')
# generate a signature from provided url (remove signature)
param_str = unquote(urlencode(params))
_url = parsed.scheme + "://" + parsed.netloc + parsed.path + "?" + param_str
# verify against generate_signature
return generate_signature(_url) == sig
@zackkitzmiller
Copy link
Author

zackkitzmiller commented Jan 26, 2021

Stub

# service A generates an email and sends a "confirm email link"

def generate_email_confirmation_link(email_address, auth_level=4) -> str:
    url = ""
    return url

# service B handles the link

def verify_url(url) -> bool:
    # example input: https://example.com/verify?email=zkitzmiller@grabango.com&auth_level=4
    return 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment