U
    I]9                     @   sF  d Z ddlmZ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	Z	ddl
mZ zddlmZ ddlmZ W n, ek
r   ddlmZ ddlmZ Y nX z(dd	lmZ dd
lmZ ddlmZ W n8 ek
r   dd	lmZ dd
lmZ ddlmZ Y nX zddlZW n" ek
r*   ddlmZ Y nX dZdZedejZ edZ!dZ"e#dZ$ej%d dkZ&e&rte'Z(ne)Z(d>ddZdd Zdd Zdd Z*dd Z+e,e"e,dB Z-dd  Z.d!d" Z/d#d$ Z0d%d& Z1d'efd(d)Z2d*d+ Z3d,d- Z4d'efd.d/Z5d0d1 Z6d?d3d4Z7d5d6 Z8d@d8d9Z9G d:d; d;e:Z;G d<d= d=e<Z=dS )Az|
oauthlib.common
~~~~~~~~~~~~~~

This module provides data structures and utilities common
to all implementations of OAuth.
    )absolute_importunicode_literalsN   )	get_debug)randbits)SystemRandom)getrandbits)quote)unquote)	urlencodeZ>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789z_ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}z&([^&;]*(?:password|token)[^=]*=)[^&;]+z&%[^0-9A-Fa-f]|%[0-9A-Fa-f][^0-9A-Fa-f]zAABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-Zoauthlib      /c                 C   s:   t | tr| dn| } t| |} t | tr6| d} | S Nutf-8)
isinstanceunicode_typeencode_quotebytesdecode)sZsafe r   1/usr/lib/python3/dist-packages/oauthlib/common.pyr	   ?   s
    


r	   c                 C   s    t | } t| tr| d} | S r   )_unquoter   r   r   )r   r   r   r   r
   I   s    

r
   c                 C   s,   t | }t|}t|tr|S |dS d S r   )encode_params_utf8
_urlencoder   r   r   )paramsZutf8_params
urlencodedr   r   r   r   S   s
    
r   c                 C   sL   g }| D ]>\}}| t|tr(|dn|t|tr>|dn|f q|S )ziEnsures that all parameters in a list of 2-element tuples are encoded to
    bytestrings using UTF-8
    r   )appendr   r   r   )r   Zencodedkvr   r   r   r   \   s    r   c                 C   sL   g }| D ]>\}}| t|tr(|dn|t|tr>|dn|f q|S )zfEnsures that all parameters in a list of 2-element tuples are decoded to
    unicode using UTF-8.
    r   )r   r   r   r   )r   Zdecodedr   r    r   r   r   decode_params_utf8h   s    r!   z=&;:%+~,*@!()/?'$c                 C   sp   | r,t | tks,d}t|t | t | f t| r>tdtsVt| trV| dn| } t	j
| dd}t|S )a  Decode a query string in x-www-form-urlencoded format into a sequence
    of two-element tuples.

    Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce
    correct formatting of the query string by validation. If validation fails
    a ValueError will be raised. urllib.parse_qsl will only raise errors if
    any of name-value pairs omits the equals sign.
    zError trying to decode a non urlencoded string. Found invalid characters: %s in the string: '%s'. Please ensure the request/response body is x-www-form-urlencoded.z%Invalid hex encoding in query string.r   Tkeep_blank_values)setr   
ValueErrorINVALID_HEX_PATTERNsearchPY3r   r   r   urlparse	parse_qslr!   )queryerrorr   r   r   r   	urldecodew   s    

r-   c                 C   s   t | ttfr6zt| }W q tk
r2   d}Y qX nnt| drzt|  W n. tk
rd   d}Y q tk
rz   d}Y qX tt | tr| 	 n| }t
|}nd}|S )a*  Extract parameters and return them as a list of 2-tuples.

    Will successfully extract parameters from urlencoded query strings,
    dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an
    empty list of parameters. Any other input will result in a return
    value of None.
    N__iter__)r   r   r   r-   r%   hasattrdict	TypeErrorlistitemsr!   )rawr   r   r   r   extract_params   s     


