U
    gs.                     @  s  d dl mZ d dlZd dl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mZmZ ddlmZmZmZ ejrd d	lmZ d
dddgZG dd
 d
ZG dd deZG dd deZG dd deZG dd deZG dd dejZdS )    )annotationsN)	b64encode)parse_http_list   )ProtocolError)CookiesRequestResponse)to_bytesto_strunquote)_HashAuth	BasicAuth
DigestAuth	NetRCAuthc                   @  sH   e Zd ZdZdZdZdddddZddddd	Zdd
dddZdS )r   a  
    Base class for all authentication schemes.

    To implement a custom authentication scheme, subclass `Auth` and override
    the `.auth_flow()` method.

    If the authentication scheme does I/O such as disk access or network calls, or uses
    synchronization primitives such as locks, you should override `.sync_auth_flow()`
    and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized
    implementations that will be used by `Client` and `AsyncClient` respectively.
    Fr   )typing.Generator[Request, Response, None]requestreturnc                 c  s
   |V  dS )a  
        Execute the authentication flow.

        To dispatch a request, `yield` it:

        ```
        yield request
        ```

        The client will `.send()` the response back into the flow generator. You can
        access it like so:

        ```
        response = yield request
        ```

        A `return` (or reaching the end of the generator) will result in the
        client returning the last response obtained from the server.

        You can dispatch as many requests as is necessary.
        N selfr   r   r   //tmp/pip-unpacked-wheel-ql4n0x43/httpx/_auth.py	auth_flow&   s    zAuth.auth_flowc                 c  sb   | j r|  | |}t|}|V }| jr4|  z||}W q  tk
rZ   Y q^Y q X q dS )z
        Execute the authentication flow synchronously.

        By default, this defers to `.auth_flow()`. You should override this method
        when the authentication scheme does I/O and/or uses concurrency primitives.
        N)requires_request_bodyreadr   nextrequires_response_bodysendStopIterationr   r   Zflowresponser   r   r   sync_auth_flow>   s    	
zAuth.sync_auth_flowz(typing.AsyncGenerator[Request, Response]c                 C sn   | j r| I dH  | |}t|}|V }| jr@| I dH  z||}W q& tk
rf   Y qjY q&X q&dS )z
        Execute the authentication flow asynchronously.

        By default, this defers to `.auth_flow()`. You should override this method
        when the authentication scheme does I/O and/or uses concurrency primitives.
        N)r   Zareadr   r   r   r   r    r!   r   r   r   async_auth_flowW   s    	
zAuth.async_auth_flowN)	__name__
__module____qualname____doc__r   r   r   r#   r$   r   r   r   r   r      s   c                   @  s0   e Zd ZdZdddddZddd	d
dZdS )FunctionAuthz
    Allows the 'auth' argument to be passed as a simple callable function,
    that takes the request, and returns a new, modified request.
    z#typing.Callable[[Request], Request]None)funcr   c                 C  s
   || _ d S NZ_func)r   r+   r   r   r   __init__w   s    zFunctionAuth.__init__r   r   r   c                 c  s   |  |V  d S r,   r-   r   r   r   r   r   z   s    zFunctionAuth.auth_flowN)r%   r&   r'   r(   r.   r   r   r   r   r   r)   q   s   r)   c                   @  sD   e Zd ZdZddddddZddd	d
dZddddddZdS )r   zy
    Allows the 'auth' argument to be passed as a (username, password) pair,
    and uses HTTP Basic authentication.
    str | bytesr*   usernamepasswordr   c                 C  s   |  ||| _d S r,   )_build_auth_header_auth_headerr   r1   r2   r   r   r   r.      s    zBasicAuth.__init__r   r   r   c                 c  s   | j |jd< |V  d S )NAuthorization)r4   headersr   r   r   r   r      s    zBasicAuth.auth_flowstrc                 C  s,   d t|t|f}t| }d| S N   :zBasic joinr
   r   decoder   r1   r2   Zuserpasstokenr   r   r   r3      s    zBasicAuth._build_auth_headerNr%   r&   r'   r(   r.   r   r3   r   r   r   r   r   ~   s   c                   @  sD   e Zd ZdZddddddZdd	d
ddZddddddZdS )r   zT
    Use a 'netrc' file to lookup basic auth credentials based on the url host.
    Nz
