
    !<iI                         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 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 ddlmZ dddZ G d d          Zd ZdS )    )generate_token)
url_decode   )
ClientAuth)	TokenAuth)OAuth2Error)!parse_authorization_code_response)parse_implicit_response)prepare_grant_uri)prepare_token_request)prepare_revoke_token_request)create_s256_code_challengezapplication/jsonz/application/x-www-form-urlencoded;charset=UTF-8)AcceptzContent-Typec                   0   e Zd ZdZeZeZeZ	dZ
g Z	 	 	 	 	 	 	 	 	 	 	 	 ddZd Zd Zed	             Zej        d
             ZddZ	 	 	 	 	 	 	 ddZd dZ	 d!dZd dZ	 	 	 	 	 d"dZ	 	 	 	 	 d"dZd Zd Z	 d#dZ	 d$dZ	 	 	 	 	 d"dZd Zd Zd%dZ d Z!dS )&OAuth2Clienta
  Construct a new OAuth 2 protocol client.

    :param session: Requests session object to communicate with
                    authorization server.
    :param client_id: Client ID, which you get from client registration.
    :param client_secret: Client Secret, which you get from registration.
    :param token_endpoint_auth_method: client authentication method for
        token endpoint.
    :param revocation_endpoint_auth_method: client authentication method for
        revocation endpoint.
    :param scope: Scope that you needed to access user resources.
    :param state: Shared secret to prevent CSRF attack.
    :param redirect_uri: Redirect URI you registered as callback.
    :param code_challenge_method: PKCE method name, only S256 is supported.
    :param token: A dict of token attributes such as ``access_token``,
        ``token_type`` and ``expires_at``.
    :param token_placement: The place to put token in HTTP request. Available
        values: "header", "body", "uri".
    :param update_token: A function for you to update token. It accept a
        :class:`OAuth2Token` as parameter.
    :param leeway: Time window in seconds before the actual expiration of the
        authentication token, that the token is considered expired and will
        be refreshed.
    )response_modenonceprompt
login_hintNheader<   c                    || _         || _        || _        || _        ||rd}nd}|| _        ||rd}nd}|| _        || _        || _        |	| _        | 	                    |
||           | _
        || _        |                    dd           }|rt          d          || _        t                      t                      t                      t                      t                      d| _        i | _        || _        d S )Nclient_secret_basicnonetoken_updaterz<update token has been redesigned, checkout the documentation)access_token_responserefresh_token_requestrefresh_token_responserevoke_token_requestintrospect_token_request)session	client_idclient_secretstatetoken_endpoint_auth_methodrevocation_endpoint_auth_methodscoperedirect_uricode_challenge_methodtoken_auth_class
token_authupdate_tokenpop
ValueErrormetadatasetcompliance_hook_auth_methodsleeway)selfr!   r"   r#   r%   r&   r'   r$   r(   r)   tokentoken_placementr,   r3   r/   r   s                   /Users/kimhansen/Desktop/03 Workspace/ceo-agents/chl-effectiveness/mcp-servers/whoop/.venv/lib/python3.11/site-packages/authlib/oauth2/client.py__init__zOAuth2Client.__init__5   s%   " "*
%- 4-B**-3**D'*2 92G//28//N,
(%:"//MM( _d;; 	N   ! &)UU%(UU&)ee$'EE(+ 
  
      c                 ~    t          |t                    r|d         | j        |d         <   dS || j        |j        <   dS )zmExtend client authenticate for token endpoint.

        :param auth: an instance to sign the request
        r   r   N)
isinstancetupler2   name)r4   auths     r7   register_client_auth_methodz(OAuth2Client.register_client_auth_methodu   sF    
 dE"" 	1*.q'DtAw''',0Dty)))r9   c                     t          |t                    r|| j        v r| j        |         }|                     | j        | j        |          S )N)r"   r#   auth_method)r;   strr2   client_auth_classr"   r#   )r4   rA   s     r7   client_authzOAuth2Client.client_auth   sY    k3'' 	:K4;M,M,M,[9K%%n,# & 
 
 	