r5   c                   C   s   t t tdt  S )a  Generate pseudorandom nonce that is unlikely to repeat.

    Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.
    Per `section 3.2.1`_ of the MAC Access Authentication spec.

    A random 64-bit number is appended to the epoch timestamp for both
    randomness and to decrease the likelihood of collisions.

    .. _`section 3.2.1`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1
    .. _`section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
    @   )r   r   generate_timestampr   r   r   r   generate_nonce   s    r8   c                   C   s   t tt S )aD  Get seconds since epoch (UTC).

    Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.
    Per `section 3.2.1`_ of the MAC Access Authentication spec.

    .. _`section 3.2.1`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1
    .. _`section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
    )r   inttimer   r   r   r   r7      s    	r7      c                    s$   t  d fddt| D S )aX  Generates a non-guessable OAuth token

    OAuth (1 and 2) does not specify the format of tokens except that they
    should be strings of random characters. Tokens should not be guessable
    and entropy when generating the random characters is important. Which is
    why SystemRandom is used instead of the default random.choice method.
     c                 3   s   | ]}  V  qd S N)Zchoice).0xcharsZrandr   r   	<genexpr>   s     z!generate_token.<locals>.<genexpr>)r   joinrangeZlengthrA   r   r@   r   generate_token   s    rF   c                 C   sT   dd l }tj }|j|tj|jd d}||j ||| d}t	|d}|S )Nr   )Zseconds)scopeZexpRS256UTF-8)
jwtdatetimeZutcnowrG   Z	timedeltaZ
expires_inupdateclaimsr   
to_unicode)Zprivate_pemZrequestrJ   ZnowrM   tokenr   r   r   generate_signed_token   s    

rP   c                 C   s   dd l }|j|| dgdS )Nr   rH   )Z
algorithms)rJ   r   )Z
public_pemrO   rJ   r   r   r   verify_signed_token   s    rQ   c                 C   s
   t | |S )zGenerates an OAuth client_id

    OAuth 2 specify the format of client_id in
    https://tools.ietf.org/html/rfc6749#appendix-A.
    )rF   rE   r   r   r   generate_client_id  s    rR   c                 C   s2   t |tr| }tj| dd}|| t|S )z)Extend a query with a list of two-tuples.Tr"   )r   r0   r3   r)   r*   extendr   )r+   r   Zqueryparamsr   r   r   add_params_to_qs  s
    

rT   Fc           	      C   sF   t  | \}}}}}}|r&t||}n
t||}t ||||||fS )z5Add a list of two-tuples to the uri query components.)r)   rT   Z
urlunparse)	urir   ZfragmentZschZnetpathZparr+   Zfrar   r   r   add_params_to_uri  s
    
rW   c                 C   sH   t | t |krdS d}t| |D ]\}}|t|t|A O }q"|dkS )a   Near-constant time string comparison.

    Used in order to avoid timing attacks on sensitive information such
    as secret keys during request verification (`rootLabs`_).

    .. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/

    Fr   )lenzipord)abresultr?   yr   r   r   safe_string_equals   s    	r_   rI   c                    s   t | tr| S t | tr$t|  dS t| drzt|  W n8 tk