str | Noner*   )filer   c                 C  s   dd l }| || _d S )Nr   )netrc_netrc_info)r   rA   rB   r   r   r   r.      s    zNetRCAuth.__init__r   r   r   c                 c  sN   | j |jj}|d ks |d s(|V  n"| j|d |d d|jd< |V  d S )N   r   )r1   r2   r6   )rC   authenticatorsurlhostr3   r7   )r   r   Z	auth_infor   r   r   r      s     zNetRCAuth.auth_flowr/   r8   r0   c                 C  s,   d t|t|f}t| }d| S r9   r;   r>   r   r   r   r3      s    zNetRCAuth._build_auth_header)Nr@   r   r   r   r   r      s   c                	   @  s   e Zd ZU ejejejejejejejejdZde	d< ddddddZ
d	d
dddZd	ddddddZd	dddddZddddddZdddddZd d	d d!d"d#Zd$S )%r   )MD5zMD5-SESSSHAzSHA-SESSzSHA-256zSHA-256-SESSzSHA-512zSHA-512-SESSz*dict[str, typing.Callable[[bytes], _Hash]]_ALGORITHM_TO_HASH_FUNCTIONr/   r*   r0   c                 C  s$   t || _t || _d | _d| _d S )Nr   )r
   	_username	_password_last_challenge_nonce_countr5   r   r   r   r.      s    

zDigestAuth.__init__r   r   r   c                 c  s   | j r| || j |jd< |V }|jdks4d|jkr8d S |jdD ]}| drD q`qDd S | |||| _ d| _| || j |jd< |j	rt
|j	j|d |V  d S )Nr6   i  zwww-authenticatezdigest r   r   )rM   r3   r7   status_codeZget_listlower
startswith_parse_challengerN   cookiesr   Zset_cookie_header)r   r   r"   auth_headerr   r   r   r      s*     
 
zDigestAuth.auth_flowr	   r8   _DigestAuthChallenge)r   r"   rU   r   c              
   C  s   | d\}}}| dks ti }t|D ]$}| dd\}	}
t|
||	< q,zh|d  }|d  }|dd}d	|kr|d	  nd
}d|kr|d  nd
}t	|||||dW S  t
k
r } zd}t||d|W 5 d
}~X Y nX d
S )z
        Returns a challenge from a Digest WWW-Authenticate header.
        These take the form of:
        `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`
         digest=r   realmnonce	algorithmrH   opaqueNqop)rZ   r[   r\   r]   r^   z(Malformed Digest WWW-Authenticate headerrO   )	partitionrQ   AssertionErrorr   stripsplitr   encodegetrV   KeyErrorr   )r   r   r"   rU   scheme_fieldsZheader_dictfieldkeyvaluerZ   r[   r\   r]   r^   excmessager   r   r   rS      s,        zDigestAuth._parse_challenge)r   	challenger   c                   sR  | j |j   ddd fdd}d| j|j| jf}|jj}d|j	
 |f}||}d| j }| | j|j}	|  jd7  _||}
|j dr|d|
|j|	f}
| j|j|d	}|d kr|
|j|g}n|
|j||	||g}| j|j|j||d||j
 d
}|jr&|j|d< |rDd|d< ||d< |	|d< d| | S )Nbytes)datar   c                   s    |    S r,   )	hexdigestrc   )rp   Z	hash_funcr   r   rX     s    z-DigestAuth._build_auth_header.<locals>.digestr:   s   %08xr   z-sessrO   )r1   rZ   r[   urir"   r\   r]      authr^   nccnoncezDigest )rJ   r\   upperr<   rK   rZ   rL   rF   raw_pathmethodrc   rN   _get_client_noncer[   rQ   endswith_resolve_qopr^   r]   _get_header_value)r   r   rn   rX   A1pathA2HA2Znc_valuerv   HA1r^   Zdigest_dataZformat_argsr   rr   r   r3      s<    

zDigestAuth._build_auth_headerintro   )nonce_countr[   r   c                 C  sL   t | }||7 }|t  7 }|td7 }t| d d  S )N      )	r8   rc   timectimeosurandomhashlibsha1rq   )r   r   r[   sr   r   r   rz   /  s
    zDigestAuth._get_client_noncezdict[str, bytes])header_fieldsr   c           
      C  sb   d}d}d}d}t | D ]@\}\}}|dkr8|d7 }||krD|n|}	||	|t|7 }q|S )N)r\   r^   ru   z{}="{}"z{}={} r   z, )	enumerateitemsformatr   )
r   r   ZNON_QUOTED_FIELDSZQUOTED_TEMPLATEZNON_QUOTED_TEMPLATEheader_valueiri   rk   templater   r   r   r}   7  s    zDigestAuth._get_header_valuebytes | None)r^   r   r   c                 C  sR   |d krd S t d|}d|kr$dS |dgkr6tdd|d}t||dd S )Ns   , ?rt   s   auth-intz.Digest auth-int support is not yet implementedzUnexpected qop value "z" in digest authrO   )rerb   NotImplementedErrorr   )r   r^   r   Zqopsrm   r   r   r   r|   I  s    
zDigestAuth._resolve_qopN)r%   r&   r'   r   md5r   sha256sha512rJ   __annotations__r.   r   rS   r3   rz   r}   r|   r   r   r   r   r      s    
0c                   @  s6   e Zd ZU ded< ded< ded< ded< ded< d	S )
rV   ro   rZ   r[   r8   r\   r   r]   r^   N)r%   r&   r'   r   r   r   r   r   rV   W  s
   
rV   )
__future__r   r   r   r   r   typingbase64r   urllib.requestr   _exceptionsr   Z_modelsr   r   r	   _utilsr
   r   r   TYPE_CHECKINGr   __all__r   r)   r   r   r   
NamedTuplerV   r   r   r   r   <module>   s(   [ )