o
    ˷e2                     @   s   d Z ddlZddlZddl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Zd	Zd
ZdZdd Zdd Z	dddZ	dddZdd Zdd Zdd Z		dddZdS )a  OAuth 2.0 client.

This is a client for interacting with an OAuth 2.0 authorization server's
token endpoint.

For more information about the token endpoint, see
`Section 3.1 of rfc6749`_

.. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2
    N)http_client)urllib)_helpers)
exceptions)jwtz!application/x-www-form-urlencodedzapplication/jsonz+urn:ietf:params:oauth:grant-type:jwt-bearerrefresh_tokenc              	   C   s^   t | tjrt| zd| d | d}W n ttfy(   t	
| }Y nw t|| )zTranslates an error response into an exception.

    Args:
        response_data (Mapping | str): The decoded response data.

    Raises:
        google.auth.exceptions.RefreshError: The errors contained in response_data.
    z{}: {}errorerror_description)
isinstancesixstring_typesr   RefreshErrorformatgetKeyError
ValueErrorjsondumps)response_dataerror_details r   L/var/www/ideatree/venv/lib/python3.10/site-packages/google/oauth2/_client.py_handle_error_response+   s   	
r   c                 C   s,   |  dd}|durt tj|d S dS )zParses the expiry field from a response into a datetime.

    Args:
        response_data (Mapping): The JSON-parsed response data.

    Returns:
        Optional[datetime]: The expiration or ``None`` if no expiration was
            specified.
    
expires_inN)seconds)r   r   utcnowdatetime	timedelta)r   r   r   r   r   _parse_expiryA   s   
r   Fc                 K   s(  |rdt i}t|d}ndti}tj|d}|r%d||d< d}	 | dd|||d|}t	|j
d	r@|j
dn|j
}	|jtjkrSt|	}
	 d|
fS z2t|	}
|
d
p_d}|
dpfd}tdd ||fD r||dk r|d7 }W q'W d|
fS W d|
fS  ty   |	}
Y d|
fS w )a  Makes a request to the OAuth 2.0 authorization server's token endpoint.
    This function doesn't throw on response errors.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        body (Mapping[str, str]): The parameters to send in the request body.
        access_token (Optional(str)): The access token needed to make the request.
        use_json (Optional(bool)): Use urlencoded format or json format for the
            content type. The default value is False.
        kwargs: Additional arguments passed on to the request method. The
            kwargs will be passed to `requests.request` method, see:
            https://docs.python-requests.org/en/latest/api/#requests.request.
            For example, you can use `cert=("cert_pem_path", "key_pem_path")`
            to set up client side SSL certificate, and use
            `verify="ca_bundle_path"` to set up the CA certificates for sever
            side SSL certificate verification.

    Returns:
        Tuple(bool, Mapping[str, str]): A boolean indicating if the request is
            successful, and a mapping for the JSON-decoded response data.
    zContent-Typezutf-8z	Bearer {}Authorizationr   TPOST)methodurlheadersbodydecoder	    r   c                 s   s    | ]}|d kV  qdS )internal_failureNr   ).0er   r   r   	<genexpr>   s    z3_token_endpoint_request_no_throw.<locals>.<genexpr>   FNr   )_JSON_CONTENT_TYPEr   r   encode_URLENCODED_CONTENT_TYPEr   parse	urlencoder   hasattrdatar%   statusr   OKloadsr   anyr   )request	token_urir$   access_tokenuse_jsonkwargsr#   retryresponseresponse_bodyr   
error_desc
error_coder   r   r    _token_endpoint_request_no_throwS   sN   


rA   c                 K   s.   t | ||f||d|\}}|st| |S )a  Makes a request to the OAuth 2.0 authorization server's token endpoint.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        body (Mapping[str, str]): The parameters to send in the request body.
        access_token (Optional(str)): The access token needed to make the request.
        use_json (Optional(bool)): Use urlencoded format or json format for the
            content type. The default value is False.
        kwargs: Additional arguments passed on to the request method. The
            kwargs will be passed to `requests.request` method, see:
            https://docs.python-requests.org/en/latest/api/#requests.request.
            For example, you can use `cert=("cert_pem_path", "key_pem_path")`
            to set up client side SSL certificate, and use
            `verify="ca_bundle_path"` to set up the CA certificates for sever
            side SSL certificate verification.

    Returns:
        Mapping[str, str]: The JSON-decoded response data.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.
    )r9   r:   )rA   r   )r7   r8   r$   r9   r:   r;   response_status_okr   r   r   r   _token_endpoint_request   s   