rN   Y nN tk
rr    fdd| D  Y S X t| dr|  } t fdd| D S | S )z:Convert a number of different types of objects to unicode.encodingr.   c                 3   s   | ]}t | V  qd S r=   rN   )r>   ir`   r   r   rB   A  s     zto_unicode.<locals>.<genexpr>r3   c                 3   s&   | ]\}}t | t | fV  qd S r=   rb   )r>   r   r    r`   r   r   rB   F  s     )r   r   r   r/   r0   r1   r%   r3   )datara   r   r`   r   rN   2  s    



rN   c                       sb   e Zd ZdZi Zdd Zdd Z fddZ fdd	ZdddZ	 fddZ
 fddZ  ZS )CaseInsensitiveDictz3Basic case insensitive dict with strings only keys.c                 C   s.   t dd |D | _|D ]}|| | |< qd S )Nc                 s   s   | ]}|  |fV  qd S r=   )lower)r>   r   r   r   r   rB   R  s     z/CaseInsensitiveDict.__init__.<locals>.<genexpr>)r0   proxy)selfrd   r   r   r   r   __init__Q  s    zCaseInsensitiveDict.__init__c                 C   s   |  | jkS r=   )rf   rg   )rh   r   r   r   r   __contains__V  s    z CaseInsensitiveDict.__contains__c                    s.   | j |  }tt| | | j | = d S r=   )rg   rf   superre   __delitem__rh   r   key	__class__r   r   rl   Y  s    zCaseInsensitiveDict.__delitem__c                    s   | j |  }tt| |S r=   )rg   rf   rk   re   __getitem__rm   ro   r   r   rq   ^  s    zCaseInsensitiveDict.__getitem__Nc                 C   s   || kr| | S |S r=   r   )rh   r   defaultr   r   r   getb  s    zCaseInsensitiveDict.getc                    s$   t t| || || j| < d S r=   )rk   re   __setitem__rg   rf   )rh   r   r    ro   r   r   rt   e  s    zCaseInsensitiveDict.__setitem__c                    s4   t t| j|| t||D ]}|| j| < qd S r=   )rk   re   rL   r0   rg   rf   )rh   argskwargsr   ro   r   r   rL   i  s    zCaseInsensitiveDict.update)N)__name__
__module____qualname____doc__rg   ri   rj   rl   rq   rs   rt   rL   __classcell__r   r   ro   r   re   K  s   
re   c                   @   sN   e Zd ZdZdddZdd Zd	d
 Zedd Zedd Z	edd Z
dS )Requesta:  A malleable representation of a signable HTTP request.

    Body argument may contain any data, but parameters will only be decoded if
    they are one of:

    * urlencoded query string
    * dict
    * list of 2-tuples

    Anything else will be treated as raw body data to be passed through
    unmolested.
    GETNr   c                    s    fdd}||| _ ||| _t||p*i | _||| _t| j| _g | _i | _d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d d| _	| j	
tt| j | j	
t| jpg  d S )Nc                    s    rt |  S | S r=   rb   )r?   r`   r   r   <lambda>      z"Request.__init__.<locals>.<lambda>)Zaccess_tokenZclientZ	client_idZclient_secretcodeZcode_challengeZcode_challenge_methodZcode_verifierZextra_credentialsZ
grant_typeZredirect_uriZrefresh_tokenZrequest_tokenZresponse_typerG   ZscopesstaterO   userZtoken_type_hintZresponse_modeZnonceZdisplaypromptrM   Zmax_ageZ
ui_localesZid_token_hintZ
login_hintZ
acr_values)rU   http_methodre   headersbodyr5   decoded_bodyZoauth_paramsZvalidator_log_paramsrL   r0   r-   	uri_query)rh   rU   r   r   r   ra   r   r   r`   r   ri   ~  sR    


"zRequest.__init__c                 C   s    || j kr| j | S t|d S r=   )r   AttributeError)rh   namer   r   r   __getattr__  s    

zRequest.__getattr__c                 C   sR   t  s
dS | j}| j }|r.tdt|}d|kr>d|d< d| j| j||f S )Nz<oauthlib.Request SANITIZED>z<SANITIZED>ZAuthorizationz<SANITIZED>zF<oauthlib.Request url="%s", http_method="%s", headers="%s", body="%s">)	r   r   r   copySANITIZE_PATTERNsubstrrU   r   )rh   r   r   r   r   r   __repr__  s    
   zRequest.__repr__c                 C   s   t  | jjS r=   )r)   rU   r+   rh   r   r   r   r     s    zRequest.uri_queryc                 C   s   | j s
g S tj| j dddS )NT)r#   Zstrict_parsing)r   r)   r*   r   r   r   r   uri_query_params  s
    
zRequest.uri_query_paramsc                 C   sP   t t}dd | jpg | j D }|D ]}||  d7  < q(dd | D S )Nc                 s   s   | ]}|d  V  qdS )r   Nr   )r>   pr   r   r   rB     s   z+Request.duplicate_params.<locals>.<genexpr>r   c                 S   s   g | ]\}}|d kr|qS )r   r   )r>   r   cr   r   r   
<listcomp>  s      z,Request.duplicate_params.<locals>.<listcomp>)collectionsdefaultdictr9   r   r   r3   )rh   Z	seen_keysZall_keysr   r   r   r   duplicate_params  s    
zRequest.duplicate_params)r}   NNr   )rw   rx   ry   rz   ri   r   r   propertyr   r   r   r   r   r   r   r|   o  s     
2

r|   )r   )F)rI   )>rz   Z
__future__r   r   r   rK   Zloggingresysr:   r<   r   Zsecretsr   r   ImportErrorZrandomr   Zurllibr	   r   r
   r   r   r   Zurllib.parser)   parseZUNICODE_ASCII_CHARACTER_SETZCLIENT_ID_CHARACTER_SETcompile
IGNORECASEr   r&   Zalways_safeZ	getLoggerlogversion_infor(   r   r   Zunicoder   r!   r$   r   r-   r5   r8   r7   rF   rP   rQ   rR   rT   rW   r_   rN   r0   re   objectr|   r   r   r   r   <module>   sp   




	1		


$