a
    w=icM                     @   s   d Z ddlmZ ddlZddlZddlZzddlmZ W n eyV   ddl	mZ Y n0 ddl
mZmZ ddlZddlZddlZddlZddlZddlZeeZG dd deZG dd	 d	eZG d
d dejjZG dd deZdS )ak  OAuth 2.0 Authorization Flow

This module provides integration with `requests-oauthlib`_ for running the
`OAuth 2.0 Authorization Flow`_ and acquiring user credentials.

Here's an example of using :class:`Flow` with the installed application
authorization flow::

    from google_auth_oauthlib.flow import Flow

    # Create the flow using the client secrets file from the Google API
    # Console.
    flow = Flow.from_client_secrets_file(
        'path/to/client_secrets.json',
        scopes=['profile', 'email'],
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')

    # Tell the user to go to the authorization URL.
    auth_url, _ = flow.authorization_url(prompt='consent')

    print('Please go to this URL: {}'.format(auth_url))

    # The user will get an authorization code. This code is used to get the
    # access token.
    code = input('Enter the authorization code: ')
    flow.fetch_token(code=code)

    # You can use flow.credentials, or you can just get a requests session
    # using flow.authorized_session.
    session = flow.authorized_session()
    print(session.get('https://www.googleapis.com/userinfo/v2/me').json())

This particular flow can be handled entirely by using
:class:`InstalledAppFlow`.

.. _requests-oauthlib: http://requests-oauthlib.readthedocs.io/en/stable/
.. _OAuth 2.0 Authorization Flow:
    https://tools.ietf.org/html/rfc6749#section-1.2
    )urlsafe_b64encodeN)SystemRandom)ascii_lettersdigitsc                   @   sp   e Zd ZdZdddZedd Zedd	 Zed
