o
    ^[2hI                     @   s   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 dZd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                   @   s8  e Zd ZdZeZeZeZ	dZ
g Z												d1ddZdd	 Zd
d Zedd Zejdd Zd2ddZ							d3ddZd4ddZ	d5ddZd4ddZ					d6ddZ					d6ddZdd  Zd!d" Z	d7d#d$Z	d8d%d&Z					d6d'd(Zd)d* Zd+d, Zd9d-d.Z d/d0 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                 K   s   || _ || _|| _|| _|d u r|rd}nd}|| _|d u r%|r#d}nd}|| _|| _|| _|	| _| 	|
|| | _
|| _|dd }|rHt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)   r0   r,   r    r4   f/home/skpark/git/infrasmart_work/infrasmart/venv/lib/python3.10/site-packages/authlib/oauth2/client.py__init__5   sB   
zOAuth2Client.__init__c                 C   s0   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tupler/   name)r1   authr4   r4   r5   register_client_auth_methodu   s   
z(OAuth2Client.register_client_auth_methodc                 C   s2   t |tr|| jv r| j| }| j| j| j|dS )N)r   r    auth_method)r7   strr/   client_auth_classr   r    )r1   r<   r4   r4   r5   client_auth   s   
zOAuth2Client.client_authc                 C   s   | j jS N)r(   r2   r1   r4   r4   r5   r2      s   zOAuth2Client.tokenc                 C   s   | j | d S r@   )r(   	set_token)r1   r2   r4   r4   r5   r2      s   c                 K   s   |du r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rQ|| jv rQ| j| ||< q?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   rC   r!   )r   r,   getr*   r%   r$   r&   r   EXTRA_AUTHORIZE_PARAMSr
   r   )r1   urlr!   code_verifierkwargsrC   kurir4   r4   r5   create_authorization_url   s8   





z%OAuth2Client.create_authorization_url POSTc                 K   s   |p| j }|dd}	|	rd|	v r| |	|S | |}
|	r0d|	v r0d}t|	|d}|d |d< |du r:| jd}|du rGt|}|| jd< | j||fi |}|du r[| 	| j
}|du rat}|du rk| 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!   rD   
grant_typetoken_endpoint)bodyr:   methodheaders)r!   r*   token_from_fragment_extract_session_request_paramsr   r,   rG   _guess_grant_type_prepare_token_endpoint_bodyr?   r"   DEFAULT_HEADERS_fetch_token)r1   rI   rV   rW   rX   r:   rT   r!   rK   rQ   session_kwargsparamsr4   r4   r5   fetch_token   s>   


zOAuth2Client.fetch_tokenc                 C   s4   t ||}d|v r| j|d |dd|| _|S )Nerrorerror_descriptionrb   description)r	   oauth_error_classrG   r2   )r1   rQ   r!   r2   r4   r4   r5   rY      s   
z OAuth2Client.token_from_fragmentc           	      K   s   |  |}|p| jd}d|vr| jr| j|d< td|fd|i|}|du r,t }|du r6| jd}| jd D ]}||||\}}}q;|du rQ| 	| 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$   NrU   r   )rg   rV   rX   r:   )rZ   r2   rG   r$   r   r]   copyr,   r.   r?   r"   _refresh_token)	r1   rI   rg   rV   r:   rX   rK   r_   hookr4   r4   r5   rg     s:   

zOAuth2Client.refresh_tokenc                 C   s   |d u r| j }|j| jdsdS |d}| jd}|r(|r(| j||d dS | jddkrG|d }| j|dd	}| jrE| j||d
 dS d S )N)r0   Trg   rU   rg   rT   client_credentialsaccess_token)rT   )rm   )r2   
