
    WhGA                     V   d 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ddlZddlZddl	m
Z ddlZddlZddlZddlZddlmZ ddlmZ  ej                    ZdZdZdZdZd	Zg d
Z G d d          Z	 ddej        j        j         fdZ! G d d          Z" G d dej#                  Z$d Z%dS )z8Provides authentication support for TensorBoardUploader.    N)util)
tb_logging)openidz.https://www.googleapis.com/auth/userinfo.emaila	  
    {
        "installed":{
            "client_id":"373649185512-8v619h5kft38l4456nm2dj4ubeqsrvh6.apps.googleusercontent.com",
            "project_id":"hosted-tensorboard-prod",
            "auth_uri":"https://accounts.google.com/o/oauth2/auth",
            "token_uri":"https://oauth2.googleapis.com/token",
            "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
            "client_secret":"pOyAuU2yq2arsM98Bw5hwYtr",
            "redirect_uris":["http://localhost"]
        }
    }
z)https://oauth2.googleapis.com/device/codez,urn:ietf:params:oauth:grant-type:device_codea  
    {
        "installed":{
            "client_id":"373649185512-26ojik4u7dt0rdtfdmfnhpajqqh579qd.apps.googleusercontent.com",
            "project_id":"hosted-tensorboard-prod",
            "auth_uri":"https://accounts.google.com/o/oauth2/auth",
            "token_uri":"https://oauth2.googleapis.com/token",
            "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
            "client_secret":"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"
        }
    }
)tensorboardcredentialszuploader-creds.jsonc                   B    e Zd ZdZ e            ZefdZd Zd Zd Z	dS )CredentialsStorezAPrivate file store for a `google.oauth2.credentials.Credentials`.c                     |t           j        u r/t          j                    }|t                              d           |	d| _        dS t          j        j	        |gt          R  | _        dS )aw  Creates a CredentialsStore.

        Args:
          user_config_directory: Optional absolute path to the root directory for
            storing user configs, under which to store the credentials file. If not
            set, defaults to a platform-specific location. If set to None, the
            store is disabled (reads return None; write and clear are no-ops).
        Nz@Credentials caching disabled - no private config directory found)r	   _DEFAULT_CONFIG_DIRECTORYr   get_user_config_directoryloggerwarning_credentials_filepathospathjoin&TENSORBOARD_CREDENTIALS_FILEPATH_PARTS)selfuser_config_directorys     _/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/tensorboard/uploader/auth.py__init__zCredentialsStore.__init__   s     !$4$NNN$($B$D$D!$,V   !()-D&&&)+%*(N* * *D&&&    c                     | j         dS t          j                            | j                   r.t          j        j        j                            | j                   S dS )zMReturns the current `google.oauth2.credentials.Credentials`, or
        None.N)	r   r   r   existsgoogleoauth2r   Credentialsfrom_authorized_user_file)r   s    r   read_credentialsz!CredentialsStore.read_credentials   sX     %-47>>$455 	)5OO. 
 tr   c                    t          |t          j        j        j                  st          dt          |          z            | j        dS t          j	        dk    }t          j        | j        |           |j        |j        |j        |j        |j        dd}t#          | j        d          5 }t%          j        ||           ddd           dS # 1 swxY w Y   dS )z>Writes a `google.oauth2.credentials.Credentials` to the store.z#Cannot write credentials of type %sNnt)privateauthorized_user)refresh_token	token_uri	client_idclient_secretscopestypew)
