Functional Weave
Code in Rust

auth.bearer-token@1.0.0

impl/python.py

1,103 bytes · the Python implementation · view raw

from typing import Optional


def _is_token_char(ch: str) -> bool:
    return ("A" <= ch <= "Z") or ("a" <= ch <= "z") or ("0" <= ch <= "9") or ch in "-._~+/"


def parse_bearer_token(authorization: Optional[str]) -> Optional[str]:
    """The token from ``Authorization: Bearer <token>`` (RFC 6750 section 2.1),
    or None. Never raises: a malformed header is an answer (401), not an error."""
    if not isinstance(authorization, str):
        return None
    value = authorization.strip(" \t")
    # Compare the scheme by ASCII case only; str.lower() would also fold
    # characters the other languages leave alone.
    scheme = value[:6]
    if len(value) < 7 or "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in scheme) != "bearer" or value[6] != " ":
        return None
    i = 6
    while i < len(value) and value[i] == " ":
        i += 1
    token = value[i:]
    j = 0
    while j < len(token) and _is_token_char(token[j]):
        j += 1
    if j == 0:
        return None
    while j < len(token) and token[j] == "=":
        j += 1
    return token if j == len(token) else None