r9   c                     | j         j        S N)r+   r5   r4   s    r7   r5   zOAuth2Client.token   s    $$r9   c                 :    | j                             |           d S rF   )r+   	set_token)r4   r5   s     r7   r5   zOAuth2Client.token   s    !!%(((((r9   c                    |t                      }| j                            dd          }|                    d|          }d|vr
| j        |d<   d|vr
| j        |d<   |r-|dk    r'| j        dk    rt          |          |d<   | j        |d<   | j        D ]}||vr|| j        v r| j        |         ||<    t          |f| j
        ||d	|}||fS )
a  Generate an authorization URL and state.

        :param url: Authorization endpoint url, must be HTTPS.
        :param state: An optional state string for CSRF protection. If not
                      given it will be generated for you.
        :param code_verifier: An optional code_verifier for code challenge.
        :param kwargs: Extra parameters to include.
        :return: authorization_url, state
        Nresponse_typecoder(   r'   S256code_challenger)   )r"   rK   r$   )r   r/   getr-   r(   r'   r)   r   EXTRA_AUTHORIZE_PARAMSr   r"   )r4   urlr$   code_verifierkwargsrK   kuris           r7   create_authorization_urlz%OAuth2Client.create_authorization_url   s&    ="$$E))/6BB

?MBB''%)%6F>"&  "jF7O 	I''*f44'A-'P'PF#$.2.HF*+, 	- 	-A1#5#5 M!,q	
n'	
 

 
 
 Ezr9    POSTc                    |p| j         }|                    dd          }	|	rd|	v r|                     |	|          S |                     |          }
|	r"d|	v rd}t	          |	|          }|d         |d<   || j                            d          }|t          |          }|| j        d<    | j        ||fi |}|| 	                    | j
                  }|t          }|| j                            d	          } | j        |f||||d
|
S )a  Generic method for fetching an access token from the token endpoint.

        :param url: Access Token endpoint URL, if not configured,
                    ``authorization_response`` is used to extract token from
                    its fragment (implicit way).
        :param body: Optional application/x-www-form-urlencoded body to add the
                     include in the token request. Prefer kwargs over body.
        :param method: The HTTP method used to make the request. Defaults
                       to POST, but may also be GET. Other methods should
                       be added as needed.
        :param headers: Dict to default request headers with.
        :param auth: An auth tuple or method as accepted by requests.
        :param grant_type: Use specified grant_type to fetch token.
        :param state: Optional "state" value to fetch token.
        :return: A :class:`OAuth2Token` object (a dict too).
        authorization_responseN#zcode=authorization_code)r$   rL   
