Skip to content

Commit

Permalink
Refactor basic auth header building
Browse files Browse the repository at this point in the history
  • Loading branch information
florimondmanca committed Sep 7, 2019
1 parent 349f5be commit 910af27
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
20 changes: 10 additions & 10 deletions httpx/middleware/basic_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,26 @@
from base64 import b64encode

from ..models import AsyncRequest, AsyncResponse
from ..utils import to_bytes
from .base import BaseMiddleware


class BasicAuthMiddleware(BaseMiddleware):
def __init__(
self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]
):
if isinstance(username, str):
username = username.encode("latin1")

if isinstance(password, str):
password = password.encode("latin1")

userpass = b":".join((username, password))
token = b64encode(userpass).decode().strip()

self.authorization_header = f"Basic {token}"
self.authorization_header = build_basic_auth_header(username, password)

async def __call__(
self, request: AsyncRequest, get_response: typing.Callable
) -> AsyncResponse:
request.headers["Authorization"] = self.authorization_header
return await get_response(request)


def build_basic_auth_header(
username: typing.Union[str, bytes], password: typing.Union[str, bytes]
) -> str:
userpass = b":".join((to_bytes(username), to_bytes(password)))
token = b64encode(userpass).decode().strip()
return f"Basic {token}"
4 changes: 4 additions & 0 deletions httpx/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,7 @@ def get_logger(name: str) -> logging.Logger:
logger.addHandler(handler)

return logging.getLogger(name)


def to_bytes(value: typing.Union[str, bytes]) -> bytes:
return value.encode() if isinstance(value, str) else value

0 comments on commit 910af27

Please sign in to comment.