From 35b5015909953ee62871e8ce03036fae647ee4df Mon Sep 17 00:00:00 2001 From: AsabuHere Date: Sun, 6 Oct 2024 14:11:11 +0530 Subject: [PATCH] Uptake of review comments --- twilio/auth_strategy/token_auth_strategy.py | 27 ++++++++++++------- twilio/base/client_base.py | 9 +++++-- twilio/credential/orgs_credential_provider.py | 6 +++-- twilio/http/http_client.py | 6 +---- twilio/rest/__init__.py | 1 + 5 files changed, 30 insertions(+), 19 deletions(-) diff --git a/twilio/auth_strategy/token_auth_strategy.py b/twilio/auth_strategy/token_auth_strategy.py index 88b0d787f..a21ea44be 100644 --- a/twilio/auth_strategy/token_auth_strategy.py +++ b/twilio/auth_strategy/token_auth_strategy.py @@ -18,8 +18,7 @@ def __init__(self, token_manager: TokenManager): self.logger = logging.getLogger(__name__) def get_auth_string(self) -> str: - if self.token is None: - self.fetch_token() + self.fetch_token() return f"Bearer {self.token}" def requires_authentication(self) -> bool: @@ -28,15 +27,23 @@ def requires_authentication(self) -> bool: def fetch_token(self): self.logger.info("New token fetched for accessing organization API") if self.token is None or self.token == "" or self.is_token_expired(self.token): - with self.lock: + with self.lock: if self.token is None or self.token == "" or self.is_token_expired(self.token): self.token = self.token_manager.fetch_access_token() def is_token_expired(self, token): - print(f'token is {token}') - decoded_jwt = jwt.decode(token, options={"verify_signature": True}, algorithms=["RS256"]) - expires_at = decoded_jwt.get("exp") - # Add a buffer of 30 seconds - buffer_seconds = 30 - buffer_expires_at = expires_at - buffer_seconds - return buffer_expires_at < datetime.datetime.now().timestamp() \ No newline at end of file + try: + decoded = jwt.decode(token, options={"verify_signature": False}) + exp = decoded.get('exp') + + if exp is None: + return True # No expiration time present, consider it expired + + # Check if the expiration time has passed + return datetime.fromtimestamp(exp) < datetime.utcnow() + + except jwt.DecodeError: + return True # Token is invalid + except Exception as e: + print(f"An error occurred: {e}") + return True \ No newline at end of file diff --git a/twilio/base/client_base.py b/twilio/base/client_base.py index 1fdc689ea..8526bdd33 100644 --- a/twilio/base/client_base.py +++ b/twilio/base/client_base.py @@ -96,8 +96,10 @@ def request( if self.credential_provider: auth_strategy = self.credential_provider.to_auth_strategy() headers["Authorization"] = auth_strategy.get_auth_string() - else: + elif self.username is not None and self.password is not None: auth = self.get_auth(auth) + else: + auth = None uri = self.get_hostname(uri) @@ -150,11 +152,14 @@ async def request_async( ##If credential provider is provided by user, get the associated auth strategy ##Using the auth strategy, fetch the auth string and set it to authorization header + if self.credential_provider: auth_strategy = self.credential_provider.to_auth_strategy() headers["Authorization"] = auth_strategy.get_auth_string() - else: + elif self.username is not None and self.password is not None: auth = self.get_auth(auth) + else: + auth = None uri = self.get_hostname(uri) diff --git a/twilio/credential/orgs_credential_provider.py b/twilio/credential/orgs_credential_provider.py index 4e58271a9..6ec31441e 100644 --- a/twilio/credential/orgs_credential_provider.py +++ b/twilio/credential/orgs_credential_provider.py @@ -18,9 +18,11 @@ def __init__(self, client_id: str, client_secret: str, token_manager=None): self.client_id = client_id self.client_secret = client_secret self.token_manager = token_manager + self.auth_strategy = None def to_auth_strategy(self): if self.token_manager is None: self.token_manager = OrgTokenManager(self.grant_type, self.client_id, self.client_secret) - - return TokenAuthStrategy(self.token_manager) + if self.auth_strategy is None: + self.auth_strategy = TokenAuthStrategy(self.token_manager) + return self.auth_strategy diff --git a/twilio/http/http_client.py b/twilio/http/http_client.py index 0e3e7638f..27617fb7a 100644 --- a/twilio/http/http_client.py +++ b/twilio/http/http_client.py @@ -78,11 +78,6 @@ def request( elif timeout <= 0: raise ValueError(timeout) - if headers: - if "Requires-Authentication" in headers: - headers.pop("Requires-Authentication", None) - auth = None - kwargs = { "method": method.upper(), "url": url, @@ -96,6 +91,7 @@ def request( else: kwargs["data"] = data self.log_request(kwargs) + print(f'args : {kwargs}') self._test_only_last_response = None session = self.session or Session() request = Request(**kwargs) diff --git a/twilio/rest/__init__.py b/twilio/rest/__init__.py index 458168fa2..7874236a2 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -136,6 +136,7 @@ def __init__( self._events: Optional["Events"] = None self._flex_api: Optional["FlexApi"] = None self._frontline_api: Optional["FrontlineApi"] = None + self._iam: Optional["Iam"] = None self._preview_iam: Optional["PreviewIam"] = None self._insights: Optional["Insights"] = None self._intelligence: Optional["Intelligence"] = None