Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add basic auth support #81

Merged
merged 1 commit into from
Apr 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions chainbench/util/http.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import logging
import typing as t
from base64 import b64encode
from enum import IntEnum
from functools import cached_property
from json import JSONDecodeError
Expand Down Expand Up @@ -66,6 +67,11 @@ def check_http_error(self, request_uri: str = "", error_level: HttpErrorLevel =
raise HttpStatusError(self.status_code, self.status_message)


def basic_auth(username, password):
token = b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
return f"Basic {token}"


class HttpClient:
def __init__(
self,
Expand All @@ -76,6 +82,13 @@ def __init__(
):
self._rpc_version = rpc_version
self._host = URL(host)
self._general_headers = {}
if "@" in host:
username_password = host.split("//")[1].split("@")[0].split(":")
username = username_password[0]
password = username_password[1]
self._general_headers["Authorization"] = f"{basic_auth(username, password)}"

self._client = HTTPClient.from_url(self._host, connection_timeout=120, network_timeout=timeout)
self.error_level = error_level

Expand All @@ -102,6 +115,7 @@ def get(
headers = {}
if "Accept" not in headers:
headers.update({"Accept": "application/json"})
headers.update(self._general_headers)
response = self._client.get(
self._request_uri(path, params),
headers=headers,
Expand All @@ -126,6 +140,7 @@ def post(
headers.update({"Content-Type": "application/json"})
if "Accept" not in headers:
headers.update({"Accept": "application/json"})
headers.update(self._general_headers)
if isinstance(data, dict):
body = json.dumps(data).encode("utf-8")
elif isinstance(data, bytes):
Expand Down