o
    bA                     @   s   d dl mZ d dlmZ d dlmZ ddlmZmZm	Z	m
Z
 ddlmZ ddlmZ ddlmZmZ d	d
dZG dd deZdd ZdS )    )generate_token)
url_decode)
text_types   )prepare_grant_uriprepare_token_request!parse_authorization_code_responseparse_implicit_response)prepare_revoke_token_request)create_s256_code_challenge)	TokenAuth
ClientAuthzapplication/jsonz/application/x-www-form-urlencoded;charset=UTF-8)AcceptzContent-Typec                   @   s
  e Zd ZdZeZeZdZg Z						d.ddZ
dd Zd	d
 Zedd Zejdd Zd/ddZ		d0ddZ		d1ddZd2ddZ		d3ddZ		d3ddZ		d4ddZ		d4ddZ		d4d d!Zd5d"d#Zd$d% Zd&d' Zd(d) Zd*d+ Zed,d- ZdS )6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 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.
    )Zresponse_modenoncepromptZ
login_hintNheaderc                 K   s   || _ || _|| _|d u r|rd}nd}|| _|d u r"|r d}nd}|| _|| _|| _|| _| |	|
| | _	|| _
|dd }|rEtd|| _t t t t t d| _i | _d S )NZ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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)selfr   r   r   r   r   r   r    r!   tokenZtoken_placementr$   r'   r    r-   T/var/www/secure340b-portal/env/lib/python3.10/site-packages/authlib/oauth2/client.py__init__1   s:   
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)r+   authr-   r-   r.   register_client_auth_methoda   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)r0   r   r*   client_auth_classr   r   )r+   r5   r-   r-   r.   client_authk   s   
zOAuth2Client.client_authc                 C   s   | j jS N)r#   r,   )r+   r-   r-   r.   r,   t   s   zOAuth2Client.tokenc                 C   s   | j | d S r8   )r#   Z	set_token)r+   r,   r-   r-   r.   r,   x      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   ZS256Zcode_challenger!   )r   r:   state)r   r'   getr%   r    r   r!   r   EXTRA_AUTHORIZE_PARAMSr   r   )r+   urlr<   Zcode_verifierkwargsr:   kurir-   r-   r.   create_authorization_url|   s0   




z%OAuth2Client.create_authorization_url POSTc                 K   s   | dd}|rd|v r| ||dS | |}	|r1d|v r1d}t||dd}
|
d |d< |du r;| jd	}| j||fi |}|du rO| | j}|du rUt	}|du r_| 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#r<   zcode=authorization_code)r<   r;   
grant_typeZtoken_endpoint)bodyr3   methodheaders)r%   token_from_fragmentr=   _extract_session_request_paramsr   r'   _prepare_token_endpoint_bodyr7   r   DEFAULT_HEADERS_fetch_token)r+   r?   rJ   rK   rL   r3   rI   r@   rF   session_kwargsparamsr-   r-   r.   fetch_token   s8   
zOAuth2Client.fetch_tokenc           	      K   s   |dkrd|v rd ||g}nd ||g}d}|d u rt}| jj||f|||d|}| jd D ]}||}q3| | S )NGET?&rD   datarL   r3   r   )joinrP   r   requestr)   parse_response_tokenjson)	r+   r?   rJ   rL   r3   rK   r@   resphookr-   r-   r.   rQ      s"   
zOAuth2Client._fetch_tokenc                 C   s   t ||}| |S r8   )r	   r\   )r+   rF   r<   r,   r-   r-   r.   rM      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}| jd D ]}||||\}}}q/|du rE| | 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`   rJ   rL   r3   )
rN   r,   r=   r   r   rP   r)   r7   r   _refresh_token)	r+   r?   r`   rJ   r3   rL   r@   rR   r_   r-   r-   r.   r`      s2   

zOAuth2Client.refresh_tokenc           
      K   s|   | j j|ftt|||d|}| jd D ]}||}q| | }	d|	vr.|| jd< t| j	r;| j	| j|d | jS )NrX   r   r`   )r`   )
r   postdictr   r)   r\   r]   r,   callabler$   )
r+   r?   r`   rJ   rL   r3   r@   r^   r_   r,   r-   r-   r.   ra   
  s    


zOAuth2Client._refresh_tokenc                 K       | 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   r,   token_type_hintrJ   r3   rL   _handle_token_hintr+   r?   r,   rg   rJ   r3   rL   r@   r-   r-   r.   revoke_token     zOAuth2Client.revoke_tokenc                 K   re   )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   rf   rh   rj   r-   r-   r.   introspect_token1  rl   zOAuth2Client.introspect_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 )Nr`   Zaccess_tokenrD   )r3   rL   )r,   r=   r
   r)   r7   r   rN   
_http_post)
r+   r_   r?   r,   rg   rJ   r3   rL   r@   rR   r-   r-   r.   ri   F  s&   
zOAuth2Client._handle_token_hintc                 K   s$   | j j|ftt|||d|S )NrX   )r   rb   rc   r   )r+   r?   rJ   r3   rL   r@   r-   r-   r.   rn   [  s   
zOAuth2Client._http_postc                 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.
        Zprotected_requestNzHook type %s is not in %s.)r#   hooksaddr)   r&   )r+   Z	hook_typer_   r-   r-   r.   register_compliance_hook`  s   
z%OAuth2Client.register_compliance_hookc                 C   s8   d|vr
|| _ | j S |d }|d|}| || d S )Nerrorerror_description)r,   r=   handle_error)r+   r,   rr   descriptionr-   r-   r.   r\   u  s   z!OAuth2Client.parse_response_tokenc                 K   sf   |d u rt |}|dkrd|vr| j|d< t||fi |S d|vr*| jr*| j|d< t||fi |S )NrH   r    r   )_guess_grant_typer    r   r   )r+   rJ   rI   r@   r-   r-   r.   rO   ~  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%   )r+   r@   rvrA   r-   r-   r.   rN     s   
z,OAuth2Client._extract_session_request_paramsc                 C   s   t d| |)Nz{}: {})r&   format)Z
error_typers   r-   r-   r.   rt     r9   zOAuth2Client.handle_error)
NNNNNNNNr   N)NN)NrD   rE   NNN)rD   NNrE   r8   )NrD   NN)NNNNN)NNN) __name__
__module____qualname____doc__r   r6   r   r"   r>   rw   r/   r4   r7   propertyr,   setterrC   rT   rQ   rM   r`   ra   rk   rm   ri   rn   rq   r\   rO   rN   staticmethodrt   r-   r-   r-   r.   r      s`    
0
	


!
3


"




	r   c                 C   s0   d| v rd}|S d| v rd| v rd}|S d}|S )Nr;   rH   usernamepasswordZclient_credentialsr-   )r@   rI   r-   r-   r.   rv     s   rv   N)Zauthlib.common.securityr   Zauthlib.common.urlsr   Zauthlib.common.encodingr   Zrfc6749.parametersr   r   r   r	   Zrfc7009r
   Zrfc7636r   r3   r   r   rP   objectr   rv   r-   r-   r-   r.   <module>   s       