Skip to content
Open
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
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://gitlab.com/vojko.pribudic.foss/pre-commit-update
rev: v0.9.0
rev: v0.10.0
hooks:
- id: pre-commit-update
- repo: https://github.com/pre-commit/pre-commit-hooks
Expand All @@ -13,12 +13,12 @@ repos:
- id: detect-private-key
- id: requirements-txt-fixer
- repo: https://github.com/codespell-project/codespell
rev: v2.4.2
rev: v2.4.3
hooks:
- id: codespell
exclude: ^locale/
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.19
rev: v0.17.6
hooks:
- id: ruff-check
args: [--fix]
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ uv add magic-admin
from magic_admin import Magic

# Initialize with your API secret key
magic = Magic(api_secret_key='your_api_secret_key_here')
magic = Magic(api_secret_key="your_api_secret_key_here")

# Validate a DID token
try:
magic.Token.validate('DID_TOKEN_FROM_CLIENT')
magic.Token.validate("DID_TOKEN_FROM_CLIENT")
print("Token is valid!")
except Exception as e:
print(f"Token validation failed: {e}")
Expand Down Expand Up @@ -61,10 +61,10 @@ Customize network behavior for your application:

```python
magic = Magic(
api_secret_key='your_key',
retries=5, # Number of retry attempts
timeout=10, # Request timeout in seconds
backoff_factor=0.03 # Exponential backoff factor
api_secret_key="your_key",
retries=5, # Number of retry attempts
timeout=10, # Request timeout in seconds
backoff_factor=0.03, # Exponential backoff factor
)
```

Expand Down
1 change: 0 additions & 1 deletion magic_admin/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from magic_admin.magic import Magic # noqa: F401


# Magic API secret key.
api_secret_key = None

Expand Down
16 changes: 4 additions & 12 deletions magic_admin/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ def __str__(self):
return self._message or "<empty message>"

def __repr__(self):
return "{error_class}(message={message!r})".format(
error_class=self.__class__.__name__,
message=self._message,
)
return f"{self.__class__.__name__}(message={self._message!r})"

def to_dict(self):
return {"message": str(self)}
Expand Down Expand Up @@ -61,14 +58,9 @@ def __init__(

def __repr__(self):
return (
"{error_class}(message={message!r}, "
"http_error_code={http_error_code}, "
"http_code={http_code}).".format(
error_class=self.__class__.__name__,
message=self._message or None,
http_error_code=self.http_error_code or None,
http_code=self.http_code or None,
)
f"{self.__class__.__name__}(message={self._message or None!r}, "
f"http_error_code={self.http_error_code or None}, "
f"http_code={self.http_code or None})."
)

def to_dict(self):
Expand Down
23 changes: 12 additions & 11 deletions magic_admin/http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@

import magic_admin
from magic_admin import version
from magic_admin.config import api_secret_api_key_missing_message
from magic_admin.config import base_url
from magic_admin.error import APIConnectionError
from magic_admin.error import APIError
from magic_admin.error import AuthenticationError
from magic_admin.error import BadRequestError
from magic_admin.error import ForbiddenError
from magic_admin.error import RateLimitingError
from magic_admin.config import api_secret_api_key_missing_message, base_url
from magic_admin.error import (
APIConnectionError,
APIError,
AuthenticationError,
BadRequestError,
ForbiddenError,
RateLimitingError,
)
from magic_admin.response import MagicResponse


Expand All @@ -37,8 +38,8 @@ def _get_platform_info():
]:
try:
val = str(func())
except Exception as e:
val = "<{}>".format(str(e))
except Exception as e: # noqa: BLE001
val = f"<{e!s}>"

platform_info[attr] = val

Expand Down Expand Up @@ -89,7 +90,7 @@ def request(self, method, url, params=None, data=None):
headers=self._get_request_headers(),
timeout=self._timeout,
)
except Exception as e:
except Exception as e: # noqa: BLE001
return self._handle_request_error(e)

