Skip to content
Myr

auth.py

This file

Path

httpcore/auth.py

38 lines · 1.1 KiB · Python

Last changed by

Auth (#65)Tom Christiebefore adoption5afa7dd

History of this file

Take it

1import typing2from base64 import b64encode34from .models import Request567class AuthBase:8    """9    Base class that all auth implementations derive from.10    """1112    def __call__(self, request: Request) -> Request:13        raise NotImplementedError("Auth hooks must be callable.")  # pragma: nocover141516class HTTPBasicAuth(AuthBase):17    def __init__(18        self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]19    ) -> None:20        self.username = username21        self.password = password2223    def __call__(self, request: Request) -> Request:24        request.headers["Authorization"] = self.build_auth_header()25        return request2627    def build_auth_header(self) -> str:28        username, password = self.username, self.password2930        if isinstance(username, str):31            username = username.encode("latin1")3233        if isinstance(password, str):34            password = password.encode("latin1")3536        userpass = b":".join((username, password))37        token = b64encode(userpass).decode().strip()38        return f"Basic {token}"