grant_typetoken_endpoint)bodyr>   methodheaders)r$   r-   token_from_fragment_extract_session_request_paramsr	   r/   rO   _guess_grant_type_prepare_token_endpoint_bodyrD   r%   DEFAULT_HEADERS_fetch_token)r4   rQ   r_   r`   ra   r>   r]   r$   rS   rZ   session_kwargsparamss               r7   fetch_tokenzOAuth2Client.fetch_token   so   6 #!',Dd!K!K! 	Kc-C&C&C++,BEJJJ==fEE! 	,g1G&G&G-J6&  F $F^F6N**<88J*622J*4DM,'0t0zLLVLL<##D$CDDD?%G;-##$455C t 
fg
 
IW
 
 	
r9   c                     t          ||          }d|v r0|                     |d         |                    d                    || _        |S )Nerrorerror_descriptionrl   description)r
   oauth_error_classrO   r5   )r4   rZ   r$   r5   s       r7   rb   z OAuth2Client.token_from_fragment   s^    '(>FFe((Gn%))<O2P2P )    
r9   c                    |                      |          }|p| j                            d          }d|vr| j        r
| j        |d<   t	          d|fd|i|}|t
                                          }|| j                            d          }| j        d         D ]} ||||          \  }}}|| 	                    | j
                  } | j        |f||||d|S )a	  Fetch a new access token using a refresh token.

        :param url: Refresh Token endpoint, must be HTTPS.
        :param refresh_token: The refresh_token to use.
        :param body: Optional application/x-www-form-urlencoded body to add the
                     include in the token request. Prefer kwargs over body.
        :param auth: An auth tuple or method as accepted by requests.
        :param headers: Dict to default request headers with.
        :return: A :class:`OAuth2Token` object (a dict too).
        refresh_tokenr'   Nr^   r   )rr   r_   ra   r>   )rc   r5   rO   r'   r   rf   copyr/   r1   rD   r%   _refresh_token)	r4   rQ   rr   r_   r>   ra   rS   rh   hooks	            r7   rr   zOAuth2Client.refresh_token  s1    ==fEE%H)H)H&  TZ "jF7O$T
 
1>
BH
 
 ?%**,,G;-##$455C()@A 	: 	:D!%c7D!9!9C$$<##D$CDDD"t"
'
 
 
 
 	
r9   c                    || j         }|                    | j                  sdS |                    d          }| j                            d          }|r|r|                     ||           dS | j                            d          dk    r?|d         }|                     |d	          }| j        r|                     ||
           dS d S )N)r3   Trr   r^   rr   r]   client_credentialsaccess_token)r]   )ry   )r5   
is_expiredr3   rO   r/   rr   rj   r,   )r4   r5   rr   rQ   ry   	new_tokens         r7   ensure_active_tokenz OAuth2Client.ensure_active_token-  s    =JEt{33 	4		/22m 011 	S 	s-@@@4]|,,0DDD 0L((9M(NNI  H!!),!GGG4 EDr9   c           	      d    ||                      | j                  } | j        d|f|||||d|S )a  Revoke token method defined via `RFC7009`_.

        :param url: Revoke Token endpoint, must be HTTPS.
        :param token: The token to be revoked.
        :param token_type_hint: The type of the token that to be revoked.
                                It can be "access_token" or "refresh_token".
        :param body: Optional application/x-www-form-urlencoded body to add the
                     include in the token request. Prefer kwargs over body.
        :param auth: An auth tuple or method as accepted by requests.
        :param headers: Dict to default request headers with.
        :return: Revocation Response

        .. _`RFC7009`: https://tools.ietf.org/html/rfc7009
        Nr   r5   token_type_hintr_   r>   ra   )rD   r&   _handle_token_hintr4   rQ   r5   r   r_   r>   ra   rS   s           r7   revoke_tokenzOAuth2Client.revoke_token>  sa    0 <##D$HIID&t&"	
 +	
 	
 	
 	
 		
r9   c           	      d    ||                      | j                  } | j        d|f|||||d|S )a  Implementation of OAuth 2.0 Token Introspection defined via `RFC7662`_.

        :param url: Introspection Endpoint, must be HTTPS.
        :param token: The token to be introspected.
        :param token_type_hint: The type of the token that to be revoked.
                                It can be "access_token" or "refresh_token".
        :param body: Optional application/x-www-form-urlencoded body to add the
                     include in the token request. Prefer kwargs over body.
        :param auth: An auth tuple or method as accepted by requests.
        :param headers: Dict to default request headers with.
        :return: Introspection Response

        .. _`RFC7662`: https://tools.ietf.org/html/rfc7662
        Nr    r~   )rD   r%   r   r   s           r7   introspect_tokenzOAuth2Client.introspect_tokenc  sa    0 <##D$CDDD&t&&	
 +	
 	
 	
 	
 		
r9   c                     |dk    r!| j         j                            |           dS || j        vrt	          d|| j                  | j        |                             |           dS )a  Register a hook for request/response tweaking.

        Available hooks are:

        * access_token_response: invoked before token parsing.
        * refresh_token_request: invoked before refreshing token.
        * refresh_token_response: invoked before refresh token parsing.
        * protected_request: invoked before making a request.
        * revoke_token_request: invoked before revoking a token.
        * introspect_token_request: invoked before introspecting a token.
        protected_requestNzHook type %s is not in %s.)r+   hooksaddr1   r.   )r4   	hook_typeru   s      r7   register_compliance_hookz%OAuth2Client.register_compliance_hook  s|     +++O!%%d+++FD000,i9M   	Y'++D11111r9   c                     |j         dk    r|                                 |                                }d|v r0|                     |d         |                    d                    || _        | j        S )Ni  rl   rm   rn   )status_coderaise_for_statusjsonrp   rO   r5   )r4   respr5   s      r7   parse_response_tokenz!OAuth2Client.parse_response_token  s~    s""!!###		e((Gn%))<O2P2P )    
zr9   c                    |                                 dk    r2 | j        j        |ft          t	          |                    ||d|}nJd|v rd                    ||g          }nd                    ||g          } | j        j        ||f||d|}| j        d         D ]} ||          }|                     |          S )NrX   datara   r>   ?&)ra   r>   r   )	upperr!   postdictr   joinrequestr1   r   )	r4   rQ   r_   ra   r>   r`   rS   r   ru   s	            r7   rg   zOAuth2Client._fetch_token  s    <<>>V##$4<$z$//00' PV DD czzhhT{++hhT{++'4<'%,4 ;A D ()@A 	 	D4::DD((...r9   c                     | j         |f|||d|}| j        d         D ]} ||          }|                     |          }	d|	vr
|| j        d<   t	          | j                  r|                     | j        |           | j        S )N)r_   r>   ra   r   rr   rw   )
_http_postr1   r   r5   callabler,   )
r4   rQ   rr   r_   ra   r>   rS   r   ru   r5   s
             r7   rt   zOAuth2Client._refresh_token  s     tsTD'TTVTT()AB 	 	D4::DD))$//%''*7DJ'D%&& 	GdjFFFzr9   c                 v   |;| j         r4| j                             d          p| j                             d          }|d}t          ||||          \  }}| j        |         D ]}	 |	|||          \  }}}||                     | j                  }|                     |          }
 | j        ||f||d|
