Functional Weave
Code in TypeScript

auth.email-token@1.0.0

impl/python/check_email_token.py

2,037 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 typing import Sequence, Tuple

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 EmailTokenCheck, EmailTokenRecord
from .crypto_constant_time_equal import constant_time_equal  ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
from .encoding_hex_hex_decode import hex_decode

_HASH = re.compile(r"[0-9a-f]{64}")


def find_email_token(
    records: Sequence[EmailTokenRecord], token: str, purpose: str, now: int
) -> Tuple[int, EmailTokenCheck]:
    """Where a token's record is among records, and its outcome now: index -1 when unknown."""
    check_email_token_purpose(purpose)
    if not isinstance(token, str):
        raise TypeError("token must be a string")
    if type(now) is not int:
        raise TypeError("now must be a whole number of Unix seconds")
    for r in records:
        if not isinstance(r.token_hash, str) or not _HASH.fullmatch(r.token_hash):
            raise ValueError("tokenHash must be 64 lowercase hex characters")
    if len(token) == 0:
        return -1, EmailTokenCheck(outcome="unknown", record=None)
    attempt = hex_decode(hash_email_token(token, purpose))
    index = -1
    for i, r in enumerate(records):
        # Every record is compared, with no early exit.
        same = constant_time_equal(attempt, hex_decode(r.token_hash))
        if same and index < 0:
            index = i
    if index < 0 or records[index].purpose != purpose:
        return -1, EmailTokenCheck(outcome="unknown", record=None)
    record = records[index]
    if record.used_at is not None:
        return index, EmailTokenCheck(outcome="used", record=record)
    if now >= record.expires_at:
        return index, EmailTokenCheck(outcome="expired", record=record)
    return index, EmailTokenCheck(outcome="ok", record=record)


def check_email_token(records: Sequence[EmailTokenRecord], token: str, purpose: str, now: int) -> EmailTokenCheck:
    """What a token from a link is worth now, without using it up."""
    return find_email_token(records, token, purpose, now)[1]