
    &g|]                         d dl Z d dlmZmZ d dlmZmZ d dlmZ d dlmZm	Z	 d dl
Z
 e j        e          Z G d de          Z G d d	e
j                  ZdS )
    N)generate_token	urldecode)WebApplicationClientInsecureTransportError)LegacyApplicationClient)TokenExpiredErroris_secure_transportc                        e Zd Z fdZ xZS )TokenUpdatedc                 d    t          t          |                                            || _        d S N)superr   __init__token)selfr   	__class__s     R/var/www/api/venv/lib/python3.11/site-packages/requests_oauthlib/oauth2_session.pyr   zTokenUpdated.__init__   s*    lD!!**,,,


    )__name__
__module____qualname__r   __classcell__r   s   @r   r   r      s8                r   r   c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d fd	Zed             Zej        d             Zd Zed             Z	e	j        d             Z	e	j
        d	             Z	ed
             Zej        d             Zed             Zej        d             Zej
        d             Zed             ZddZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd Z	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 d fd	Zd Z xZS )OAuth2Sessiona*  Versatile OAuth 2 extension to :class:`requests.Session`.

    Supports any grant type adhering to :class:`oauthlib.oauth2.Client` spec
    including the four core OAuth 2 grants.

    Can be used to create authorization urls, fetch tokens and access protected
    resources using the :class:`requests.Session` interface you are used to.

    - :class:`oauthlib.oauth2.WebApplicationClient` (default): Authorization Code Grant
    - :class:`oauthlib.oauth2.MobileApplicationClient`: Implicit Grant
    - :class:`oauthlib.oauth2.LegacyApplicationClient`: Password Credentials Grant
    - :class:`oauthlib.oauth2.BackendApplicationClient`: Client Credentials Grant

    Note that the only time you will be using Implicit Grant from python is if
    you are driving a user agent able to obtain URL fragments.
    Nc                     t          t          |           j        di | |pt          ||          | _        |pi | _        || _        || _        |pt          | _	        || _
        || _        |pi | _        |	| _        |