rC   c           	   
   C   sr   |t d}t| ||}z|d }W n ty/ } ztd|}t|| W Y d}~nd}~ww t|}|||fS )a  Implements the JWT Profile for OAuth 2.0 Authorization Grants.

    For more details, see `rfc7523 section 4`_.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        assertion (str): The OAuth 2.0 assertion.

    Returns:
        Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
            expiration, and additional data returned by the token endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.

    .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
    	assertion
grant_typer9   No access token in response.N)_JWT_GRANT_TYPErC   r   r   r   r   
raise_fromr   )	r7   r8   rE   r$   r   r9   
caught_excnew_excexpiryr   r   r   	jwt_grant   s   

rM   c           
   
   C   s   |t d}t| ||}z|d }W n ty/ } ztd|}t|| W Y d}~nd}~ww tj|dd}t	j	
|d }	||	|fS )a  Implements the JWT Profile for OAuth 2.0 Authorization Grants, but
    requests an OpenID Connect ID Token instead of an access token.

    This is a variant on the standard JWT Profile that is currently unique
    to Google. This was added for the benefit of authenticating to services
    that require ID Tokens instead of access tokens or JWT bearer tokens.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorization server's token endpoint
            URI.
        assertion (str): JWT token signed by a service account. The token's
            payload must include a ``target_audience`` claim.

    Returns:
        Tuple[str, Optional[datetime], Mapping[str, str]]:
            The (encoded) Open ID Connect ID Token, expiration, and additional
            data returned by the endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.
    rD   id_tokenzNo ID token in response.NF)verifyexp)rH   rC   r   r   r   r   rI   r   r%   r   utcfromtimestamp)
r7   r8   rE   r$   r   rN   rJ   rK   payloadrL   r   r   r   id_token_jwt_grant   s   

rS   c              
   C   sj   z| d }W n t y$ } ztd| }t|| W Y d}~nd}~ww | d|}t| }|||| fS )aW  Extract tokens from refresh grant response.

    Args:
        response_data (Mapping[str, str]): Refresh grant response data.
        refresh_token (str): Current refresh token.

    Returns:
        Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access token,
            refresh token, expiration, and additional data returned by the token
            endpoint. If response_data doesn't have refresh token, then the current
            refresh token will be returned.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.
    r9   rG   Nr   )r   r   r   r   rI   r   r   )r   r   r9   rJ   rK   rL   r   r   r   _handle_refresh_grant_response  s   rT   c           	      C   sB   t |||d}|rd||d< |r||d< t| ||}t||S )a  Implements the OAuth 2.0 refresh token grant.

    For more details, see `rfc678 section 6`_.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        refresh_token (str): The refresh token to use to get a new access
            token.
        client_id (str): The OAuth 2.0 application's client ID.
        client_secret (str): The Oauth 2.0 appliaction's client secret.
        scopes (Optional(Sequence[str])): Scopes to request. If present, all
            scopes must be authorized for the refresh token. Useful if refresh
            token has a wild card scope (e.g.
            'https://www.googleapis.com/auth/any-api').
        rapt_token (Optional(str)): The reauth Proof Token.

    Returns:
        Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access
            token, new or current refresh token, expiration, and additional data
            returned by the token endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.

    .. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
    )rF   	client_idclient_secretr    scoperapt)_REFRESH_GRANT_TYPEjoinrC   rT   )	r7   r8   r   rU   rV   scopes
rapt_tokenr$   r   r   r   r   refresh_grant,  s   (
r^   )NF)NN)__doc__r   r   r   	six.movesr   r   google.authr   r   r   r.   r,   rH   rZ   r   r   rA   rC   rM   rS   rT   r^   r   r   r   r   <module>   s2   
J
%%)#