d Z	e	j
dd Z	dd Zdd Zedd Zdd ZdS )Flowa  OAuth 2.0 Authorization Flow

    This class uses a :class:`requests_oauthlib.OAuth2Session` instance at
    :attr:`oauth2session` to perform all of the OAuth 2.0 logic. This class
    just provides convenience methods and sane defaults for doing Google's
    particular flavors of OAuth 2.0.

    Typically you'll construct an instance of this flow using
    :meth:`from_client_secrets_file` and a `client secrets file`_ obtained
    from the `Google API Console`_.

    .. _client secrets file:
        https://developers.google.com/identity/protocols/oauth2/web-server
        #creatingcred
    .. _Google API Console:
        https://console.developers.google.com/apis/credentials
    NFc                 C   s,   || _ || | _|| _|| _|| _|| _dS )a  
        Args:
            oauth2session (requests_oauthlib.OAuth2Session):
                The OAuth 2.0 session from ``requests-oauthlib``.
            client_type (str): The client type, either ``web`` or
                ``installed``.
            client_config (Mapping[str, Any]): The client
                configuration in the Google `client secrets`_ format.
            redirect_uri (str): The OAuth 2.0 redirect URI if known at flow
                creation time. Otherwise, it will need to be set using
                :attr:`redirect_uri`.
            code_verifier (str): random string of 43-128 chars used to verify
                the key exchange.using PKCE.
            autogenerate_code_verifier (bool): If true, auto-generate a
                code_verifier.
        .. _client secrets:
            https://github.com/googleapis/google-api-python-client/blob
            /main/docs/client-secrets.md
        N)client_typeclient_configoauth2sessionredirect_uricode_verifierautogenerate_code_verifier)selfr	   r   r   r
   r   r    r   j/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/google_auth_oauthlib/flow.py__init__`   s    
zFlow.__init__c           	      K   st   d|v rd}nd|v rd}nt d|dd}|dd}tjj||fi |\}}|dd}| ||||||S )a(  Creates a :class:`requests_oauthlib.OAuth2Session` from client
        configuration loaded from a Google-format client secrets file.

        Args:
            client_config (Mapping[str, Any]): The client
                configuration in the Google `client secrets`_ format.
            scopes (Sequence[str]): The list of scopes to request during the
                flow.
            kwargs: Any additional parameters passed to
                :class:`requests_oauthlib.OAuth2Session`

        Returns:
            Flow: The constructed Flow instance.

        Raises:
            ValueError: If the client configuration is not in the correct
                format.

        .. _client secrets:
            https://github.com/googleapis/google-api-python-client/blob/main/docs/client-secrets.md
        Zweb	installedz2Client secrets must be for a web or installed app.r   Nr   r
   )
ValueErrorpopgoogle_auth_oauthlibhelpersZsession_from_client_configget)	clsr   scopeskwargsr   r   r   sessionr
   r   r   r   from_client_config   s0    zFlow.from_client_configc                 K   sJ   t |d}t|}W d   n1 s*0    Y  | j|fd|i|S )a  Creates a :class:`Flow` instance from a Google client secrets file.

        Args:
            client_secrets_file (str): The path to the client secrets .json
                file.
            scopes (Sequence[str]): The list of scopes to request during the
                flow.
            kwargs: Any additional parameters passed to
                :class:`requests_oauthlib.OAuth2Session`

        Returns:
            Flow: The constructed Flow instance.
        rNr   )openjsonloadr   )r   Zclient_secrets_filer   r   Z	json_filer   r   r   r   from_client_secrets_file   s    (zFlow.from_client_secrets_filec                 C   s   | j jS )zXThe OAuth 2.0 redirect URI. Pass-through to
        ``self.oauth2session.redirect_uri``.r	   r
   r   r   r   r   r
      s    zFlow.redirect_uric                 C   s   || j _d S Nr!   )r   valuer   r   r   r
      s    c           	         s   | dd | jrJtt d  t  fddtddD }d|| _| jrt	 }|
t| j | }t|}| d	d }| d
| | dd | jj| jd fi |\}}||fS )ah  Generates an authorization URL.

        This is the first step in the OAuth 2.0 Authorization Flow. The user's
        browser should be redirected to the returned URL.

        This method calls
        :meth:`requests_oauthlib.OAuth2Session.authorization_url`
        and specifies the client configuration's authorization URI (usually
        Google's authorization server) and specifies that "offline" access is
        desired. This is required in order to obtain a refresh token.

        Args:
            kwargs: Additional arguments passed through to
                :meth:`requests_oauthlib.OAuth2Session.authorization_url`

        Returns:
            Tuple[str, str]: The generated authorization URL and state. The
                user must visit the URL to complete the flow. The state is used
                when completing the flow to verify that the request originated
                from your application. If your application is using a different
                :class:`Flow` instance to obtain the token, you will need to
                specify the ``state`` when constructing the :class:`Flow`.
        Zaccess_typeZofflinez-._~c                    s   g | ]}  qS r   )choice).0_charsZrndr   r   
<listcomp>       z*Flow.authorization_url.<locals>.<listcomp>r       =code_challengeZcode_challenge_methodZS256Zauth_uri)
setdefaultr   r   r   r   rangejoinr   hashlibsha256updatestrencodedigestr   decodesplitr	   authorization_urlr   )	r   r   Zrandom_verifierZ	code_hashZunencoded_challengeZb64_challenger/   urlstater   r(   r   r;      s(    
zFlow.authorization_urlc                 K   s:   | d| jd  | d| j | jj| jd fi |S )a  Completes the Authorization Flow and obtains an access token.

        This is the final step in the OAuth 2.0 Authorization Flow. This is
        called after the user consents.

        This method calls
        :meth:`requests_oauthlib.OAuth2Session.fetch_token`
        and specifies the client configuration's token URI (usually Google's
        token server).

        Args:
            kwargs: Arguments passed through to
                :meth:`requests_oauthlib.OAuth2Session.fetch_token`. At least
                one of ``code`` or ``authorization_response`` must be
                specified.

        Returns:
            Mapping[str, str]: The obtained tokens. Typically, you will not use
                return value of this function and instead and use
                :meth:`credentials` to obtain a
                :class:`~google.auth.credentials.Credentials` instance.
        Zclient_secretr   Z	token_uri)r0   r   r   r	   fetch_token)r   r   r   r   r   r>     s    zFlow.fetch_tokenc                 C   s   t j| j| jS )a  Returns credentials from the OAuth 2.0 session.

        :meth:`fetch_token` must be called before accessing this. This method
        constructs a :class:`google.oauth2.credentials.Credentials` class using
        the session's token and the client config.

        Returns:
            google.oauth2.credentials.Credentials: The constructed credentials.

        Raises:
            ValueError: If there is no access token in the session.
        )r   r   Zcredentials_from_sessionr	   r   r"   r   r   r   credentials   s    zFlow.credentialsc                 C   s   t jjj| jS )a  Returns a :class:`requests.Session` authorized with credentials.

        :meth:`fetch_token` must be called before this method. This method
        constructs a :class:`google.auth.transport.requests.AuthorizedSession`
        class using this flow's :attr:`credentials`.

        Returns:
            google.auth.transport.requests.AuthorizedSession: The constructed
                session.
        )googleauth	transportrequestsZAuthorizedSessionr?   r"   r   r   r   authorized_session2  s    zFlow.authorized_session)NNF)__name__
__module____qualname____doc__r   classmethodr   r    propertyr
   setterr;   r>   r?   rD   r   r   r   r   r   M   s$      
&
3


-
r   c                   @   sD   e Zd ZdZdZdZdZdZeefddZdd	eed
d
fddZ	dS )InstalledAppFlowa  Authorization flow helper for installed applications.

    This :class:`Flow` subclass makes it easier to perform the
    `Installed Application Authorization Flow`_. This flow is useful for
    local development or applications that are installed on a desktop operating
    system.

    This flow has two strategies: The console strategy provided by
    :meth:`run_console` and the local server strategy provided by
    :meth:`run_local_server`.

    Example::

        from google_auth_oauthlib.flow import InstalledAppFlow

        flow = InstalledAppFlow.from_client_secrets_file(
            'client_secrets.json',
            scopes=['profile', 'email'])

        flow.run_local_server()

        session = flow.authorized_session()

        profile_info = session.get(
            'https://www.googleapis.com/userinfo/v2/me').json()

        print(profile_info)
        # {'name': '...',  'email': '...', ...}


    Note that these aren't the only two ways to accomplish the installed
    application flow, they are just the most common ways. You can use the
    :class:`Flow` class to perform the same flow with different methods of
    presenting the authorization URL to the user or obtaining the authorization
    response, such as using an embedded web view.

    .. _Installed Application Authorization Flow:
        https://github.com/googleapis/google-api-python-client/blob/main/docs/oauth-installed.md
    zurn:ietf:wg:oauth:2.0:oobz:Please visit this URL to authorize this application: {url}zEnter the authorization code: zAThe authentication flow has completed. You may close this window.c                 K   sR   | dd | j| _| jf i |\}}t|j|d t|}| j|d | jS )az  Run the flow using the console strategy.

        The console strategy instructs the user to open the authorization URL
        in their browser. Once the authorization is complete the authorization
        server will give the user a code. The user then must copy & paste this
        code into the application. The code is then exchanged for a token.

        Args:
            authorization_prompt_message (str): The message to display to tell
                the user to navigate to the authorization URL.
            authorization_code_message (str): The message to display when
                prompting the user for the authorization code.
            kwargs: Additional keyword arguments passed through to
                :meth:`authorization_url`.

        Returns:
            google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
                for the user.
        promptZconsentr<   )code)	r0   _OOB_REDIRECT_URIr
   r;   printformatinputr>   r?   )r   authorization_prompt_messageZauthorization_code_messager   auth_urlr'   rO   r   r   r   run_consolex  s    zInstalledAppFlow.run_console	localhosti  Tc                 K   s   t |}dtjj_tjj|||td}	|r.dnd}
|
||	j| _	| j
f i |\}}|rjtj|ddd t|j|d |	  |jd	d
}| j|d |	  | jS )a  Run the flow using the server strategy.

        The server strategy instructs the user to open the authorization URL in
        their browser and will attempt to automatically open the URL for them.
        It will start a local web server to listen for the authorization
        response. Once authorization is complete the authorization server will
        redirect the user's browser to the local web server. The web server
        will get the authorization code from the response and shutdown. The
        code is then exchanged for a token.

        Args:
            host (str): The hostname for the local redirect server. This will
                be served over http, not https.
            port (int): The port for the local redirect server.
            authorization_prompt_message (str): The message to display to tell
                the user to navigate to the authorization URL.
            success_message (str): The message to display in the web browser
                the authorization flow is complete.
            open_browser (bool): Whether or not to open the authorization URL
                in the user's browser.
            redirect_uri_trailing_slash (bool): whether or not to add trailing
                slash when constructing the redirect_uri. Default value is True.
            kwargs: Additional keyword arguments passed through to
                :meth:`authorization_url`.

        Returns:
            google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
                for the user.
        F)Zhandler_classzhttp://{}:{}/zhttp://{}:{}   T)newZ	autoraiserN   httphttps)authorization_response)_RedirectWSGIAppwsgirefsimple_serverZ
WSGIServerallow_reuse_addressZmake_server_WSGIRequestHandlerrR   Zserver_portr
   r;   
webbrowserr   rQ   handle_requestlast_request_urireplacer>   server_closer?   )r   hostportrT   success_messageZopen_browserZredirect_uri_trailing_slashr   Zwsgi_appZlocal_serverZredirect_uri_formatrU   r'   r\   r   r   r   run_local_server  s"    '

z!InstalledAppFlow.run_local_serverN)
rE   rF   rG   rH   rP   Z_DEFAULT_AUTH_PROMPT_MESSAGEZ_DEFAULT_AUTH_CODE_MESSAGEZ_DEFAULT_WEB_SUCCESS_MESSAGErV   rj   r   r   r   r   rL   @  s"   (
)rL   c                   @   s   e Zd ZdZdd ZdS )ra   zWCustom WSGIRequestHandler.

    Uses a named logger instead of printing to stderr.
    c                 G   s   t j|g|R   d S r#   )_LOGGERinfo)r   rR   argsr   r   r   log_message  s    z_WSGIRequestHandler.log_messageN)rE   rF   rG   rH   rn   r   r   r   r   ra     s   ra   c                   @   s    e Zd ZdZdd Zdd ZdS )r]   zwWSGI app to handle the authorization redirect.

    Stores the request URI and displays the given success message.
    c                 C   s   d| _ || _dS )z
        Args:
            success_message (str): The message to display in the web browser
                the authorization flow is complete.
        N)rd   _success_message)r   ri   r   r   r   r     s    z_RedirectWSGIApp.__init__c                 C   s(   |ddg t j|| _| jdgS )a  WSGI Callable.

        Args:
            environ (Mapping[str, Any]): The WSGI environment.
            start_response (Callable[str, list]): The WSGI start_response
                callable.

        Returns:
            Iterable[bytes]: The response body.
        z200 OK)zContent-typeztext/plain; charset=utf-8zutf-8)r^   utilrequest_urird   ro   r7   )r   environZstart_responser   r   r   __call__   s    z_RedirectWSGIApp.__call__N)rE   rF   rG   rH   r   rs   r   r   r   r   r]     s   	r]   ) rH   base64r   r3   r   loggingZsecretsr   ImportErrorrandomstringr   r   rb   Zwsgiref.simple_serverr^   Zwsgiref.utilZgoogle.auth.transport.requestsr@   Zgoogle.oauth2.credentialsZgoogle_auth_oauthlib.helpersr   	getLoggerrE   rk   objectr   rL   r_   ZWSGIRequestHandlerra   r]   r   r   r   r   <module>   s,   '
 t &