o
    ~j6h-                     @   s   d 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dd	Z	d
d Z
dd Zdd Z	dddZ			dddZdS )a  A module that provides functions for handling rapt authentication.

Reauth is a process of obtaining additional authentication (such as password,
security token, etc.) while refreshing OAuth 2.0 credentials for a user.

Credentials that use the Reauth flow must have the reauth scope,
``https://www.googleapis.com/auth/accounts.reauth``.

This module provides a high-level function for executing the Reauth process,
:func:`refresh_grant`, and lower-level helpers for doing the individual
steps of the reauth process.

Those steps are:

1. Obtaining a list of challenges from the reauth server.
2. Running through each challenge and sending the result back to the reauth
   server.
3. Refreshing the access token using the returned rapt token.
    N)
exceptions)_client)_client_async)
challenges)reauthc                    s6   d|i}|r||d< t j| tjd ||ddI dH S )a  Does initial request to reauth API to get the challenges.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests. This must be an aiohttp request.
        supported_challenge_types (Sequence[str]): list of challenge names
            supported by the manager.
        access_token (str): Access token with reauth scopes.
        requested_scopes (Optional(Sequence[str])): Authorized scopes for the credentials.

    Returns:
        dict: The response from the reauth API.
    supportedChallengeTypes oauthScopesForDomainPolicyLookupz:startTaccess_tokenuse_jsonN)r   _token_endpoint_requestr   _REAUTH_API)requestsupported_challenge_typesr
   requested_scopesbody r   j/var/www/html/chefvision.cloud.itp360.com/venv/lib/python3.10/site-packages/google/oauth2/_reauth_async.py_get_challenges,   s   r   c                    s6   ||d|d}t j| tjd| ||ddI dH S )az  Attempt to refresh access token by sending next challenge result.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests. This must be an aiohttp request.
        session_id (str): session id returned by the initial reauth call.
        challenge_id (str): challenge id returned by the initial reauth call.
        client_input: dict with a challenge-specific client input. For example:
            ``{'credential': password}`` for password challenge.
        access_token (str): Access token with reauth scopes.

    Returns:
        dict: The response from the reauth API.
    RESPOND)	sessionIdchallengeIdactionproposalResponsez/{}:continueTr	   N)r   r   r   r   format)r   
session_idchallenge_idclient_inputr
   r   r   r   r   _send_challenge_resultI   s   r   c                    s   | d D ]N}|d dkrqt j|d d}|s,td|d dtt j |j	s9td|d |
|}|sC dS t|| d	 |d
 ||I dH   S dS )a  Get the next challenge from msg and run it.

    Args:
        msg (dict): Reauth API response body (either from the initial request to
            https://reauth.googleapis.com/v2/sessions:start or from sending the
            previous challenge response to
            https://reauth.googleapis.com/v2/sessions/id:continue)
        request (google.auth.transport.Request): A callable used to make
            HTTP requests. This must be an aiohttp request.
        access_token (str): reauth access token

    Returns:
        dict: The response from the reauth API.

    Raises:
        google.auth.exceptions.ReauthError: if reauth failed.
    r   statusREADYchallengeTypeNz4Unsupported challenge type {0}. Supported types: {1},z%Challenge {0} is not locally eligibler   r   )r   AVAILABLE_CHALLENGESgetr   ReauthFailErrorr   joinlistkeysis_locally_eligibleobtain_challenge_inputr   )msgr   r
   	challengecr   r   r   r   _run_next_challengej   s:   
r.   c                    s   t | ttj ||I dH }|d tjkr|d S tdtjD ]9}|d tj	ks;|d tj
ks;td|d t sDtdt|| |I dH }|d tjkrZ|d   S q!td)a  Given an http request method and reauth access token, get rapt token.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests. This must be an aiohttp request.
        access_token (str): reauth access token
        requested_scopes (Sequence[str]): scopes required by the client application

    Returns:
        str: The rapt token.

    Raises:
        google.auth.exceptions.ReauthError: if reauth failed
    Nr   encodedProofOfReauthTokenr   z6Reauthentication challenge failed due to API error: {}z_Reauthentication challenge could not be answered because you are not in an interactive session.zFailed to obtain rapt token.)r   r'   r   r#   r(   r   _AUTHENTICATEDrangeRUN_CHALLENGE_RETRY_LIMIT_CHALLENGE_REQUIRED_CHALLENGE_PENDINGr   r%   r   is_interactiver.   )r   r
   r   r+   _r   r   r   _obtain_rapt   s4   

r7   c           	         sN   t jd tj| ||||tjgdI dH \}}}}t| ||dI dH }|S )a  Given an http request method and refresh_token, get rapt token.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests. This must be an aiohttp request.
        client_id (str): client id to get access token for reauth scope.
        client_secret (str): client secret for the client_id
        refresh_token (str): refresh token to refresh access token
        token_uri (str): uri to refresh access token
        scopes (Optional(Sequence[str])): scopes required by the client application

    Returns:
        str: The rapt token.
    Raises:
        google.auth.exceptions.RefreshError: If reauth failed.
    zReauthentication required.
)r   	client_idclient_secretrefresh_token	token_uriscopesN)r   )sysstderrwriter   refresh_grantr   _REAUTH_SCOPEr7   )	r   r8   r9   r:   r;   r<   r
   r6   
rapt_tokenr   r   r   get_rapt_token   s   
rC   Fc                    s   t j|||d}|rd||d< |r||d< t| ||I dH \}	}
}|	sd|
dtjkrd|
dtjks?|
dtj	krd|sFt
dt| |||||d	I dH }||d< t| ||I dH \}	}
}|	slt |
| t |
|}||f S )
av  Implements the reauthentication flow.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests. This must be an aiohttp request.
        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 rapt token for reauth.
        enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow
            should be used. The default value is False. This option is for
            gcloud only, other users should use the default value.

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

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.
    )
grant_typer8   r9   r:    scoperaptNerrorerror_subtypezaReauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate.)r<   )r   _REFRESH_GRANT_TYPEr&   r    _token_endpoint_request_no_throwr$   r   _REAUTH_NEEDED_ERROR!_REAUTH_NEEDED_ERROR_INVALID_RAPT"_REAUTH_NEEDED_ERROR_RAPT_REQUIREDr   RefreshErrorrC   _handle_error_response_handle_refresh_grant_response)r   r;   r:   r8   r9   r<   rB   enable_reauth_refreshr   response_status_okresponse_dataretryable_errorrefresh_responser   r   r   r@      sV   (
r@   )N)NNF)__doc__r=   google.authr   google.oauth2r   r   r   r   r   r   r.   r7   rC   r@   r   r   r   r   <module>   s$   
!14
+