| _        | j        dvr-t          d                    | j        | j                            d | _        t'                      t'                      t'                      t'                      t'                      d| _        dS )a  Construct a new OAuth 2 client session.

        :param client_id: Client id obtained during registration
        :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
                       WebApplicationClient which is useful for any
                       hosted application but not mobile or desktop.
        :param scope: List of scopes you wish to request access to
        :param redirect_uri: Redirect URI you registered as callback
        :param token: Token dictionary, must include access_token
                      and token_type.
        :param state: State string used to prevent CSRF. This will be given
                      when creating the authorization url and must be supplied
                      when parsing the authorization response.
                      Can be either a string or a no argument callable.
        :auto_refresh_url: Refresh token endpoint URL, must be HTTPS. Supply
                           this if you wish the client to automatically refresh
                           your access tokens.
        :auto_refresh_kwargs: Extra arguments to pass to the refresh token
                              endpoint.
        :token_updater: Method with one argument, token, to be used to update
                        your token database on automatic token refresh. If not
                        set a TokenUpdated warning will be raised when a token
                        has been refreshed. This warning will carry the token
                        in its token argument.
        :param pkce: Set "S256" or "plain" to enable PKCE. Default is disabled.
        :param kwargs: Arguments to pass to the Session constructor.
        )r   )S256plainNzWrong value for {}(.., pkce={})c                     | S r    )rs    r   <lambda>z(OAuth2Session.__init__.<locals>.<lambda>^   s    a r   )access_token_responserefresh_token_responseprotected_requestrefresh_token_requestaccess_token_requestNr    )r   r   r   r   _clientr   _scoperedirect_urir   state_stateauto_refresh_urlauto_refresh_kwargstoken_updater_pkceAttributeErrorformatr   authsetcompliance_hook)r   	client_idclientr-   r.   scoper*   r   r+   r/   pkcekwargsr   s               r   r   zOAuth2Session.__init__$   s   R 	,mT""+55f555M!5iu!M!M!M[b
(,n
 0#6#<" *
:444 !B!I!I$.Z^Zd!e!efff  K	
 &)UU&)ee!$%(UU$'EE 
  
r   c                 H    | j         | j         S | j        | j        j        S dS )zBBy default the scope from the client is used, except if overriddenN)r)   r(   r8   r   s    r   r8   zOAuth2Session.scopej   s,     ;";\%<%%4r   c                     || _         d S r   )r)   )r   r8   s     r   r8   zOAuth2Session.scopet   s    r   c                     	 |                                  | _        t                              d| j                   n<# t          $ r/ | j         | _        t                              d| j                   Y nw xY w| j        S )z6Generates a state string to be used in authorizations.zGenerated new state %s.z&Re-using previously supplied state %s.)r+   r,   logdebug	TypeErrorr<   s    r   	new_statezOAuth2Session.new_statex   s    	M**,,DKII/==== 	M 	M 	M*DKII>LLLLL	M {s   9< 6A54A5c                 .    t          | j        dd           S )Nr6   getattrr(   r<   s    r   r6   zOAuth2Session.client_id   s    t|[$777r   c                     || j         _        d S r   r(   r6   r   values     r   r6   zOAuth2Session.client_id   s    !&r   c                     | j         `d S r   rG   r<   s    r   r6   zOAuth2Session.client_id   s    L"""r   c                 .    t          | j        dd           S )Nr   rD   r<   s    r   r   zOAuth2Session.token   s    t|Wd333r   c                 R    || j         _        | j                             |           d S r   )r(   r   populate_token_attributesrH   s     r   r   zOAuth2Session.token   s(    "..u55555r   c                 .    t          | j        dd           S )Naccess_tokenrD   r<   s    r   rO   zOAuth2Session.access_token   s    t|^T:::r   c                     || j         _        d S r   r(   rO   rH   s     r   rO   zOAuth2Session.access_token   s    $)!!!r   c                     | j         `d S r   rQ   r<   s    r   rO   zOAuth2Session.access_token   s    L%%%r   c                 *    t          | j                  S )a  Boolean that indicates whether this session has an OAuth token
        or not. If `self.authorized` is True, you can reasonably expect
        OAuth-protected requests to the resource to succeed. If
        `self.authorized` is False, you need the user to go through the OAuth
        authentication dance before OAuth-protected requests to the resource
        will succeed.
        )boolrO   r<   s    r   
authorizedzOAuth2Session.authorized   s     D%&&&r   c                 &   |p|                                  }| j        rR| j                            d          | _        | j        |d<   | j                            | j        | j                  |d<    | j        j        |f| j        | j        |d||fS )aF  Form an authorization URL.

        :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 kwargs: Extra parameters to include.
        :return: authorization_url, state
        +   code_challenge_method)code_verifierrX   code_challenge)r*   r8   r+   )	rB   r0   r(   create_code_verifier_code_verifiercreate_code_challengeprepare_request_urir*   r8   )r   urlr+   r:   s       r   authorization_urlzOAuth2Session.authorization_url   s     ))): 	"&,"C"CB"G"GD.2jF*+'+|'I'I"1&*j (J ( (F#$
 -DL,!.j	 
   	
 		
r    POSTFc                    t          |          st                      |s0|r.| j                            || j                   | j        j        }n9|s7t          | j        t                    r| j        j        }|st          d          | j	        r | j
        t          d          | j
        |d<   t          | j        t                    r"|t          d          |t          d          |||d<   |||d	<   ||d
}nN|durJ| j        }|rAt                              d|           ||nd}t          j                            ||          }|r|||d<    | j        j        d%||| j        |d|}|pddd}i | _        i }|                                dk    r$t-          t/          |                    ||	rdnd<   nG|                                dk    r t-          t/          |                    |d<   nt          d          | j        d         D ].}t                              d|            ||||          \  }}}/ | j        d%|||
|||||d|}t                              d|j                   t                              d|j        j                   t                              d|j        j                   t                              d|j        j                   t                              d|j        |j                   t                              d t?          | j        d!                              | j        d!         D ](}t                              d"|            ||          })| j                             |j        | j!        #           | j        j        | _        t                              d$| j                   | j        S )&a  Generic method for fetching an access token from the token endpoint.

        If you are using the MobileApplicationClient you will want to use
        `token_from_fragment` instead of `fetch_token`.

        The current implementation enforces the RFC guidelines.

        :param token_url: Token endpoint URL, must use HTTPS.
        :param code: Authorization code (used by WebApplicationClients).
        :param authorization_response: Authorization response URL, the callback
                                       URL of the request back to you. Used by
                                       WebApplicationClients instead of code.
        :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 username: Username required by LegacyApplicationClients to appear
                         in the request body.
        :param password: Password required by LegacyApplicationClients to appear
                         in the request 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 force_querystring: If True, force the request body to be sent
            in the querystring instead.
        :param timeout: Timeout of the request in seconds.
        :param headers: Dict to default request headers with.
        :param verify: Verify SSL certificate.
        :param proxies: The `proxies` argument is passed onto `requests`.
        :param include_client_id: Should the request body include the
                                  `client_id` parameter. Default is `None`,
                                  which will attempt to autodetect. This can be
                                  forced to always include (True) or never
                                  include (False).
        :param client_secret: The `client_secret` paired to the `client_id`.
                              This is generally required unless provided in the
                              `auth` tuple. If the value is `None`, it will be
                              omitted from the request, however if the value is
                              an empty string, an empty string will be sent.
        :param cert: Client certificate to send for OAuth 2.0 Mutual-TLS Client
                     Authentication (draft-ietf-oauth-mtls). Can either be the
                     path of a file containing the private key and certificate or
                     a tuple of two filenames for certificate and key.
        :param kwargs: Extra parameters to include in the token request.
        :return: A token dict
        r+   z?Please supply either code or authorization_response parameters.NzFCode verifier is not found, authorization URL must be generated beforerY   zQ`LegacyApplicationClient` requires both the `username` and `password` parameters.zGThe required parameter `username` was supplied, but `password` was not.usernamepasswordFTzIEncoding `client_id` "%s" with `client_secret` as Basic auth credentials.ra   client_secret)codebodyr*   include_client_idapplication/json!application/x-www-form-urlencodedAcceptzContent-Typerb   paramsdataGETz%The method kwarg must be POST or GET.r'   z&Invoking access_token_request hook %s.)methodr_   timeoutheadersr3   verifyproxiescertz0Request to fetch token completed with status %s.zRequest url was %szRequest headers were %szRequest body was %s(Response headers were %s and content %s.!Invoking %d token response hooks.r#   Invoking hook %s.r8   zObtained token %s.r    )"r	   r   r(   parse_request_uri_responser,   rh   
