
    &gL                     D   d Z ddlmZ ddlZddlZddlZ	 ddlmZ n# e$ r	 ddl	mZ Y nw xY w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j        e          Z G d de          Z G d d	e          Z G d
 dej        j                  Z G d de          ZdS )a  OAuth 2.0 Authorization Flow

This module provides integration with `requests-oauthlib`_ for running the
`OAuth 2.0 Authorization Flow`_ and acquiring user credentials.  See
`Using OAuth 2.0 to Access Google APIs`_ for an overview of OAuth 2.0
authorization scenarios Google APIs support.

Here's an example of using :class:`InstalledAppFlow`::

    from google_auth_oauthlib.flow import InstalledAppFlow

    # Create the flow using the client secrets file from the Google API
    # Console.
    flow = InstalledAppFlow.from_client_secrets_file(
        'client_secrets.json',
        scopes=['profile', 'email'])

    flow.run_local_server()

    # You can use flow.credentials, or you can just get a requests session
    # using flow.authorized_session.
    session = flow.authorized_session()

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

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

.. _requests-oauthlib: http://requests-oauthlib.readthedocs.io/en/latest/
.. _OAuth 2.0 Authorization Flow:
    https://tools.ietf.org/html/rfc6749#section-1.2
.. _Using OAuth 2.0 to Access Google APIs:
    https://developers.google.com/identity/protocols/oauth2

    )urlsafe_b64encodeN)SystemRandom)ascii_lettersdigitsc                       e Zd ZdZ	 	 	 ddZed             Zed             Zed             Z	e	j
        d             Z	d	 Zd
 Zed             Z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
    NTc                 l    || _         	 ||         | _        	 || _        	 || _        || _        || _        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   s          K/var/www/api/venv/lib/python3.11/site-packages/google_auth_oauthlib/flow.py__init__zFlow.__init__]   sH    8 'G*;7D*E(**D'''    c                    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
        web	installedz2Client secrets must be for a web or installed app.r   Nr   r   )
ValueErrorpopgoogle_auth_oauthlibhelperssession_from_client_configget)	clsr   scopeskwargsr
   r   r   sessionr   s	            r   from_client_configzFlow.from_client_config   s    . M!!KKM))%KKQRRR 