isinstancer   r   r   r   	TypeErrorr)   r   r   namer   make_file_with_directoriesr$   r%   r&   r'   r(   openjsondump)r   r   r"   datafs        r   write_credentialsz"CredentialsStore.write_credentials   s4   +v}'@'LMM 	5[8I8II   %-F 'T/'&	
 	
 	
 	
 )6$.$.(6!(%
 
 $,c22 	aIdA	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   /CCCc                     | j         dS 	 t          j        | j                    dS # t          $ r!}|j        t          j        k    r Y d}~dS d}~ww xY w)z:Clears the store of any persisted credentials information.N)r   r   removeOSErrorerrnoENOENT)r   es     r   clearzCredentialsStore.clear   ss    %-F	Id011111 	 	 	w%,&& '&&&&&	s   & 
AAAN)
__name__
__module____qualname____doc__objectr   r   r   r4   r;    r   r   r	   r	   |   sj        KK &-F    ,    4    r   r	   Freturnc                    t           }| st          j        d          r	 t          j        t
                    }t          j                            ||          }|	                    d          S # t          j        $ r" t          j                            d           Y nw xY wt          j        t                    }t!          ||          }|                                S )a+  Makes the user authenticate to retrieve auth credentials.

    The default behavior is to use the [installed app flow](
    http://developers.google.com/identity/protocols/oauth2/native-app), in which
    a browser is started for the user to authenticate, along with a local web
    server. The authentication in the browser would produce a redirect response
    to `localhost` with an authorization code that would then be received by the
    local web server started here.

    The two most notable cases where the default flow is not well supported are:
    - When the uploader is run from a colab notebook.
    - Then the uploader is run via a remote terminal (SSH).

    If any of the following is true, a different auth flow will be used:
    - the flag `--auth_force_console` is set to true, or
    - a browser is not available, or
    - a local web server cannot be started

    In this case, a [limited-input device flow](
    http://developers.google.com/identity/protocols/oauth2/limited-input-device)
    will be used, in which the user is presented with a URL and a short code
    that they'd need to use to authenticate and authorize access in a separate
    browser or device. The uploader will poll for access until the access is
    granted or rejected, or the initiated authorization request expires.
    DISPLAY)r(   r   )portz.Falling back to remote authentication flow...
)OPENID_CONNECT_SCOPESr   getenvr0   loads"_INSTALLED_APP_OAUTH_CLIENT_CONFIG
auth_flowsInstalledAppFlowfrom_client_configrun_local_server
webbrowserErrorsysstderrwrite)_LIMITED_INPUT_DEVICE_OAUTH_CLIENT_CONFIG_LimitedInputDeviceAuthFlowrun)force_consoler(   client_configflows       r   authenticate_userrY      s    8 #F PRYy11 P	P J'IJJM.AAf B  D ((a(000 	P 	P 	PJNOOOOO	P JHIIM&}VDDDD88::s   AA/ /.B B c                       e Zd ZdZd Zdej        j        j        fdZ	d Z
dededefd	Zdej        j        j        fd
ZdS )rT   zOAuth flow to authenticate using the limited-input device flow.

    See:
    http://developers.google.com/identity/protocols/oauth2/limited-input-device
    c                 .    |d         | _         || _        d S )N	installed)_client_config_scopes)r   rW   r(   s      r   r   z$_LimitedInputDeviceAuthFlow.__init__   s     ,K8r   rB   c                    |                                  }d                    |d         |d                   }t          |           |                     |d         |d         |d                   }|                     |          S )	NzTo sign in with the TensorBoard uploader:

1. On your computer or phone, visit:

   {url}

2. Sign in with your Google account, then enter:

   {code}
verification_url	user_code)urlcodedevice_codeinterval
expires_in)rd   polling_intervalexpiration_seconds)_send_device_auth_requestformatprint_poll_for_auth_token_build_credentials)r   device_responseprompt_messageauth_responses       r   rU   z_LimitedInputDeviceAuthFlow.run  s    88:: !&#$67$[1 !   	 	n11'6,Z8.|< 2 
 
 &&}555r   c                     | j         d         d                    | j                  d}t          j        t
          |                                          }d|vrt          d          |S )Nr&    )r&   scoper2   rd   zZThere was an error while contacting Google's authorization server. Please try again later.)r]   r   r^   requestspost_DEVICE_AUTH_CODE_URIr0   RuntimeError)r   paramsrs      r   ri   z5_LimitedInputDeviceAuthFlow._send_device_auth_request  sv    ,[9XXdl++
 
 M/f===BBDD!!2   r   rd   rg   rh   c                    | j         d         }| j         d         | j         d         |t          d}t          j                    |z   }t          j                    |k     rt          j        ||          }|                                }d|v r|S d|v r!|d         dk    rt          j        |           n}d|v r3|d         d	k    r't          |d
z            }t          j        |           nFd|v r|d         dk    rt          d          |j	        dv rt          d          t          d          t          j                    |k     t          d          )Nr%   r&   r'   )r&   r'   rd   
grant_typert   access_tokenerrorauthorization_pending	slow_downg      ?access_deniedzAccess was denied by user.>       z&There must be an error in the request.z=An unexpected error occurred while waiting for authorization.z$Timed out waiting for authorization.)r]   %_LIMITED_INPUT_DEVICE_AUTH_GRANT_TYPEtimeru   rv   r0   sleepintPermissionErrorstatus_code
ValueErrorrx   TimeoutError)	r   rd   rg   rh   r%   ry   expiration_timeresprz   s	            r   rl   z0_LimitedInputDeviceAuthFlow._poll_for_auth_token*  s}    '4	,[9!0A&?	
 
 )++(:: ikkO++=888D		A""A!G*0G"G"G 
+,,,,A!G*";";
 $''7#'=#>#> 
+,,,,A!G*"?"?%&BCCC!Z// !IJJJ"%  + ikkO++2 ABBBr   c           
      V   t           j                             t          t          j                              |d         z             }t          j        j                            |d         |d         |d         | j        d         | j        d         | j        d         | j	        |          S )	Nrf   r}   r$   id_tokenr%   r&   r'   )r$   r   r%   r&   r'   r(   expiry)