isinstancer   
ValueErrorr0   r\   r   r6   r?   r@   requestsr3   HTTPBasicAuthprepare_request_bodyr*   r   upperdictr   r5   requeststatus_coder_   rt   ri   textlenparse_request_body_responser8   )r   	token_urlrh   authorization_responseri   r3   re   rf   rr   force_querystringrs   rt   ru   rv   rj   rg   rw   r:   r6   request_kwargshookr!   s                         r   fetch_tokenzOAuth2Session.fetch_token   s   B #9-- 	+(*** 
	. 
	L33&dk 4    <$DD 	*T\3GHH 	<$D  X   : 	:"* \   '+&9F?# dl$;<< 
	 <    .   !)F:!)F:  !($)! !,, N	 QII5!  
 6C5NMMTVM#=66y-PPD 	8 (*7'0t|0 
*/	
 

 
 
  
(?
 
 
<<>>V##HL$I IN'8D88fEE \\^^u$$'+IdOO'<'<N8$$DEEE()?@ 	 	DII>EEE157N2 2.Iw DL 



 

 

 

 			DamTTT		&	666		+QY->???		'888		<aiPPP		/$%<=>>	
 	
 	
 ()@A 	 	DII)4000QAA00tz0JJJ\'
		&
333zr   c                 t    | j                             || j                   | j         j        | _        | j        S )zParse token from the URI fragment, used by MobileApplicationClients.

        :param authorization_response: The full URL of the redirect back to you
        :return: A token dict
        rd   )r(   r|   r,   r   )r   r   s     r   token_from_fragmentz!OAuth2Session.token_from_fragment  s@     	//"$+ 	0 	
 	
 	
 \'
zr   c	           
         |st          d          t          |          st                      |p| j                            d          }t
                              d| j                   |	                    | j                    | j	        j
        d||| j        d|	}t
                              d|           |ddd	}| j        d
         D ].}
t
                              d|
            |
|||          \  }}}/|                     |t          t          |                    ||||d|          }t
                              d|j                   t
                              d|j        |j                   t
                              dt'          | j        d                              | j        d         D ](}
t
                              d|
            |
