
    ~hI                         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y)    )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                   ,   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!y)"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_hintNc                    || _         || _        || _        || _        ||rd}nd}|| _        ||rd}nd}|| _        || _        || _        |	| _        | j                  |
||       | _
        || _        |j                  dd       }|rt        d      || _        t               t               t               t               t               d| _        i | _        || _        y )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*   r1   r-   r   s                   Q/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/authlib/oauth2/client.py__init__zOAuth2Client.__init__5   s    " "*
%--B*-3**D'*22G/28//N,
(%:"//M( _d;N  ! &)U%(U&)e$'E(+ 
      c                     t        |t              r|d   | j                  |d   <   y|| j                  |j                  <   y)zmExtend client authenticate for token endpoint.

        :param auth: an instance to sign the request
        r   r   N)
isinstancetupler0   name)r2   auths     r5   register_client_auth_methodz(OAuth2Client.register_client_auth_methodu   s:    
 dE"*.q'DtAw',0Dtyy)r7   c                     t        |t              r|| j                  v r| j                  |   }| j                  | j                  | j
                  |      S )N)r    r!   auth_method)r9   strr0   client_auth_classr    r!   )r2   r?   s     r5   client_authzOAuth2Client.client_auth   sT    k3'K4;M;M,M,,[9K%%nn,,# & 
 	
r7   c                 .    | j                   j                  S N)r)   r3   r2   s    r5   r3   zOAuth2Client.token   s    $$$r7   c                 :    | j                   j                  |       y rD   )r)   	set_token)r2   r3   s     r5   r3   zOAuth2Client.token   s    !!%(r7   c                    |
t               }| j                  j                  dd      }|j                  d|      }d|vr| j                  |d<   d|vr| j
                  |d<   |r1|dk(  r,| j                  dk(  rt        |      |d<   | j                  |d<   | j                  D ](  }||vs|| j                  v s| 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
        response_typecoder&   r%   S256code_challenger'   )r    rI   r"   )r   r-   getr+   r&   r%   r'   r   EXTRA_AUTHORIZE_PARAMSr   r    )r2   urlr"   code_verifierkwargsrI   kuris           r5   create_authorization_urlz%OAuth2Client.create_authorization_url   s    ="$E))/6B

?MB'%)%6%6F>"& "jjF7O '**f4'A-'PF#$.2.H.HF*+,, 	-A1#5 MM!,q		-  
nn'	

 
 Ezr7   c                     |xs | j                   }|j                  dd      }	|	rd|	v r| j                  |	|      S | j                  |      }
|	rd|	v rd}t	        |	|      }|d   |d<   || j
                  j                  d      }|t        |      }|| j
                  d<    | j                  ||fi |}|| j                  | j                        }|t        }|| j
                  j                  d	      } | j                  |f||||d
|
S )am  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
        :return: A :class:`OAuth2Token` object (a dict too).
        authorization_responseN#zcode=authorization_code)r"   rJ   
grant_typetoken_endpoint)bodyr<   methodheaders)r"   r+   token_from_fragment_extract_session_request_paramsr	   r-   rM   _guess_grant_type_prepare_token_endpoint_bodyrB   r#   DEFAULT_HEADERS_fetch_token)r2   rO   r[   r\   r]   r<   rY   r"   rQ   rV   session_kwargsparamss               r5   fetch_tokenzOAuth2Client.fetch_token   s@   4 #!',Dd!K!c-C&C++,BEJJ==fE!g1G&G-J6&F $F^F6N**<8J*62J*4DMM,'0t00zLVL<##D$C$CDD?%G;--##$45C t  
fg
IW
 	
r7   c                 ~    t        ||      }d|v r%| j                  |d   |j                  d            || _        |S )Nerrorerror_descriptionrh   description)r
   oauth_error_classrM   r3   )r2   rV   r"   r3   s       r5   r^   z OAuth2Client.token_from_fragment   sP    '(>Fe((Gn%))<O2P )   
r7   c                    | j                  |      }|xs | j                  j                  d      }d|vr| j                  r| j                  |d<   t	        d|fd|i|}|t
        j                         }|| j                  j                  d      }| j                  d   D ]  } ||||      \  }}} || j                  | 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%   rZ   r   )rn   r[   r]   r<   )r_   r3   rM   r%   r   rb   copyr-   r/   rB   r#   _refresh_token)	r2   rO   rn   r[   r<   r]   rQ   rd   hooks	            r5   rn   zOAuth2Client.refresh_token  s    ==fE%H)H& TZZ"jjF7O$T
1>
BH
 ?%**,G;--##$45C(()@A 	:D!%c7D!9C$	: <##D$C$CDD"t""
'
 
 	
r7   c                    || j                   }|j                  | j                        sy|j                  d      }| j                  j                  d      }|r|r| j                  ||       y| j                  j                  d      dk(  r8|d   }| j                  |d	      }| j                  r| j                  ||
       yy )N)r1   Trn   rZ   rn   rY   client_credentialsaccess_token)rY   )ru   )r3   