datetimeutcfromtimestampr   r   r   r   r   r   r]   r^   )r   rp   expiration_datetimes      r   rm   z._LimitedInputDeviceAuthFlow._build_credentialsR  s     '/@@	}\::
 
 }(44.)'8":.)+6)+6-o><& 5 	
 	
 		
r   N)r<   r=   r>   r?   r   r   r   r   r   rU   ri   strr   rl   rm   rA   r   r   rT   rT      s           6V].: 6 6 6 64  &C&C25&CKN&C &C &C &CP
		"	.
 
 
 
 
 
r   rT   c                   (     e Zd ZdZ fdZd Z xZS )IdTokenAuthMetadataPluginas  A `gRPC AuthMetadataPlugin` that uses ID tokens.

    This works like the existing `google.auth.transport.grpc.AuthMetadataPlugin`
    except that instead of always using access tokens, it preferentially uses the
    `Credentials.id_token` property if available (and logs an error otherwise).

    See http://www.grpc.io/grpc/python/grpc.html#grpc.AuthMetadataPlugin
    c                     t                                                       t          |t          j        j        j                  st          dt          |          z            || _	        || _
        dS )a3  Constructs an IdTokenAuthMetadataPlugin.

        Args:
          credentials (google.auth.credentials.Credentials): The credentials to
            add to requests.
          request (google.auth.transport.Request): A HTTP transport request object
            used to refresh credentials as needed.
        z-Cannot get ID tokens from credentials type %sN)superr   r+   r   r   r   r   r,   r)   _credentials_request)r   r   request	__class__s      r   r   z"IdTokenAuthMetadataPlugin.__init__o  so     	+v}'@'LMM 	?{##$   (r   c                 V   i }| j                             | j        |j        |j        |           t          | j         dd          }|r| j                             ||           nt                              d            |t          |
                                          d           dS )a  Passes authorization metadata into the given callback.

        Args:
          context (grpc.AuthMetadataContext): The RPC context.
          callback (grpc.AuthMetadataPluginCallback): The callback that will
            be invoked to pass in the authorization metadata.
        r   N)tokenz#Failed to find ID token credentials)r   before_requestr   method_nameservice_urlgetattrapplyr   r~   listitems)r   contextcallbackheadersr   s        r   __call__z"IdTokenAuthMetadataPlugin.__call__  s     ((M7.0CW	
 	
 	
 4,j$?? 	@##G8#<<<<LL>???gmmoo&&-----r   )r<   r=   r>   r?   r   r   __classcell__)r   s   @r   r   r   e  sQ                  $. . . . . . .r   r   c                     t           j        j        j                                        }t          j        t          | |                    S )zConstructs `grpc.CallCredentials` using
    `google.auth.Credentials.id_token`.

    Args:
      credentials (google.auth.credentials.Credentials): The credentials to use.

    Returns:
      grpc.CallCredentials: The call credentials.
    )r   auth	transportru   Requestgrpcmetadata_call_credentialsr   )r   r   s     r   id_token_call_credentialsr     s?     k#,4466G)!+w77  r   )F)&r?   r   r8   r0   r   ru   rP   r   rN   google_auth_oauthlib.flowrX   rJ   r   google.authr   google.auth.transport.requestsgoogle.oauth2.credentialstensorboard.uploaderr   tensorboard.utilr   
get_loggerr   rF   rI   rw   r   rS   r   r	   r   r   r   rY   rT   AuthMetadataPluginr   r   rA   r   r   <module>r      s    ? >    				  



      . . . . . .      % % % %         % % % % % % ' ' ' ' ' ' 
		 	 
 & "( D  3 &*- ) * * * &J J J J J J J J\ * *]** * * *Zl
 l
 l
 l
 l
 l
 l
 l
^.. .. .. .. .. 7 .. .. ..b    r   