impl/python/generate_email_token.py
1,592 bytes · the Python implementation · view raw
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
from typing import Sequence
from .auth_email_token_hash_email_token import check_email_token_purpose, hash_email_token ← hashEmailToken, another function of this group · built into the same file, even by a slim install
from .auth_email_token_types import IssuedEmailToken
from .encoding_base64_base64_url_encode import base64_url_encode
def generate_email_token(
random_bytes: Sequence[int], purpose: str, subject: str, now: int, ttl_seconds: int
) -> IssuedEmailToken:
"""A new single-use token from the caller's random bytes. The token goes
in the email's link only; store the rest."""
if isinstance(random_bytes, (str, dict)) or not hasattr(random_bytes, "__len__"):
raise TypeError("randomBytes must be a list of integers from 0 to 255")
for b in random_bytes:
if type(b) is not int or b < 0 or b > 255:
raise ValueError("randomBytes must be a list of integers from 0 to 255")
if len(random_bytes) < 16:
raise ValueError("randomBytes must hold at least 16 bytes")
check_email_token_purpose(purpose)
if not isinstance(subject, str) or len(subject) == 0:
raise ValueError("subject must be a non-empty string")
if type(now) is not int:
raise TypeError("now must be a whole number of Unix seconds")
if type(ttl_seconds) is not int or ttl_seconds < 1 or ttl_seconds > 2592000:
raise ValueError("ttlSeconds must be a whole number from 1 to 2592000")
token = base64_url_encode(random_bytes)
return IssuedEmailToken(
token=token,
token_hash=hash_email_token(token, purpose),
purpose=purpose,
subject=subject,
expires_at=now + ttl_seconds,
)