o
    Ďij                     @   s   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	Z	d dl
Z
d dlZd dlZd dlmZmZmZ d dlmZ d dlmZ d dlmZ G dd dZdS )    N)datetime	timedeltatimezone)KaggleClient)KaggleCredentials)ExchangeOAuthTokenRequestc                   @   s   e Zd ZdZdefddZG dd dZG dd dejj	Z
ed	d
 Zdedee ddfddZdee dedefddZdd ZdefddZddee dedefddZdS )KaggleOAuth	kagglesdkclientc                 C   s,   || _ | | _d| _d | _tt| _d S NF)	_clienthttp_client_http_client_server_running_credslogging	getLogger__name___logger)selfr
    r   R/home/jeff/fluffinator/venv/lib/python3.10/site-packages/kagglesdk/kaggle_oauth.py__init__   s
   
zKaggleOAuth.__init__c                   @   sJ   e Zd Zdd ZddefddZddedefd	d
ZdedefddZdS )KaggleOAuth.OAuthStatec                 C   s.   t t | _tj | _tj| j| _	d S N)
struuiduuid4stater   
OAuthState_generate_code_verifiercode_verifier_generate_code_challengecode_challenger   r   r   r   r      s   zKaggleOAuth.OAuthState.__init__    lengthc                 C   s
   t | S r   )secretstoken_urlsafer&   r   r   r   _generate_state#      
z&KaggleOAuth.OAuthState._generate_state@   returnc                 C   s.   d|   krdkst d t dt| S )N*      z;Code verifier length must be between 42 and 128 characters.)
ValueErrorr'   r(   r)   r   r   r   r    &   s
   
z.KaggleOAuth.OAuthState._generate_code_verifierr!   c                 C   s,   |  d}t| }t|d}|S )Nzutf-8)encodehashlibsha256digestbase64urlsafe_b64encodedecode)r!   code_verifier_bytescode_challenge_bytescode_challenge_base64r   r   r   r"   +   s   
z/KaggleOAuth.OAuthState._generate_code_challengeN)r%   )r,   )	r   
__module____qualname__r   intr*   r   r    r"   r   r   r   r   r      s
    r   c                       sH   e Zd Zddddd			d fddZd	d
 Zdd Zdd Z  ZS )z KaggleOAuth.OAuthCallbackHandlerNoauthoauth_state
on_successloggerr?   r   r@   r   c                   s.   || _ || _|| _|| _t j|i | d S r   )_oauth_oauth_state_on_successr   superr   )r   r?   r@   rA   rB   argskwargs	__class__r   r   r   2   s
   	z)KaggleOAuth.OAuthCallbackHandler.__init__c                 C   s0   | j dkrd S z|   W |   d S |   w )Nz/favicon.ico)path_handle_oauth_callback_stop_serverr$   r   r   r   do_GETA   s
   

z'KaggleOAuth.OAuthCallbackHandler.do_GETc                 C   sD  t j| j}t j|j}d|v rd|v r|d d }|d d }| jd | jd|  | jd|  || jj	kr\| 
d | dd	 |   | jd
 | | d S | jd| jj	 d|  | 
d | dd	 |   | jd d S | jd| j  | 
d | dd	 |   | jd d S )Ncoder   r   z
Received OAuth Callback:z	  code : z	  state:    zContent-typez	text/htmls^   <html><body><h1>Authentication Successful!</h1><p>You can close this window.</p></body></html>zInvalid state! Expected: z, Received: i  s9   <html><body><h1>Authentication Failed!</h1></body></html>z"
Received Invalid OAuth Callback: s\   <html><body><h1>Authentication Failed!</h1><p>Invalid callback parameters.</p></body></html>)urllibparseurlparserK   parse_qsqueryr   debugrD   r   send_responsesend_headerend_headerswfilewriterE   error)r   
parsed_urlquery_paramsrO   r   r   r   r   rL   I   s8   


