Functional Weave
Code in TypeScript

auth.email-token@1.0.0

impl/python/hash_email_token.py

900 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.

import re

from .crypto_sha256 import sha256  ← from crypto.sha256 ^1.0.0 · built alongside by fune
from .encoding_hex_hex_encode import hex_encode
from .encoding_utf8_utf8_encode import utf8_encode

_PURPOSE = re.compile(r"[a-z0-9-]{1,40}")


def check_email_token_purpose(purpose: str) -> None:
    """Refuses a purpose that is not 1 to 40 characters of a-z, 0-9 and -."""
    if not isinstance(purpose, str) or not _PURPOSE.fullmatch(purpose):
        raise ValueError("purpose must be 1 to 40 characters of a-z, 0-9 and -")


def hash_email_token(token: str, purpose: str) -> str:
    """The stored key for a token: the hex SHA-256 of the purpose, ":" and
    the token, so a token issued for one purpose never matches another."""
    check_email_token_purpose(purpose)
    if not isinstance(token, str) or len(token) == 0:
        raise ValueError("token must be a non-empty string")
    return hex_encode(sha256(utf8_encode(purpose + ":" + token)))