S )Nrr   ry   rW   )r>   ra   )r5   rO   r   r1   rD   r&   rc   r   )r4   ru   rQ   r5   r   r_   r>   ra   rS   r1   rh   s              r7   r   zOAuth2Client._handle_token_hint  s     =TZ=JNN?33Utz~~n7U7UE<D4?D'
 
g  $3D9 	E 	EO!0gt!D!DC$$<##D$HIID==fEEtsDWtWWWWWWr9   c                     |dk    rd|vr
| j         |d<   t          ||fi |S d|vr| j        r
| j        |d<   t          ||fi |S )Nr\   r(   r'   )r(   r   r'   )r4   r_   r]   rS   s       r7   re   z)OAuth2Client._prepare_token_endpoint_body  ss    ---V++)-):~&(TDDVDDD&  TZ "jF7O$Z@@@@@r9   c                 V    i }| j         D ]}||v r|                    |          ||<   |S )zDExtract parameters for session object from the passing ``**kwargs``.)SESSION_REQUEST_PARAMSr-   )r4   rS   rvrT   s       r7   rc   z,OAuth2Client._extract_session_request_params  s;    , 	& 	&AF{{

11	r9   c                 d     | j         j        |ft          t          |                    ||d|S )Nr   )r!   r   r   r   )r4   rQ   r_   r>   ra   rS   s         r7   r   zOAuth2Client._http_post   sG     t| 
:d++,,gD
 
LR
 
 	
r9   c                 
    | ` d S rF   )r!   rG   s    r7   __del__zOAuth2Client.__del__  s    LLLr9   )NNNNNNNNNr   Nr   )NN)NrW   rX   NNNNrF   )NNrW   NN)NNNNN)rW   NNrX   )NrW   NN)NNN)"__name__
__module____qualname____doc__r   rC   r   r*   r   rp   rP   r   r8   r?   rD   propertyr5   setterrV   rj   rb   rr   r|   r   r   r   r   rg   rt   r   re   rc   r   r    r9   r7   r   r      s`        2 # #O
 #'(," > > > >@1 1 1
 
 
 % % X% \) ) \)' ' ' 'V ?
 ?
 ?
 ?
B    IM(
 (
 (
 (
T   ( #
 #
 #
 #
P #
 #
 #
 #
J2 2 2,
 
 
 =C/ / / /, DH   * X X X X<A A A  
 
 
 

    r9   r   c                 .    d| v rd}nd| v rd| v rd}nd}|S )NrL   r\   usernamepasswordrx   r   )rS   r]   s     r7   rd   rd   	  s;    )

	v		*"6"6

)
r9   N)authlib.common.securityr   authlib.common.urlsr   r>   r   r   baser   rfc6749.parametersr	   r
   r   r   rfc7009r   rfc7636r   rf   r   rd   r   r9   r7   <module>r      s)   2 2 2 2 2 2 * * * * * *                   A A A A A A 7 7 7 7 7 7 1 1 1 1 1 1 5 5 5 5 5 5 1 1 1 1 1 1 / / / / / / !E r r r r r r r rj    r9   