Skip to content
Merged
Show file tree
Hide file tree
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
49 changes: 45 additions & 4 deletions disruptive/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,53 @@
import time
import urllib.parse
from typing import Any

import jwt
import base64
import hmac
import hashlib

from disruptive import requests as dtrequests, errors as dterrors


def base64url_encode(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("utf-8")


def base64url_decode(data: str) -> bytes:
padding = '=' * (4 - (len(data) % 4))
return base64.urlsafe_b64decode(data + padding)


def create_jwt(payload: dict,
secret: str,
algorithm: str,
headers: dict,
) -> str:
headers["typ"] = "JWT"

header_encoded = base64url_encode(data=json.dumps(
obj=headers,
separators=(',', ':'),
).encode("utf-8"))
payload_encoded = base64url_encode(json.dumps(
obj=payload,
separators=(',', ':'),
).encode("utf-8"))

message = f"{header_encoded}.{payload_encoded}"

if algorithm == "HS256":
signature = hmac.new(
key=secret.encode("utf-8"),
msg=message.encode("utf-8"),
digestmod=hashlib.sha256,
).digest()
else:
raise ValueError(f"Unsupported algorithm: {algorithm}")

signature_encoded = base64url_encode(signature)
return f"{message}.{signature_encoded}"


class _AuthRoutineBase(object):

def __init__(self) -> None:
Expand Down Expand Up @@ -227,9 +268,9 @@ def _get_access_token(self) -> dict:
}

# Sign and encode JWT with the secret.
encoded_jwt: str = jwt.encode(
encoded_jwt: str = create_jwt(
payload=jwt_payload,
key=self.secret,
secret=self.secret,
algorithm=self.algorithm,
headers=jwt_headers,
)
Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@ requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"

[tool.black]
force-exclude = '.*'
force-exclude = '.*'

[tool.ruff.format]
exclude = ["*"]
1 change: 0 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ classifiers =
python_requires = >=3.9
install_requires =
requests >= 2.19.0, < 3.0.0
pyjwt >= 2.0.0, < 3.0.0
include-package-data = True
packages = find:

Expand Down
Loading