?D99%+ZZ0Ld%S%S"
 !(C6
 
%+
 
	

 zz.$77s&
 
 	
r   c                     t          |d          5 }t          j        |          }ddd           n# 1 swxY w 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   client_secrets_filer   r   	json_filer   s         r   from_client_secrets_filezFlow.from_client_secrets_file   s     %s++ 	1y Ii00M	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 &s%mMMFMfMMMs   266c                     | j         j        S )XThe OAuth 2.0 redirect URI. Pass-through to
        ``self.oauth2session.redirect_uri``.r   r   r   s    r   r   zFlow.redirect_uri   s     !..r   c                     || j         _        dS )r+   Nr,   )r   values     r   r   zFlow.redirect_uri   s     +0'''r   c                   	
 |                     dd           | j        rWt          t          z   dz   	t	                      
	
fdt          dd          D             }d                    |          | _        | j        rt          j	                    }|
                    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`.
        access_typeofflinez-._~c                 :    g | ]}                               S  )choice).0_charsrnds     r   
<listcomp>z*Flow.authorization_url.<locals>.<listcomp>   s%    HHHQszz%00HHHr   r       =code_challengecode_challenge_methodS256auth_uri)
setdefaultr   r   r   r   rangejoinr   hashlibsha256updatestrencodedigestr   decodesplitr   authorization_urlr   )r   r   random_verifier	code_hashunencoded_challengeb64_challenger>   urlstater8   r9   s            @@r   rM   zFlow.authorization_url   sc   0 	-333* 	:!F*V3E..CHHHHH%3--HHHO!#!9!9D 	?((ISZZ(:;;<<<"+"2"2"4"4-.ABBM*113399#>>qAN.???5v>>>9T'9z*
 
.4
 

U Ezr   c                     |                     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 use
                :meth:`credentials` to obtain a
                :class:`~google.auth.credentials.Credentials` instance.
        client_secretr   	token_uri)rB   r   r   r   fetch_token)r   r   s     r   rW   zFlow.fetch_token  sb    . 	/4+=o+NOOO/4+=>>>-t!-d.@.MXXQWXXXr   c                 V    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   credentials_from_sessionr   r   r-   s    r   credentialszFlow.credentials  s*     $+DD 2
 
 	
r   c                 ^    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requestsAuthorizedSessionrZ   r-   s    r   authorized_sessionzFlow.authorized_session1  s#     {$-??@PQQQr   )NNT)__name__
__module____qualname____doc__r   classmethodr!   r)   propertyr   setterrM   rW   rZ   ra   r4   r   r   r   r   J   s        . #'$E $E $E $EL 1
 1
 [1
f N N [N& / / X/
 0 0 0
+ + +ZY Y Y6 
 
 X
"R R R R Rr   r   c            
       >    e Zd ZdZdZ	 dZ	 dZdddeedddddf
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 uses a 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 this isn't the only way to accomplish the installed
    application flow, just one of the most common. 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:Please visit this URL to authorize this application: {url}zEnter the authorization code: zAThe authentication flow has completed. You may close this window.	localhostNi  Tc                    t          |          }dt          j        j        _        t          j                            |p|||t                    }	 |rdnd}|                    ||j                  | _	         | j
        di |\  }}|r*t          j        |
                              |dd           |r#t          |                    |                     ||_        |                                 |j                            d	d
          }|                     ||	           |                                 n# |                                 w xY w| 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.
            bind_addr (str): Optionally provide an ip address for the redirect
                server to listen on when it is not the same as host
                (e.g. in a container). Default value is None,
                which means that the redirect server will listen
                on the ip address specified in the host parameter.
            port (int): The port for the local redirect server.
            authorization_prompt_message (str | None): The message to display to tell
                the user to navigate to the authorization URL. If None or empty,
                don't display anything.
            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.
            timeout_seconds (int): It will raise an error after the timeout timing
                if there are no credentials response. The value is in seconds.
                When set to None there is no timeout.
                Default value is None.
            token_audience (str): Passed along with the request for an access
                token. Determines the endpoints with which the token can be
                used. Optional.
            browser (str): specify which browser to open for authentication. If not
                specified this defaults to default browser.
            kwargs: Additional keyword arguments passed through to
                :meth:`authorization_url`.

        Returns:
            google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
                for the user.
        F)handler_classzhttp://{}:{}/zhttp://{}:{}   T)new	autoraise)rR   httphttps)authorization_responseaudiencer4   )_RedirectWSGIAppwsgirefsimple_server
WSGIServerallow_reuse_addressmake_server_WSGIRequestHandlerformatserver_portr   rM   
webbrowserr   r$   printtimeouthandle_requestlast_request_urireplacerW   server_closerZ   )r   host	bind_addrportauthorization_prompt_messagesuccess_messageopen_browserredirect_uri_trailing_slashtimeout_secondstoken_audiencebrowserr   wsgi_applocal_serverredirect_uri_formatauth_urlr7   rs   s                     r   run_local_serverz!InstalledAppFlow.run_local_servers  s   t $O44?D(<,88tX=P 9 
 
	(#>RN   !4 : :l.! !D 1$0::6::KHa Nw'',,X1,MMM+ I299h9GGHHH#2L ''))) &.%>%F%Fvw%W%W"'=     %%''''L%%''''s   CD: :E)rb   rc   rd   re   _DEFAULT_AUTH_PROMPT_MESSAGE_DEFAULT_AUTH_CODE_MESSAGE_DEFAULT_WEB_SUCCESS_MESSAGEr   r4   r   r   rj   rj   ?  s        $ $N 	E !!A> 	L ! %A4$(]  ]  ]  ]  ]  ] r   rj   c                       e Zd ZdZd ZdS )r{   zWCustom WSGIRequestHandler.

    Uses a named logger instead of printing to stderr.
    c                 *    t          j        |g|R   d S )N)_LOGGERinfo)r   r|   argss      r   log_messagez_WSGIRequestHandler.log_message  s"     	V#d######r   N)rb   rc   rd   re   r   r4   r   r   r{   r{     s-         
$ $ $ $ $r   r{   c                       e Zd ZdZd Zd ZdS )ru   zwWSGI app to handle the authorization redirect.

    Stores the request URI and displays the given success message.
    c                 "    d| _         || _        dS )z
        Args:
            success_message (str): The message to display in the web browser
                the authorization flow is complete.
        N)r   _success_message)r   r   s     r   r   z_RedirectWSGIApp.__init__  s     !% /r   c                      |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)rv   utilrequest_urir   r   rI   )r   environstart_responses      r   __call__z_RedirectWSGIApp.__call__  sL     	x"O!PQQQ ' 8 8 A A%,,W5566r   N)rb   rc   rd   re   r   r   r4   r   r   ru   ru     s<         
0 0 07 7 7 7 7r   ru   ) re   base64r   rE   r%   loggingsecretsr   ImportErrorrandomstringr   r   r~   wsgiref.simple_serverrv   wsgiref.utilgoogle.auth.transport.requestsr\   google.oauth2.credentialsgoogle_auth_oauthlib.helpersr   	getLoggerrb   r   objectr   rj   rw   WSGIRequestHandlerr{   ru   r4   r   r   <module>r      s  # #H % $ $ $ $ $   $$$$$$$$ $ $ $########$ ( ( ( ( ( ( ( (             % % % %         # # # # '
H
%
%rR rR rR rR rR6 rR rR rRjQ  Q  Q  Q  Q t Q  Q  Q h	$ 	$ 	$ 	$ 	$'/B 	$ 	$ 	$7 7 7 7 7v 7 7 7 7 7s    ++