z7KaggleOAuth.OAuthCallbackHandler._handle_oauth_callbackc                 C   s   | j   d S r   )rC   stop_serverr$   r   r   r   rM   i   s   z-KaggleOAuth.OAuthCallbackHandler._stop_server)r?   r   r@   r   )r   r;   r<   r   rN   rL   rM   __classcell__r   r   rI   r   OAuthCallbackHandler1   s     ra   c                   C   s0   t  dv rdS dtjv rtjd dkrdS dS )N)WindowsDarwinTDISPLAY F)platformsystemosenvironr   r   r   r   _can_open_browserl   s
   zKaggleOAuth._can_open_browserrO   scopesr@   r   c                 C   s`   t  }||_|j|_d|_| jjj|}t| j|j	|j
ttjt|jd |j|d| _d S )Nauthorization_code)seconds)r
   refresh_tokenaccess_tokenaccess_token_expirationusernamerk   )r   rO   r!   
grant_typer   securityoauth_clientexchange_oauth_tokenr   refreshTokenaccessTokenr   nowr   utcr   
expires_inrq   r   )r   rO   rk   r@   requestresponser   r   r   _exchange_oauth_tokenv   s   z!KaggleOAuth._exchange_oauth_tokenno_launch_browserr-   c           
         sd  | ot  }j }|r"tdd}d| }jd|  t  jj	t j
|jjd}|rt| td td| d d	tffd
d  fdd}d_td|f|$}jd| d jrz|  jssjd W d    jS 1 sw   Y  jS td td|  tddd t }	|	 jS )Ni@  i(#  zhttp://localhost:z!Will listen for the callback at: )	client_idredirect_uriscoper   r#   z&Your browser has been opened to visit:z  z

rO   c                    s    |   d S r   )r}   )rO   )r@   rk   r   r   r   ru      s   z9KaggleOAuth._run_oauth_flow.<locals>.exchange_oauth_tokenc                     s   t j|  jd|S )Nr>   )r   ra   r   )rG   rH   )ru   r@   r   r   r   handler_factory   s   z4KaggleOAuth._run_oauth_flow.<locals>.handler_factoryTz	127.0.0.1zListening for callback on port z...z)OAuth flow completed (or server stopped).zW
Go to the following link in your browser, and complete the sign-in prompts at Kaggle:
zF
Once finished, enter the verification code provided in your browser: re   )end)r   rj   r   get_oauth_default_redirect_urlrandomrandintr   rV   r   build_start_oauth_urlOAUTH_CLIENT_IDr   r#   
webbrowseropenprintr   r   socketserver	TCPServerhandle_requestinputr}   r   )
r   rk   r~   use_browserr   portoauth_start_urlr   httpdrO   r   )ru   r@   rk   r   r   _run_oauth_flow   sP   




zKaggleOAuth._run_oauth_flowc                 C   s
   d| _ d S r   )r   r$   r   r   r   r_      r+   zKaggleOAuth.stop_servercredsc                 C   s   |st d| S )NzAuthentication failed.)	Exception
introspect)r   r   r   r   r   _ensure_creds_valid   s   zKaggleOAuth._ensure_creds_validFc                 C   s2   |  ||}| |}|  td| d |S )Nz
You are now logged in as [z]
)r   r   saver   )r   rk   r~   r   rq   r   r   r   authenticate   s
   
zKaggleOAuth.authenticateN)F)r   r;   r<   r   r   r   r   httpserverBaseHTTPRequestHandlerra   staticmethodrj   r   listr}   boolr   r   r_   r   r   r   r   r   r   r      s    ;
	5 r   )r5   r2   http.serverr   r   rh   rf   r   r'   r   r   urllib.parserQ   r   r   r   r   kagglesdk.kaggle_clientr   kagglesdk.kaggle_credsr   &kagglesdk.security.types.oauth_servicer   r   r   r   r   r   <module>   s"    