|          })| j	                            |j        | j                  | _        d| j        vr$t
                              d           || j        d<   | j        S )a  Fetch a new access token using a refresh token.

        :param token_url: The 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 timeout: Timeout of the request in seconds.
        :param headers: A dict of headers to be used by `requests`.
        :param verify: Verify SSL certificate.
        :param proxies: The `proxies` argument will be passed to `requests`.
        :param kwargs: Extra parameters to include in the token request.
        :return: A token dict
        z'No token endpoint set for auto_refresh.refresh_tokenz*Adding auto refresh key word arguments %s.)ri   r   r8   z&Prepared refresh token request body %sNrk   rl   rm   r&   z'Invoking refresh_token_request hook %s.T)rp   r3   rs   rt   ru   withhold_tokenrv   z2Request to refresh token completed with status %s.rx   ry   r$   rz   r{   z)No new refresh token given. Re-using old.r    )r~   r	   r   r   getr?   r@   r.   updater(   prepare_refresh_bodyr8   r5   postr   r   r   rt   r   r   r   )r   r   r   ri   r3   rs   rt   ru   rv   r:   r   r!   s               r   r   zOAuth2Session.refresh_token  sb   4  	HFGGG"9-- 	+(***%H)H)H		8$:R	
 	
 	
 	d.///0t|0 
]$*
 
HN
 
 			:DAAA?,!D G
 ()@A 	F 	FDII?FFF'+tIw'E'E$IwIIioo&&  	
 	
 			FVVV		<aiPPP		/$%=>??	
 	
 	
 ()AB 	 	DII)4000QAA\==afDJ=WW
$*,,IIABBB*7DJ'zr   c	                    t          |          st                      | j        r|st                              dt          | j        d                              | j        d         D ].}
t                              d|
            |
|||          \  }}}/t                              d| j                   	 | j                            ||||          \  }}}n# t          $ r | j
        rt                              d| j
                   |	                    dd          }|r?|r=|;t                              d	|           t          j                            ||          } | j        | j
        fd|i|	}| j        rYt                              d
|| j                   |                     |           | j                            ||||          \  }}}nt#          |           Y nw xY wt                              d||           t                              d||           t                              d|	            t%          t&          |           j        ||f|||d|	S )z<Intercept all requests and add the OAuth 2 token if present.z-Invoking %d protected resource request hooks.r%   rz   zAdding token %s to request.)http_methodri   rt   z1Auto refresh is set, attempting to refresh at %s.r3   NzEEncoding client_id "%s" with client_secret as Basic auth credentials.zUpdating token to %s using %s.z"Requesting url %s using method %s.z Supplying headers %s and data %sz&Passing through key word arguments %s.)rt   rp   files)r	   r   r   r?   r@   r   r5   r(   	add_tokenr   r-   popr   r3   r   r   r/   r   r   r   r   )r   rr   r_   rp   rt   r   r6   rg   r   r:   r   r3   r   r   s                r   r   zOAuth2Session.request  s    #3'' 	+(***: ,	n ,	II?D()<=>>   ,-@A > >		-t444%)T#w%=%="WddII3TZ@@@"%)\%;%;V$ &< & &"Wdd %   ( IIK-   "::fd33D  U] U		c%    (}::9mTT.D.- 48<B E ) 	2		<eTEW   **5111-1\-C-CV$ .D . .*Wdd +5111 '+d/> 			6VDDD		4gtDDD		:FCCC1u]D))1C
!(t5
 
DJ
 
 	
s   :"C DG/.G/c                     || 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_response invoked before refresh token parsing.
            protected_request invoked before making a request.
            access_token_request invoked before making a token fetch request.
            refresh_token_request invoked before making a refresh request.

        If you find a new hook is needed please send a GitHub PR request
        or open an issue.
        zHook type %s is not in %s.N)r5   r~   add)r   	hook_typer   s      r   register_compliance_hookz&OAuth2Session.register_compliance_hook:  sR     D000,i9M   	Y'++D11111r   )
NNNNNNNNNNr   )NNra   NNNrb   FNNNNNNN)Nra   NNNNN)NNFNNN)r   r   r   __doc__r   propertyr8   setterrB   r6   deleterr   rO   rU   r`   r   r   r   r   r   r   r   s   @r   r   r      s        &  D
 D
 D
 D
 D
 D
L   X \  \   8 8 X8 ' ' ' # # # 4 4 X4 \6 6 \6 ; ; X; * * * & & & ' ' X'
 
 
 
> ##O O O Ob
 
 
 M M M Mf B
 B
 B
 B
 B
 B
H2 2 2 2 2 2 2r   r   )loggingoauthlib.commonr   r   oauthlib.oauth2r   r   r   r   r	   r   	getLoggerr   r?   Warningr   Sessionr   r    r   r   <module>r      s     5 5 5 5 5 5 5 5 H H H H H H H H 3 3 3 3 3 3 B B B B B B B B g!!    7   y2 y2 y2 y2 y2H$ y2 y2 y2 y2 y2r   