return self._parse_and_convert_to_api_response(
Expand Down
4 changes: 1 addition & 3 deletions magic_admin/magic.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import os

import magic_admin
from magic_admin.config import api_secret_api_key_missing_message
from magic_admin.config import base_url
from magic_admin.config import api_secret_api_key_missing_message, base_url
from magic_admin.error import AuthenticationError
from magic_admin.http_client import RequestsClient
from magic_admin.resources.base import ResourceComponent


RETRIES = 3
TIMEOUT = 10
BACKOFF_FACTOR = 0.02
Expand Down
2 changes: 1 addition & 1 deletion magic_admin/resources/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from magic_admin.resources.token import Token # noqa: F401
from magic_admin.resources.user import User # noqa: F401
from magic_admin.resources.wallet import WalletType # noqa: F401
from magic_admin.resources.utils import Utils # noqa: F401
from magic_admin.resources.wallet import WalletType # noqa: F401
12 changes: 3 additions & 9 deletions magic_admin/resources/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,17 @@ def __getattr__(self, resource_name):
return self._registry[resource_name]
else:
raise AttributeError(
"{object_name} has no attribute '{resource_name}'".format(
object_name=self.__class__.__name__,
resource_name=resource_name,
),
f"{self.__class__.__name__} has no attribute '{resource_name}'",
)

def setup_request_client(self, retries, timeout, backoff_factor):
_request_client = RequestsClient(retries, timeout, backoff_factor)

for resource in self._registry.values():
setattr(resource, "_request_client", _request_client)
resource._request_client = _request_client

def _construct_url(self, url_path):
return "{base_url}{url_path}".format(
base_url=self._base_url,
url_path=url_path,
)
return f"{self._base_url}{url_path}"

def _sanitize_request_data(self, data):
if isinstance(data, dict):
Expand Down
16 changes: 5 additions & 11 deletions magic_admin/resources/token.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,10 @@
from web3.auto import w3

import magic_admin
from magic_admin.error import DIDTokenExpired
from magic_admin.error import DIDTokenInvalid
from magic_admin.error import DIDTokenMalformed
from magic_admin.error import DIDTokenExpired, DIDTokenInvalid, DIDTokenMalformed
from magic_admin.resources.base import ResourceComponent
from magic_admin.utils.did_token import parse_public_address_from_issuer
from magic_admin.utils.time import apply_did_token_nbf_grace_period
from magic_admin.utils.time import epoch_time_now

from magic_admin.utils.time import apply_did_token_nbf_grace_period, epoch_time_now

EXPECTED_DID_TOKEN_CONTENT_LENGTH = 2

Expand Down Expand Up @@ -47,9 +43,7 @@ def _check_required_fields(cls, claim):

if missing_fields:
raise DIDTokenMalformed(
message="DID token is missing required field(s): {}".format(
sorted(missing_fields),
),
message=f"DID token is missing required field(s): {sorted(missing_fields)}",
)

@classmethod
Expand All @@ -69,7 +63,7 @@ def decode(cls, did_token):
decoded_did_token = json.loads(
base64.urlsafe_b64decode(did_token).decode("utf-8"),
)
except Exception as e:
except Exception as e: # noqa: BLE001
raise DIDTokenMalformed(
message="DID token is malformed. It has to be a based64 encoded "
"JSON serialized string. {err} ({msg}).".format(
Expand All @@ -88,7 +82,7 @@ def decode(cls, did_token):

try:
claim = json.loads(decoded_did_token[1])
except Exception as e:
except Exception as e: # noqa: BLE001
raise DIDTokenMalformed(
message="DID token is malformed. Given claim should be a JSON "
"serialized string. {err} ({msg}).".format(
Expand Down
19 changes: 12 additions & 7 deletions magic_admin/resources/utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
from magic_admin.resources.base import ResourceComponent
from magic_admin.error import DIDTokenMalformed, DIDTokenExpired
from magic_admin.error import ExpectedBearerStringError
from web3 import Web3
import json

from web3 import Web3

from magic_admin.error import (
DIDTokenExpired,
DIDTokenMalformed,
ExpectedBearerStringError,
)
from magic_admin.resources.base import ResourceComponent


class Utils(ResourceComponent):
"""
Expand Down Expand Up @@ -36,7 +41,7 @@ def validate_token_ownership(
contract_address: str,
contract_type: str,
rpc_url: str,
token_id: str = None,
token_id: str | None = None,
) -> dict:
"""
Token Gating function validates user ownership of wallet + NFT.
Expand Down Expand Up @@ -80,8 +85,8 @@ def validate_token_ownership(
"error_code": "UNAUTHORIZED",
"message": "Invalid DID token: ERROR_DIDT_EXPIRED",
}
except Exception as e:
raise Exception(str(e))
except Exception as e: # noqa: BLE001
raise Exception(str(e)) # noqa: TRY002

# Check on-chain if user owns NFT by calling contract with web3
w3 = Web3(Web3.HTTPProvider(rpc_url))
Expand Down
6 changes: 3 additions & 3 deletions magic_admin/utils/did_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ def parse_public_address_from_issuer(issuer):
return issuer.split(":")[2]
except IndexError:
raise DIDTokenMalformed(
"Given issuer ({}) is malformed. Please make sure it follows the "
"`did:method-name:method-specific-id` format.".format(issuer),
f"Given issuer ({issuer}) is malformed. Please make sure it follows the "
"`did:method-name:method-specific-id` format.",
)


def construct_issuer_with_public_address(public_address):
return "did:ethr:{}".format(public_address)
return f"did:ethr:{public_address}"
2 changes: 1 addition & 1 deletion tests/integration/magic_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_gets_resource(self, resource_name):

def test_raises_attr_error(self):
with pytest.raises(AttributeError):
Magic(api_secret_key=self.api_secret_key).troll_goat
_ = Magic(api_secret_key=self.api_secret_key).troll_goat

def test_raises_authentication_error_if_secret_key_missing(self):
with pytest.raises(AuthenticationError):
Expand Down
12 changes: 7 additions & 5 deletions tests/integration/resources/token_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
from pretend import stub

from magic_admin.resources.token import Token
from testing.data.did_token import claim
from testing.data.did_token import future_did_token
from testing.data.did_token import issuer
from testing.data.did_token import proof
from testing.data.did_token import public_address
from testing.data.did_token import (
claim,
future_did_token,
issuer,
proof,
public_address,
)


class TestToken:
Expand Down
52 changes: 28 additions & 24 deletions tests/unit/error_test.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
from magic_admin.error import APIConnectionError
from magic_admin.error import APIError
from magic_admin.error import AuthenticationError
from magic_admin.error import BadRequestError
from magic_admin.error import DIDTokenInvalid
from magic_admin.error import ForbiddenError
from magic_admin.error import MagicError
from magic_admin.error import RateLimitingError
from magic_admin.error import RequestError
from typing import ClassVar

from magic_admin.error import (
APIConnectionError,
APIError,
AuthenticationError,
BadRequestError,
DIDTokenInvalid,
ForbiddenError,
MagicError,
RateLimitingError,
RequestError,
)


class MagicErrorBase:
Expand All @@ -21,9 +25,10 @@ def test_str_with_empty_message(self):
assert str(self.error_class()) == "<empty message>"

def test_repr(self):
assert repr(
self.error_class(self.message)
) == "{}(message='Magic is amazing')".format(self.error_class.__name__)
assert (
repr(self.error_class(self.message))
== f"{self.error_class.__name__}(message='Magic is amazing')"
)

def test_to_dict(self):
assert self.error_class(self.message).to_dict() == {
Expand All @@ -49,11 +54,11 @@ class RequestErrorBase:
message = "Magic is amazing"
http_status = "success"
http_code = 200
http_resp_data = {"magic": "link"}
http_resp_data: ClassVar[dict[str, str]] = {"magic": "link"}
http_message = "Troll goat is cute"
http_error_code = "TROLL_GOAT_IS_CUTE"
http_request_params = "a=b&b=c"
http_request_data = {"magic": "link"}
http_request_data: ClassVar[dict[str, str]] = {"magic": "link"}
http_method = "post"

def test_str(self):
Expand All @@ -63,16 +68,15 @@ def test_str_with_empty_message(self):
assert str(self.error_class()) == "<empty message>"

def test_repr(self):
assert repr(
self.error_class(
self.message,
http_error_code=self.http_error_code,
http_code=self.http_code,
),
) == "{}(message='Magic is amazing', http_error_code={}, http_code={}).".format(
self.error_class.__name__,
self.http_error_code,
self.http_code,
assert (
repr(
self.error_class(
self.message,
http_error_code=self.http_error_code,
http_code=self.http_code,
),
)
== f"{self.error_class.__name__}(message='Magic is amazing', http_error_code={self.http_error_code}, http_code={self.http_code})."
)

def test_to_dict(self):
Expand Down
Loading