o
    is                      @   s   d dl Z d dlZd dlmZmZ d dlZd dlZd dlmZ d dl	m
Z
 ddlmZ ddlmZ ddlmZmZmZmZ G d	d
 d
eZdd ZdS )    N)DictAny)urlparse)ClientAuthenticationError   )CredentialUnavailableError)DEVELOPER_SIGN_ON_CLIENT_ID)AuthCodeRedirectServerInteractiveCredentialwrap_exceptions
within_dacc                       s@   e Zd ZdZdeddf fddZededefdd	Z	  Z
S )
InteractiveBrowserCredentiala  Opens a browser to interactively authenticate a user.

    :func:`~get_token` opens a browser to a login URL provided by Microsoft Entra ID and authenticates a user
    there with the authorization code flow, using PKCE (Proof Key for Code Exchange) internally to protect the code.

    :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com",
        the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts`
        defines authorities for other clouds.
    :keyword str tenant_id: a Microsoft Entra tenant ID. Defaults to the "organizations" tenant, which can
        authenticate work or school accounts.
    :keyword str client_id: Client ID of the Microsoft Entra application that users will sign into. It is recommended
        that developers register their applications and assign appropriate roles. For more information,
        visit https://aka.ms/azsdk/identity/AppRegistrationAndRoleAssignment. If not specified, users will
        authenticate to an Azure development application, which is not recommended for production scenarios.
    :keyword str login_hint: a username suggestion to pre-fill the login page's username/email address field. A user
        may still log in with a different username.
    :keyword str redirect_uri: a redirect URI for the application identified by `client_id` as configured in Azure
        Active Directory, for example "http://localhost:8400". This is only required when passing a value for
        **client_id**, and must match a redirect URI in the application's registration. The credential must be able to
        bind a socket to this URI.
    :keyword AuthenticationRecord authentication_record: :class:`AuthenticationRecord` returned by :func:`authenticate`
    :keyword bool disable_automatic_authentication: if True, :func:`get_token` will raise
        :class:`AuthenticationRequiredError` when user interaction is required to acquire a token. Defaults to False.
    :keyword cache_persistence_options: configuration for persistent token caching. If unspecified, the credential
        will cache tokens in memory.
    :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions
    :keyword int timeout: seconds to wait for the user to complete authentication. Defaults to 300 (5 minutes).
    :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting
        to authenticate. Setting this to true will completely disable both instance discovery and authority validation.
        This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in
        private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from
        https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the
        authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and
        trustworthy.
    :keyword bool enable_support_logging: Enables additional support logging in the underlying MSAL library.
        This logging potentially contains personally identifiable information and is intended to be used only for
        troubleshooting purposes.
    :raises ValueError: invalid **redirect_uri**

    .. admonition:: Example:

        .. literalinclude:: ../samples/credential_creation_code_snippets.py
            :start-after: [START create_interactive_browser_credential]
            :end-before: [END create_interactive_browser_credential]
            :language: python
            :dedent: 4
            :caption: Create an InteractiveBrowserCredential.
    kwargsreturnNc                    s   | dd }|rt|| _| jjr| jjstdnd | _| dd | _| dd| _| dt| _	| dt
}tt| jdd|i| d S )	Nredirect_urizR"redirect_uri" must be a URL with port number, for example "http://localhost:8400"
login_hinttimeouti,  _server_class	client_id )popr   _parsed_urlhostnameport
ValueError_login_hint_timeoutr	   r   r   superr   __init__)selfr   r   r   	__class__r   Z/home/app/Keep/.python/lib/python3.10/site-packages/azure/identity/_credentials/browser.pyr   E   s   
z%InteractiveBrowserCredential.__init__scopesc              
   O   sh  d }d}| j r6zd| j j| j j}| j| j j| j j| jd}W n8 tjy5 } ztd| d|d }~ww t	ddD ]}z| jd|| jd}d	|}W  n
 tjyX   Y q;w |s`td
dt
|}|d}| jdi |}|j||d|| jd}	d|	vrtdt|	d stdd| }
|
st rtd| jdtd| jd|j|	|
||dS )N zhttp://{}:{})r   z!Couldn't start an HTTP server on )messagei   i(#  	localhostzhttp://localhost:{}z*Couldn't start an HTTP server on localhostclaimsZselect_account)r   promptclaims_challenger   Zauth_uriz#Failed to begin authentication flowzFailed to open a browserz?Timed out after waiting {} seconds for the user to authenticate)r#   r)   r   )r   formatr   r   r   r   socketerrorr   rangelistgetZ_get_appZinitiate_auth_code_flowr   _open_browserZwait_for_redirectr   r   Zacquire_token_by_auth_code_flow)r   r#   r   serverr   exr   r'   appZflowresponser   r   r"   _request_tokenT   sX   





z+InteractiveBrowserCredential._request_token)__name__
__module____qualname____doc__r   r   r   strr   r5   __classcell__r   r   r    r"   r      s
    1r   c                 C   s   t | }|sEt }|d  }|d  }d|v rE|dkrEddi}ztjddd	d
| gfi |}|dk}W |S  tyD   Y |S w |S )Nr   r   Z	microsoftlinuxr      zpowershell.exez
-NoProfilez-CommandzStart-Process "{}")	
webbrowseropenplatformunamelower
subprocesscallr*   	Exception)urlZopenedrA   systemreleaser   	exit_coder   r   r"   r0      s(   

r0   )r@   r+   typingr   r   rC   r>   urllib.parser   Zazure.core.exceptionsr   r$   r   
_constantsr   	_internalr	   r
   r   r   r   r0   r   r   r   r"   <module>   s   y