Skip to content
Myr

auth.py

This file

Path

httpcore/auth.py

38 lines · 1.1 KiB · Python

Last changed by

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

History of this file

Take it

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 1–3why, one step back
1import typing
2from base64 import b64encode3

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

line 4why, one step back
4from .models import AsyncRequest

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 5–11why, one step back
5
67class AuthBase:8 """9 Base class that all auth implementations derive from.10 """11

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

line 12why, one step back
12 def __call__(self, request: AsyncRequest) -> AsyncRequest:

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 13–22why, one step back
13 raise NotImplementedError("Auth hooks must be callable.") # pragma: nocover
141516class 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 = password22

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

line 23why, one step back
23 def __call__(self, request: AsyncRequest) -> AsyncRequest:

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 24–38why, one step back
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}"