is_expiredr1   rM   r-   rn   rf   r*   )r2   r3   rn   rO   ru   	new_tokens         r5   ensure_active_tokenz OAuth2Client.ensure_active_token,  s    =JJEt{{3		/2mm 01Ss-@]]|,0DD 0L((9M(NI  !!),!G Er7   c           	      p    || j                  | 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
        r   r3   token_type_hintr[   r<   r]   )rB   r$   _handle_token_hintr2   rO   r3   r{   r[   r<   r]   rQ   s           r5   revoke_tokenzOAuth2Client.revoke_token=  sZ    0 <##D$H$HID&t&&"	
 +	
 	
 		
r7   c           	      p    || j                  | 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
        r   rz   )rB   r#   r|   r}   s           r5   introspect_tokenzOAuth2Client.introspect_tokenb  sZ    0 <##D$C$CDD&t&&&	
 +	
 	
 		
r7   c                     |dk(  r&| j                   j                  j                  |       y|| j                  vrt	        d|| j                        | j                  |   j                  |       y)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addr/   r,   )r2   	hook_typerq   s      r5   register_compliance_hookz%OAuth2Client.register_compliance_hook  sk     ++OO!!%%d+D000,i9M9M  	Y'++D1r7   c                     |j                   dk\  r|j                          |j                         }d|v r%| j                  |d   |j	                  d            || _        | j
                  S )Ni  rh   ri   rj   )status_coderaise_for_statusjsonrl   rM   r3   )r2   respr3   s      r5   parse_response_tokenz!OAuth2Client.parse_response_token  sm    s"!!#		e((Gn%))<O2P )   
zzr7   c                    |j                         dk(  r4 | j                  j                  |ft        t	        |            ||d|}nLd|v rdj                  ||g      }ndj                  ||g      } | j                  j                  ||f||d|}| j                  d   D ]
  } ||      } | j                  |      S )NPOSTdatar]   r<   ?&)r]   r<   r   )	upperr   postdictr   joinrequestr/   r   )	r2   rO   r[   r]   r<   r\   rQ   r   rq   s	            r5   rc   zOAuth2Client._fetch_token  s     <<>V#$4<<$$z$/0'PVD czhhT{+hhT{+'4<<''%,4;AD (()@A 	D:D	 ((..r7   c                 ,    | j                   |f|||d|}| j                  d   D ]
  } ||      } | j                  |      }	d|	vr|| j                  d<   t	        | j
                        r| j                  | j                  |       | j                  S )N)r[   r<   r]   r   rn   rs   )
_http_postr/   r   r3   callabler*   )
r2   rO   rn   r[   r]   r<   rQ   r   rq   r3   s
             r5   rp   zOAuth2Client._refresh_token  s     tsTD'TVT(()AB 	D:D	 ))$/%'*7DJJ'D%%&djjFzzr7   c                    |D| j                   r8| j                   j                  d      xs | j                   j                  d      }|d}t        ||||      \  }}| j                  |   D ]  }	 |	|||      \  }}} || j	                  | j
                        }| j                  |      }
 | j                  ||f||d|
S )Nrn   ru    )r<   r]   )r3   rM   r   r/   rB   r$   r_   r   )r2   rq   rO   r3   r{   r[   r<   r]   rQ   r/   rd   s              r5   r|   zOAuth2Client._handle_token_hint  s     =TZZJJNN?3Utzz~~n7UE<D4?D'
g  $33D9 	EO!0gt!DC$	E <##D$H$HID==fEtsDWtWWWWr7   c                     |dk(  r d|vr| j                   |d<   t        ||fi |S d|vr| j                  r| j                  |d<   t        ||fi |S )NrX   r&   r%   )r&   r   r%   )r2   r[   rY   rQ   s       r5   ra   z)OAuth2Client._prepare_token_endpoint_body  sb    --V+)-):):~&(TDVDD& TZZ"jjF7O$Z@@@r7   c                 ^    i }| j                   D ]  }||v s|j                  |      ||<    |S )zDExtract parameters for session object from the passing ``**kwargs``.)SESSION_REQUEST_PARAMSr+   )r2   rQ   rvrR   s       r5   r_   z,OAuth2Client._extract_session_request_params  s;    ,, 	&AF{

11	& 	r7   c                 h     | j                   j                  |ft        t        |            ||d|S )Nr   )r   r   r   r   )r2   rO   r[   r<   r]   rQ   s         r5   r   zOAuth2Client._http_post  s<     t||  
:d+,gD
LR
 	
r7   c                     | ` y rD   )r   rE   s    r5   __del__zOAuth2Client.__del__  s    Lr7   )NNNNNNNNNheaderN<   )NN)Nr   r   NNNNrD   )NNr   NN)NNNNN)r   NNr   )Nr   NN)NNN)"__name__
__module____qualname____doc__r   rA   r   r(   r   rl   rN   r   r6   r=   rB   propertyr3   setterrT   rf   r^   rn   rx   r~   r   r   r   rc   rp   r|   ra   r_   r   r    r7   r5   r   r      s>   2 # #O
 #'(," >@1
 % % \\) )'V >
@ IM(
T( #
P #
J2,
 =C/, DH* X<A

r7   r   c                 2    d| v rd}|S d| v rd| v rd}|S d}|S )NrJ   rX   usernamepasswordrt   r   )rQ   rY   s     r5   r`   r`     sB    )

 	 
v	*"6
  *
r7   N)authlib.common.securityr   authlib.common.urlsr   r<   r   r   baser   rfc6749.parametersr	   r
   r   r   rfc7009r   rfc7636r   rb   r   r`   r   r7   r5   <module>r      sG    2 *    A 7 1 5 1 / !Eq qhr7   