-
Notifications
You must be signed in to change notification settings - Fork 718
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
feat: Adding examples for orgs api uptake and public oauth #824
Closed
Closed
Changes from all commits
Commits
Show all changes
36 commits
Select commit
Hold shift + click to select a range
b4c5734
feat: oauth sdk implementation (#799)
manisha1997 3e246e4
Python Orgs Api Changes
AsabuHere 8395487
removing unwanted logs
AsabuHere bc5c16b
removing unwanted logs
AsabuHere a66f9e9
removing unwanted logs
AsabuHere b5a6490
removing unwanted logs
AsabuHere fac26ee
Fixing token fetch flow
AsabuHere 15e15c0
twilio python changes for orgs api uptake
AsabuHere 7b07ba7
twilio python changes for orgs api uptake
AsabuHere af11fd2
Update test_cluster.py
AsabuHere 661785d
Update test_cluster.py
AsabuHere 6a8c2d8
twilio python changes for orgs api uptake
AsabuHere 1ba2f9b
twilio python changes for orgs api uptake
AsabuHere 98708f0
twilio python changes for orgs api uptake
AsabuHere d78d5d5
twilio python changes for orgs api uptake
AsabuHere 7bdf1b5
Merge branch 'main' into asabu_Python_changes
AsabuHere bc77770
twilio python changes for orgs api uptake
AsabuHere 0211f23
twilio python changes for orgs api uptake
AsabuHere 27dec32
twilio python changes for orgs api uptake
AsabuHere 2959689
twilio python changes for orgs api uptake
AsabuHere b973065
Uptake of review comments
AsabuHere ceebd46
modified error messages
AsabuHere 35b5015
Uptake of review comments
AsabuHere 76fecab
Merge branch 'main' into asabu_Python_changes
AsabuHere e9eaa72
Organization api uptake changes
AsabuHere 1c8420c
Organization api uptake changes
AsabuHere 644f94b
Organization api uptake changes
AsabuHere 66f3e28
Organization api uptake changes
AsabuHere 88f6623
removing accept headers for delete operation
AsabuHere 630c28c
Removing unwanted code
AsabuHere 26ee4d3
Merge branch 'main' into asabu_Python_changes
AsabuHere ddb336b
Modified generated files
AsabuHere d79366e
removing unwamted logs
AsabuHere 824ed9f
Formatting changes
AsabuHere 3670f03
make prettier run
AsabuHere eafd8dd
Adding examples and pushing client token manager and cred provider
AsabuHere File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import os | ||
|
||
from twilio.rest import Client | ||
from twilio.credential.orgs_credential_provider import OrgsCredentialProvider | ||
|
||
API_KEY = os.environ.get("TWILIO_API_KEY") | ||
API_SECRET = os.environ.get("TWILIO_API_SECRET") | ||
ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") | ||
CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID") | ||
CLIENT_SECRET = os.environ.get("TWILIO_CLIENT_SECRET") | ||
ORGS_SID = os.environ.get("TWILIO_ORGS_SID") | ||
|
||
|
||
def example(self=None): | ||
""" | ||
Some example usage of fetching accounts within an organization | ||
""" | ||
self.client = Client( | ||
username=API_KEY, | ||
password=API_SECRET, | ||
account_sid=ACCOUNT_SID, | ||
credential_provider= OrgsCredentialProvider(CLIENT_ID, CLIENT_SECRET) | ||
) | ||
accounts = self.client.preview_iam.organization(organization_sid=ORGS_SID).accounts.stream() | ||
self.assertIsNotNone(accounts) | ||
|
||
if __name__ == "__main__": | ||
example() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import os | ||
|
||
from twilio.rest import Client | ||
from twilio.credential.client_credential_provider import ClientCredentialProvider | ||
|
||
API_KEY = os.environ.get("TWILIO_API_KEY") | ||
API_SECRET = os.environ.get("TWILIO_API_SECRET") | ||
ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") | ||
CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID") | ||
CLIENT_SECRET = os.environ.get("TWILIO_CLIENT_SECRET") | ||
ORGS_SID = os.environ.get("TWILIO_ORGS_SID") | ||
FROM_NUMBER = os.environ.get("TWILIO_FROM_NUMBER") | ||
TO_NUMBER = os.environ.get("TWILIO_TO_NUMBER") | ||
|
||
|
||
def example(self=None): | ||
""" | ||
Some example usage of fetching accounts within an organization | ||
""" | ||
self.client = Client( | ||
username=API_KEY, | ||
password=API_SECRET, | ||
account_sid=ACCOUNT_SID, | ||
credential_provider= ClientCredentialProvider(CLIENT_ID, CLIENT_SECRET) | ||
) | ||
msg = self.client.messages.create( | ||
to=self.to_number, from_=self.from_number, body="hello world" | ||
) | ||
self.assertEqual(msg.to, self.to_number) | ||
self.assertEqual(msg.from_, self.from_number) | ||
self.assertEqual(msg.body, "hello world") | ||
self.assertIsNotNone(msg.sid) | ||
|
||
if __name__ == "__main__": | ||
example() |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
from twilio.auth_strategy.auth_type import AuthType | ||
from abc import abstractmethod | ||
|
||
|
||
class AuthStrategy(object): | ||
def __init__(self, auth_type: AuthType): | ||
self._auth_type = auth_type | ||
|
||
@property | ||
def auth_type(self) -> AuthType: | ||
return self._auth_type | ||
|
||
@abstractmethod | ||
def get_auth_string(self) -> str: | ||
"""Return the authentication string.""" | ||
|
||
@abstractmethod | ||
def requires_authentication(self) -> bool: | ||
"""Return True if authentication is required, else False.""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
from enum import Enum | ||
|
||
|
||
class AuthType(Enum): | ||
ORGS_TOKEN = "orgs_stoken" | ||
NO_AUTH = "noauth" | ||
BASIC = "basic" | ||
API_KEY = "api_key" | ||
CLIENT_CREDENTIALS = "client_credentials" | ||
|
||
def __str__(self): | ||
return self.value |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
from auth_type import AuthType | ||
from twilio.auth_strategy.auth_strategy import AuthStrategy | ||
|
||
|
||
class NoAuthStrategy(AuthStrategy): | ||
def __init__(self): | ||
super().__init__(AuthType.NO_AUTH) | ||
|
||
def get_auth_string(self) -> str: | ||
return "" | ||
|
||
def requires_authentication(self) -> bool: | ||
return False |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import jwt | ||
import threading | ||
import logging | ||
from datetime import datetime | ||
|
||
from twilio.auth_strategy.auth_type import AuthType | ||
from twilio.auth_strategy.auth_strategy import AuthStrategy | ||
from twilio.http.token_manager import TokenManager | ||
|
||
|
||
class TokenAuthStrategy(AuthStrategy): | ||
def __init__(self, token_manager: TokenManager): | ||
super().__init__(AuthType.ORGS_TOKEN) | ||
self.token_manager = token_manager | ||
self.token = None | ||
self.lock = threading.Lock() | ||
logging.basicConfig(level=logging.INFO) | ||
self.logger = logging.getLogger(__name__) | ||
|
||
def get_auth_string(self) -> str: | ||
self.fetch_token() | ||
return f"Bearer {self.token}" | ||
|
||
def requires_authentication(self) -> bool: | ||
return True | ||
|
||
def fetch_token(self): | ||
if self.token is None or self.token == "" or self.is_token_expired(self.token): | ||
with self.lock: | ||
if ( | ||
self.token is None | ||
or self.token == "" | ||
or self.is_token_expired(self.token) | ||
): | ||
self.logger.info("New token fetched for accessing organization API") | ||
self.token = self.token_manager.fetch_access_token() | ||
|
||
def is_token_expired(self, token): | ||
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
from twilio.http.orgs_token_manager import OrgTokenManager | ||
from twilio.base.exceptions import TwilioException | ||
from twilio.credential.credential_provider import CredentialProvider | ||
from twilio.auth_strategy.auth_type import AuthType | ||
from twilio.auth_strategy.token_auth_strategy import TokenAuthStrategy | ||
|
||
|
||
class ClientCredentialProvider(CredentialProvider): | ||
def __init__(self, client_id: str, client_secret: str, token_manager=None): | ||
super().__init__(AuthType.CLIENT_CREDENTIALS) | ||
|
||
if client_id is None or client_secret is None: | ||
raise TwilioException("Client id and Client secret are mandatory") | ||
|
||
self.grant_type = "client_credentials" | ||
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 | ||
) | ||
if self.auth_strategy is None: | ||
self.auth_strategy = TokenAuthStrategy(self.token_manager) | ||
return self.auth_strategy |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
from twilio.auth_strategy.auth_type import AuthType | ||
|
||
|
||
class CredentialProvider: | ||
def __init__(self, auth_type: AuthType): | ||
self._auth_type = auth_type | ||
|
||
@property | ||
def auth_type(self) -> AuthType: | ||
return self._auth_type | ||
|
||
def to_auth_strategy(self): | ||
raise NotImplementedError("Subclasses must implement this method") |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / SonarCloud
JWT should be signed and verified