is_expiredr0   rG   r,   rg   ra   r)   )r1   r2   rg   rI   rm   	new_tokenr4   r4   r5   ensure_active_token,  s    
z OAuth2Client.ensure_active_tokenc                 K   4   |du r
|  | 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   r2   token_type_hintrV   r:   rX   )r?   r#   _handle_token_hintr1   rI   r2   rs   rV   r:   rX   rK   r4   r4   r5   revoke_token=     zOAuth2Client.revoke_tokenc                 K   rq   )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   rr   )r?   r"   rt   ru   r4   r4   r5   introspect_tokenb  rw   zOAuth2Client.introspect_tokenc                 C   sF   |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addr.   r+   )r1   	hook_typerj   r4   r4   r5   register_compliance_hook  s   
z%OAuth2Client.register_compliance_hookc                 C   sF   |j dkr	|  | }d|v r| j|d |dd|| _| jS )Ni  rb   rc   rd   )status_coderaise_for_statusjsonrf   rG   r2   )r1   respr2   r4   r4   r5   parse_response_token  s   
z!OAuth2Client.parse_response_tokenc           	      K   s   |  dkr| jj|ftt|||d|}n!d|v r%d||g}nd||g}| jj||f||d|}| jd D ]}||}q?| |S )NrP   datarX   r:   ?&)rX   r:   r   )	upperr   postdictr   joinrequestr.   r   )	r1   rI   rV   rX   r:   rW   rK   r   rj   r4   r4   r5   r^     s*   

zOAuth2Client._fetch_tokenc           
      K   sn   | j |f|||d|}| jd D ]}||}q| |}	d|	vr'|| jd< t| jr4| j| j|d | jS )N)rV   r:   rX   r   rg   rk   )
_http_postr.   r   r2   callabler)   )
r1   rI   rg   rV   rX   r:   rK   r   rj   r2   r4   r4   r5   ri     s   



zOAuth2Client._refresh_tokenc                 K   s   |d u r| j r| j dp| j d}|d u rd}t||||\}}| j| D ]}	|	|||\}}}q'|d u r=| | j}| |}
| j||f||d|
S )Nrg   rm   rO   )r:   rX   )r2   rG   r   r.   r?   r#   rZ   r   )r1   rj   rI   r2   rs   rV   r:   rX   rK   r.   r_   r4   r4   r5   rt     s   
zOAuth2Client._handle_token_hintc                 K   sV   |dkrd|vr| j |d< t||fi |S d|vr"| jr"| j|d< t||fi |S )NrS   r%   r$   )r%   r   r$   )r1   rV   rT   rK   r4   r4   r5   r\     s   

z)OAuth2Client._prepare_token_endpoint_bodyc                 C   s*   i }| j D ]}||v r||||< q|S )zDExtract parameters for session object from the passing ``**kwargs``.)SESSION_REQUEST_PARAMSr*   )r1   rK   rvrL   r4   r4   r5   rZ     s   
z,OAuth2Client._extract_session_request_paramsc                 K   s$   | j j|ftt|||d|S )Nr   )r   r   r   r   )r1   rI   rV   r:   rX   rK   r4   r4   r5   r     s   zOAuth2Client._http_postc                 C   s   | ` d S r@   )r   rA   r4   r4   r5   __del__  s   zOAuth2Client.__del__)NNNNNNNNNr   Nr   )NN)NrO   rP   NNNNr@   )NNrO   NN)NNNNN)rO   NNrP   )NrO   NN)NNN)"__name__
__module____qualname____doc__r   r>   r   r'   r   rf   rH   r   r6   r;   r?   propertyr2   setterrN   ra   rY   rg   rp   rv   rx   r}   r   r^   ri   rt   r\   rZ   r   r   r4   r4   r4   r5   r      s    
@
	


+

@


*
(
%




r   c                 C   s0   d| v rd}|S d| v rd| v rd}|S d}|S )NrD   rS   usernamepasswordrl   r4   )rK   rT   r4   r4   r5   r[     s   r[   N)authlib.common.securityr   authlib.common.urlsr   r:   r   r   baser   rfc6749.parametersr   r	   r
   r   rfc7009r   rfc7636r   r]   r   r[   r4   r4   r4   r5   <module>   s&       w