diff --git a/twilio/auth_strategy/__init__.py b/twilio/auth_strategy/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/twilio/auth_strategy/auth_strategy.py b/twilio/auth_strategy/auth_strategy.py new file mode 100644 index 000000000..223cbff08 --- /dev/null +++ b/twilio/auth_strategy/auth_strategy.py @@ -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.""" diff --git a/twilio/auth_strategy/auth_type.py b/twilio/auth_strategy/auth_type.py new file mode 100644 index 000000000..61886f925 --- /dev/null +++ b/twilio/auth_strategy/auth_type.py @@ -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 diff --git a/twilio/auth_strategy/no_auth_strategy.py b/twilio/auth_strategy/no_auth_strategy.py new file mode 100644 index 000000000..a5bfd6d27 --- /dev/null +++ b/twilio/auth_strategy/no_auth_strategy.py @@ -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 diff --git a/twilio/auth_strategy/token_auth_strategy.py b/twilio/auth_strategy/token_auth_strategy.py new file mode 100644 index 000000000..ee51f05a4 --- /dev/null +++ b/twilio/auth_strategy/token_auth_strategy.py @@ -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 diff --git a/twilio/base/client_base.py b/twilio/base/client_base.py index 5f17c7540..b16f85bf5 100644 --- a/twilio/base/client_base.py +++ b/twilio/base/client_base.py @@ -4,10 +4,10 @@ from urllib.parse import urlparse, urlunparse from twilio import __version__ -from twilio.base.exceptions import TwilioException from twilio.http import HttpClient from twilio.http.http_client import TwilioHttpClient from twilio.http.response import Response +from twilio.credential.credential_provider import CredentialProvider class ClientBase(object): @@ -23,6 +23,7 @@ def __init__( environment: Optional[MutableMapping[str, str]] = None, edge: Optional[str] = None, user_agent_extensions: Optional[List[str]] = None, + credential_provider: Optional[CredentialProvider] = None, ): """ Initializes the Twilio Client @@ -35,7 +36,9 @@ def __init__( :param environment: Environment to look for auth details, defaults to os.environ :param edge: Twilio Edge to make requests to, defaults to None :param user_agent_extensions: Additions to the user agent string + :param credential_provider: credential provider for authentication method that needs to be used """ + environment = environment or os.environ self.username = username or environment.get("TWILIO_ACCOUNT_SID") @@ -48,9 +51,8 @@ def __init__( """ :type : str """ self.user_agent_extensions = user_agent_extensions or [] """ :type : list[str] """ - - if not self.username or not self.password: - raise TwilioException("Credentials are required to create a TwilioClient") + self.credential_provider = credential_provider or None + """ :type : CredentialProvider """ self.account_sid = account_sid or self.username """ :type : str """ @@ -85,15 +87,27 @@ def request( :returns: Response from the Twilio API """ - auth = self.get_auth(auth) headers = self.get_headers(method, headers) - uri = self.get_hostname(uri) + if self.credential_provider: + + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + + if method == "DELETE": + del headers["Accept"] + + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) return self.http_client.request( method, uri, params=params, - data=data, + data=filtered_data, headers=headers, auth=auth, timeout=timeout, @@ -132,21 +146,44 @@ async def request_async( "http_client must be asynchronous to support async API requests" ) - auth = self.get_auth(auth) headers = self.get_headers(method, headers) - uri = self.get_hostname(uri) + if method == "DELETE": + del headers["Accept"] + + if self.credential_provider: + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + 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) + filtered_data = self.copy_non_none_values(data) return await self.http_client.request( method, uri, params=params, - data=data, + data=filtered_data, headers=headers, auth=auth, timeout=timeout, allow_redirects=allow_redirects, ) + def copy_non_none_values(self, data): + if isinstance(data, dict): + return { + k: self.copy_non_none_values(v) + for k, v in data.items() + if v is not None + } + elif isinstance(data, list): + return [ + self.copy_non_none_values(item) for item in data if item is not None + ] + return data + def get_auth(self, auth: Optional[Tuple[str, str]]) -> Tuple[str, str]: """ Get the request authentication object diff --git a/twilio/base/page.py b/twilio/base/page.py index 2238528da..b5b2da7b2 100644 --- a/twilio/base/page.py +++ b/twilio/base/page.py @@ -77,6 +77,8 @@ def load_page(self, payload: Dict[str, Any]): key = keys - self.META_KEYS if len(key) == 1: return payload[key.pop()] + if "Resources" in payload: + return payload["Resources"] raise TwilioException("Page Records can not be deserialized") diff --git a/twilio/base/version.py b/twilio/base/version.py index 64cc601fa..ed7e86f49 100644 --- a/twilio/base/version.py +++ b/twilio/base/version.py @@ -164,7 +164,6 @@ async def fetch_async( timeout=timeout, allow_redirects=allow_redirects, ) - return self._parse_fetch(method, uri, response) def _parse_update(self, method: str, uri: str, response: Response) -> Any: @@ -461,7 +460,6 @@ def create( timeout=timeout, allow_redirects=allow_redirects, ) - return self._parse_create(method, uri, response) async def create_async( @@ -488,5 +486,4 @@ async def create_async( timeout=timeout, allow_redirects=allow_redirects, ) - return self._parse_create(method, uri, response) diff --git a/twilio/credential/__init__.py b/twilio/credential/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/twilio/credential/credential_provider.py b/twilio/credential/credential_provider.py new file mode 100644 index 000000000..72aafeed4 --- /dev/null +++ b/twilio/credential/credential_provider.py @@ -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") diff --git a/twilio/credential/orgs_credential_provider.py b/twilio/credential/orgs_credential_provider.py new file mode 100644 index 000000000..e623f5232 --- /dev/null +++ b/twilio/credential/orgs_credential_provider.py @@ -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 OrgsCredentialProvider(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 diff --git a/twilio/http/http_client.py b/twilio/http/http_client.py index 9d329c6aa..e15be8635 100644 --- a/twilio/http/http_client.py +++ b/twilio/http/http_client.py @@ -88,10 +88,11 @@ def request( } if headers and headers.get("Content-Type") == "application/json": kwargs["json"] = data + elif headers and headers.get("Content-Type") == "application/scim+json": + kwargs["json"] = data else: kwargs["data"] = data self.log_request(kwargs) - self._test_only_last_response = None session = self.session or Session() request = Request(**kwargs) @@ -102,12 +103,11 @@ def request( settings = session.merge_environment_settings( prepped_request.url, self.proxy, None, None, None ) - response = session.send( prepped_request, allow_redirects=allow_redirects, timeout=timeout, - **settings + **settings, ) self.log_response(response.status_code, response) diff --git a/twilio/http/orgs_token_manager.py b/twilio/http/orgs_token_manager.py new file mode 100644 index 000000000..767ed270a --- /dev/null +++ b/twilio/http/orgs_token_manager.py @@ -0,0 +1,41 @@ +from twilio.http.token_manager import TokenManager +from twilio.rest import Client + + +class OrgTokenManager(TokenManager): + """ + Orgs Token Manager + """ + + def __init__( + self, + grant_type: str, + client_id: str, + client_secret: str, + code: str = None, + redirect_uri: str = None, + audience: str = None, + refreshToken: str = None, + scope: str = None, + ): + self.grant_type = grant_type + self.client_id = client_id + self.client_secret = client_secret + self.code = code + self.redirect_uri = redirect_uri + self.audience = audience + self.refreshToken = refreshToken + self.scope = scope + self.client = Client() + + def fetch_access_token(self): + token_instance = self.client.preview_iam.v1.token.create( + grant_type=self.grant_type, + client_id=self.client_id, + client_secret=self.client_secret, + code=self.code, + redirect_uri=self.redirect_uri, + audience=self.audience, + scope=self.scope, + ) + return token_instance.access_token diff --git a/twilio/http/token_manager.py b/twilio/http/token_manager.py new file mode 100644 index 000000000..28cc73101 --- /dev/null +++ b/twilio/http/token_manager.py @@ -0,0 +1,7 @@ +from twilio.base.version import Version + + +class TokenManager: + + def fetch_access_token(self, version: Version): + pass diff --git a/twilio/rest/__init__.py b/twilio/rest/__init__.py index 5c8f3ebcf..7874236a2 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -96,6 +96,7 @@ def __init__( environment=None, edge=None, user_agent_extensions=None, + credential_provider=None, ): """ Initializes the Twilio Client @@ -121,6 +122,7 @@ def __init__( environment, edge, user_agent_extensions, + credential_provider, ) # Domains @@ -135,6 +137,7 @@ def __init__( 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 self._ip_messaging: Optional["IpMessaging"] = None @@ -147,6 +150,7 @@ def __init__( self._numbers: Optional["Numbers"] = None self._oauth: Optional["Oauth"] = None self._preview: Optional["Preview"] = None + self._preview_iam: Optional["PreviewIam"] = None self._pricing: Optional["Pricing"] = None self._proxy: Optional["Proxy"] = None self._routes: Optional["Routes"] = None @@ -396,6 +400,19 @@ def microvisor(self) -> "Microvisor": self._microvisor = Microvisor(self) return self._microvisor + @property + def preview_iam(self) -> "PreviewIam": + """ + Access the PreviewIam Twilio Domain + + :returns: PreviewIam Twilio Domain + """ + if self._preview_iam is None: + from twilio.rest.preview_iam import PreviewIam + + self._preview_iam = PreviewIam(self) + return self._preview_iam + @property def monitor(self) -> "Monitor": """ diff --git a/twilio/rest/preview_iam/PreviewIamBase.py b/twilio/rest/preview_iam/PreviewIamBase.py new file mode 100644 index 000000000..d8735295d --- /dev/null +++ b/twilio/rest/preview_iam/PreviewIamBase.py @@ -0,0 +1,47 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from twilio.base.domain import Domain +from typing import Optional +from twilio.rest import Client + +from twilio.rest.preview_iam.v1 import V1 +from twilio.rest.preview_iam.versionless import Versionless + + +class PreviewIamBase(Domain): + def __init__(self, twilio: Client): + """ + Initialize the PreviewIam Domain + + :returns: Domain for PreviewIam + """ + super().__init__(twilio, "https://preview-iam.twilio.com") + self._versionless: Optional[Versionless] = None + self._v1: Optional[V1] = None + + @property + def versionless(self) -> Versionless: + """ + :returns: Versionless of PreviewIam + """ + if self._versionless is None: + self._versionless = Versionless(self) + return self._versionless + + @property + def v1(self) -> V1: + """ + :returns: V1 of PreviewIam + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 diff --git a/twilio/rest/preview_iam/__init__.py b/twilio/rest/preview_iam/__init__.py new file mode 100644 index 000000000..910343622 --- /dev/null +++ b/twilio/rest/preview_iam/__init__.py @@ -0,0 +1,25 @@ +from twilio.rest.preview_iam.PreviewIamBase import PreviewIamBase + +from twilio.rest.preview_iam.v1.authorize import ( + AuthorizeList, +) +from twilio.rest.preview_iam.v1.token import ( + TokenList, +) +from twilio.rest.preview_iam.versionless.organization import ( + OrganizationList, +) + + +class PreviewIam(PreviewIamBase): + @property + def organization(self) -> OrganizationList: + return self.versionless.organization + + @property + def authorize(self) -> AuthorizeList: + return self.v1.authorize + + @property + def token(self) -> TokenList: + return self.v1.token diff --git a/twilio/rest/preview_iam/v1/__init__.py b/twilio/rest/preview_iam/v1/__init__.py new file mode 100644 index 000000000..224327779 --- /dev/null +++ b/twilio/rest/preview_iam/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview_iam.v1.authorize import AuthorizeList +from twilio.rest.preview_iam.v1.token import TokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "v1") + self._authorize: Optional[AuthorizeList] = None + self._token: Optional[TokenList] = None + + @property + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/v1/authorize.py b/twilio/rest/preview_iam/v1/authorize.py new file mode 100644 index 000000000..051f13a8e --- /dev/null +++ b/twilio/rest/preview_iam/v1/authorize.py @@ -0,0 +1,126 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AuthorizeInstance(InstanceResource): + """ + :ivar redirect_to: The callback URL + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class AuthorizeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/authorize" + + def fetch( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/v1/token.py b/twilio/rest/preview_iam/v1/token.py new file mode 100644 index 000000000..81eed237f --- /dev/null +++ b/twilio/rest/preview_iam/v1/token.py @@ -0,0 +1,162 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/__init__.py b/twilio/rest/preview_iam/versionless/__init__.py new file mode 100644 index 000000000..7d6d210f1 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview_iam.versionless.organization import OrganizationList + + +class Versionless(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Versionless version of PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "Organizations") + self._organization: Optional[OrganizationList] = None + + @property + def organization(self) -> OrganizationList: + if self._organization is None: + self._organization = OrganizationList(self) + return self._organization + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/organization/__init__.py b/twilio/rest/preview_iam/versionless/organization/__init__.py new file mode 100644 index 000000000..ce6e70e97 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/__init__.py @@ -0,0 +1,128 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.instance_context import InstanceContext + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.preview_iam.versionless.organization.account import AccountList +from twilio.rest.preview_iam.versionless.organization.role_assignment import ( + RoleAssignmentList, +) +from twilio.rest.preview_iam.versionless.organization.user import UserList + + +class OrganizationContext(InstanceContext): + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the OrganizationContext + + :param version: Version that contains the resource + :param organization_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}".format(**self._solution) + + self._accounts: Optional[AccountList] = None + self._role_assignments: Optional[RoleAssignmentList] = None + self._users: Optional[UserList] = None + + @property + def accounts(self) -> AccountList: + """ + Access the accounts + """ + if self._accounts is None: + self._accounts = AccountList( + self._version, + self._solution["organization_sid"], + ) + return self._accounts + + @property + def role_assignments(self) -> RoleAssignmentList: + """ + Access the role_assignments + """ + if self._role_assignments is None: + self._role_assignments = RoleAssignmentList( + self._version, + self._solution["organization_sid"], + ) + return self._role_assignments + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["organization_sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OrganizationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OrganizationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, organization_sid: str) -> OrganizationContext: + """ + Constructs a OrganizationContext + + :param organization_sid: + """ + return OrganizationContext(self._version, organization_sid=organization_sid) + + def __call__(self, organization_sid: str) -> OrganizationContext: + """ + Constructs a OrganizationContext + + :param organization_sid: + """ + return OrganizationContext(self._version, organization_sid=organization_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/organization/account.py b/twilio/rest/preview_iam/versionless/organization/account.py new file mode 100644 index 000000000..f1c801986 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/account.py @@ -0,0 +1,438 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AccountInstance(InstanceResource): + """ + :ivar account_sid: Twilio account sid + :ivar friendly_name: Account friendly name + :ivar status: Account status + :ivar owner_sid: Twilio account sid + :ivar date_created: The date and time when the account was created in the system + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + account_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "organization_sid": organization_sid, + "account_sid": account_sid or self.account_sid, + } + self._context: Optional[AccountContext] = None + + @property + def _proxy(self) -> "AccountContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountContext for this AccountInstance + """ + if self._context is None: + self._context = AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + return self._context + + def fetch(self) -> "AccountInstance": + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountInstance": + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountContext(InstanceContext): + + def __init__(self, version: Version, organization_sid: str, account_sid: str): + """ + Initialize the AccountContext + + :param version: Version that contains the resource + :param organization_sid: + :param account_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "account_sid": account_sid, + } + self._uri = "/{organization_sid}/Accounts/{account_sid}".format( + **self._solution + ) + + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + async def fetch_async(self) -> AccountInstance: + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: + """ + Build an instance of AccountInstance + + :param payload: Payload response from the API + """ + return AccountInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AccountList(ListResource): + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the AccountList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/Accounts".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountInstance]: + """ + Streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AccountInstance]: + """ + Asynchronously streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Asynchronously lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Asynchronously retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AccountPage: + """ + Retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AccountPage: + """ + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountPage(self._version, response, self._solution) + + def get(self, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param account_sid: + """ + return AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=account_sid, + ) + + def __call__(self, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param account_sid: + """ + return AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=account_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/organization/role_assignment.py b/twilio/rest/preview_iam/versionless/organization/role_assignment.py new file mode 100644 index 000000000..9d356f2c7 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/role_assignment.py @@ -0,0 +1,574 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleAssignmentInstance(InstanceResource): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + """ + :ivar sid: Twilio Role Assignment Sid representing this role assignment + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing identity of this assignment + :ivar identity: Twilio Sid representing scope of this assignment + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("moreInfo") + self.status: Optional[int] = payload.get("status") + + self._solution = { + "organization_sid": organization_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleAssignmentContext] = None + + @property + def _proxy(self) -> "RoleAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleAssignmentContext for this RoleAssignmentInstance + """ + if self._context is None: + self._context = RoleAssignmentContext( + self._version, + organization_sid=self._solution["organization_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class RoleAssignmentContext(InstanceContext): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + def __init__(self, version: Version, organization_sid: str, sid: str): + """ + Initialize the RoleAssignmentContext + + :param version: Version that contains the resource + :param organization_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "sid": sid, + } + self._uri = "/{organization_sid}/RoleAssignments/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class RoleAssignmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleAssignmentInstance: + """ + Build an instance of RoleAssignmentInstance + + :param payload: Payload response from the API + """ + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleAssignmentList(ListResource): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the RoleAssignmentList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/RoleAssignments".format(**self._solution) + + def create( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> RoleAssignmentInstance: + """ + Create the RoleAssignmentInstance + + :param public_api_create_role_assignment_request: + + :returns: The created RoleAssignmentInstance + """ + data = public_api_create_role_assignment_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + async def create_async( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> RoleAssignmentInstance: + """ + Asynchronously create the RoleAssignmentInstance + + :param public_api_create_role_assignment_request: + + :returns: The created RoleAssignmentInstance + """ + data = public_api_create_role_assignment_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def stream( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleAssignmentInstance]: + """ + Streams RoleAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, scope=scope, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleAssignmentInstance]: + """ + Asynchronously streams RoleAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + identity=identity, scope=scope, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleAssignmentInstance]: + """ + Lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + scope=scope, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleAssignmentInstance]: + """ + Asynchronously lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + scope=scope, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoleAssignmentPage: + """ + Retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleAssignmentInstance + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoleAssignmentPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoleAssignmentPage: + """ + Asynchronously retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleAssignmentInstance + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoleAssignmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RoleAssignmentPage: + """ + Retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoleAssignmentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RoleAssignmentPage: + """ + Asynchronously retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoleAssignmentPage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param sid: + """ + return RoleAssignmentContext( + self._version, organization_sid=self._solution["organization_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param sid: + """ + return RoleAssignmentContext( + self._version, organization_sid=self._solution["organization_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/organization/user.py b/twilio/rest/preview_iam/versionless/organization/user.py new file mode 100644 index 000000000..166f76b42 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/user.py @@ -0,0 +1,1050 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserInstance(InstanceResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") + self.name: Optional[UserList.str] = payload.get("name") + self.emails: Optional[List[UserList.str]] = payload.get("emails") + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.str] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scimType") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("moreInfo") + + self._solution = { + "organization_sid": organization_sid, + "id": id or self.id, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> "UserInstance": + """ + Update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + return self._proxy.update( + scim_user=scim_user, + if_match=if_match, + ) + + async def update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + scim_user=scim_user, + if_match=if_match, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + def __init__(self, version: Version, organization_sid: str, id: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param organization_sid: + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "id": id, + } + self._uri = "/{organization_sid}/scim/Users/{id}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> UserInstance: + """ + Update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UserList(ListResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/scim/Users".format(**self._solution) + + def create(self, scim_user: ScimUser) -> UserInstance: + """ + Create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + async def create_async(self, scim_user: ScimUser) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def stream( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str filter: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(filter=filter, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str filter: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(filter=filter, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str filter: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + filter=filter, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str filter: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + filter=filter, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "filter": filter, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/scim+json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "filter": filter, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/scim+json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, id: str) -> UserContext: + """ + Constructs a UserContext + + :param id: + """ + return UserContext( + self._version, organization_sid=self._solution["organization_sid"], id=id + ) + + def __call__(self, id: str) -> UserContext: + """ + Constructs a UserContext + + :param id: + """ + return UserContext( + self._version, organization_sid=self._solution["organization_sid"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return ""