
    cA4                        d 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
mZmZ ddlmZ 	 ddlmZmZ dZd	Z ej2                  d
ej4                        Z ej2                  d      ZdZ ej<                  d      Zd%dZ	d Zd Zd Z d Z! e"e       e"d      z  Z#d Z$d Z%d Z&d Z'defdZ(d Z)d Z*defdZ+d Z,d&dZ-d Z.d'd Z/ G d! d"e0      Z1 G d# d$      Z2y# e$ r ddlmZmZ Y w xY w)(z|
oauthlib.common
~~~~~~~~~~~~~~

This module provides data structures and utilities common
to all implementations of OAuth.
    N)quoteunquote	urlencode   )	get_debug)SystemRandomrandbits)r   getrandbits>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789z_ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}z&([^&;]*(?:password|token)[^=]*=)[^&;]+z&%[^0-9A-Fa-f]|%[0-9A-Fa-f][^0-9A-Fa-f]zAABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-oauthlibc                     t        | t              r| j                  d      n| } t        | |      } t        | t              r| j                  d      } | S Nutf-8)
isinstancestrencode_quotebytesdecode)ssafes     1/usr/lib/python3/dist-packages/oauthlib/common.pyr   r   +   sE    '3/QAq$A !UHHWH    c                 ^    t        |       } t        | t              r| j                  d      } | S r   )_unquoter   r   r   )r   s    r   r   r   5   s*    A !UHHWHr   c                 t    t        |       }t        |      }t        |t              r|S |j	                  d      S r   )encode_params_utf8
_urlencoder   r   r   )paramsutf8_params
urlencodeds      r   r   r   ?   s7    $V,KK(J*c"  ))r   c                     g }| D ]Z  \  }}|j                  t        |t              r|j                  d      n|t        |t              r|j                  d      n|f       \ |S )ziEnsures that all parameters in a list of 2-element tuples are encoded to
    bytestrings using UTF-8
    r   )appendr   r   r   )r   encodedkvs       r   r   r   H   sb     G =1!+As!3AHHW!+As!3AHHW< 	== Nr   c                     g }| D ]Z  \  }}|j                  t        |t              r|j                  d      n|t        |t              r|j                  d      n|f       \ |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   decodedr%   r&   s       r   decode_params_utf8r)   T   sb     G ?1!+Au!5AHHW1!+Au!5AHHW1> 	?? Nr   z=&;:%+~,*@!()/?'$c                     | r4t        |       t        k  s"d}t        |t        |       t        z
  | fz        t        j	                  |       rt        d      t        j                  | 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.Tkeep_blank_values)setr!   
ValueErrorINVALID_HEX_PATTERNsearchurlparse	parse_qslr)   )queryerrorr   s      r   	urldecoder5   c   sv     SZ:-*
 #e*z"95!AABB !!%(@AA >F f%%r   c                 T   t        | t        t        f      r	 t        |       }|S t        | d      rD	 t        |        t        t        | t              r| j                         n|       }t        |      }|S d}|S # t        $ r d}Y |S w xY w# t        $ r d}Y |S t        $ r d}Y |S w xY w)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   r5   r.   hasattrdictlistitemsr)   	TypeError)rawr   s     r   extract_paramsr>      s     #s|$	s^F  M 
j	!	0I C)>#))+CHF'/F M M  	F M	
  	F M  	F M	s(   A9 B 9BBB'
B'&B'c                  R    t        t        t        d            t               z         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_timestamp r   r   generate_noncerC      s!     s8B< #5#7788r   c                  N    t        t        t        j                                     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timerB   r   r   rA   rA      s     s499;  r      c                 b    t               dj                  f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   @   K   | ]  }j                          y wN)choice).0xcharsrands     r   	<genexpr>z!generate_token.<locals>.<genexpr>   s     =!4;;u%=s   )r   joinrange)lengthrO   rP   s    `@r   generate_tokenrU      s%     >D77=uV}===r   c                    dd l }t        j                  j                         }|j                  |t        j                  |j
                        z   d}|j                  |j                         |j                  || d      }t        |d      }|S )Nr   )seconds)scopeexpRS256UTF-8)
jwtdatetimeutcnowrX   	timedelta
expires_inupdateclaimsr   
to_unicode)private_pemrequestr\   nowrb   tokens         r   generate_signed_tokenrh      sw    



"
"
$C X''0B0BCCF
 MM'..!JJv{G4Eug&ELr   c                 4    dd l }|j                  || dg      S )Nr   rZ   )
algorithms)r\   r   )
public_pemrg   r\   s      r   verify_signed_tokenrl      s    ::eZWI:>>r   c                     t        | |      S )zGenerates an OAuth client_id

    OAuth 2 specify the format of client_id in
    https://tools.ietf.org/html/rfc6749#appendix-A.
    )rU   )rT   rO   s     r   generate_client_idrn      s     &%((r   c                     t        |t              r|j                         }t        j                  | d      }|j                  |       t        |      S )z)Extend a query with a list of two-tuples.Tr+   )r   r9   r;   r1   r2   extendr   )r3   r   queryparamss      r   add_params_to_qsrr      sB    &$$$UdCKv[!!r   c                     t        j                   |       \  }}}}}}|rt        ||      }nt        ||      }t        j                  ||||||f      S )z5Add a list of two-tuples to the uri query components.)r1   rr   
urlunparse)	urir   fragmentschnetpathparr3   fras	            r   add_params_to_urir|      sX    &.&7&7&<#CdCsF+ /S$UC@AAr   c                     t        |       t        |      k7  ryd}t        | |      D ]  \  }}|t        |      t        |      z  z  }! |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resultrN   ys        r   safe_string_equalsr      sU     1vQFAq	 "1#a&3q6/!"Q;r   c           	      x   t        | t              r| S t        | t              rt        |       S t        | d      rR	 t	        |        t        | d      r| j                         } | D ci c]  \  }}t        |      t        |       c}}S | S c c}}w # t        $ r Y | S t        $ r fd| D        cY S w xY w)z:Convert a number of different types of objects to unicode.)encodingr7   r;   c              3   6   K   | ]  }t        |        y wrK   rc   )rM   ir   s     r   rQ   zto_unicode.<locals>.<genexpr>  s     :Jq(+:s   )	r   r   r   r8   r9   r;   rc   r<   r.   )datar   r%   r&   s    `  r   rc   rc     s    $$4(++tZ 	WJ tW%zz|QUVAJq(+Z8-DDVVK W  	 K  	;:T::	;s   B *!B	B9#B98B9c                   X     e Zd ZdZi Zd Zd Z fdZ fdZd	dZ	 fdZ
 fdZ xZS )
CaseInsensitiveDictz3Basic case insensitive dict with strings only keys.c                 t    |D ci c]  }|j                         | c}| _        |D ]
  }||   | |<    y c c}w rK   lowerproxy)selfr   r%   s      r   __init__zCaseInsensitiveDict.__init__-  s?    ,01qaggil1
 	A1gDG	 2s   5c                 :    |j                         | j                  v S rK   r   )r   r%   s     r   __contains__z CaseInsensitiveDict.__contains__2  s    wwyDJJ&&r   c                     | j                   |j                            }t        |   |       | j                   |j                         = y rK   )r   r   super__delitem__r   r%   key	__class__s      r   r   zCaseInsensitiveDict.__delitem__5  s6    jj#C JJqwwy!r   c                 \    | j                   |j                            }t        |   |      S rK   )r   r   r   __getitem__r   s      r   r   zCaseInsensitiveDict.__getitem__:  s'    jj#w"3''r   c                     || v r| |   S |S rK   rB   )r   r%   defaults      r   getzCaseInsensitiveDict.get>  s    t)tAw00r   c                 `    t         |   ||       || j                  |j                         <   y rK   )r   __setitem__r   r   )r   r%   r&   r   s      r   r   zCaseInsensitiveDict.__setitem__A  s&    Aq! !

1779r   c                 ~    t        |   |i | t        |i |D ]  }|| j                  |j	                         <   ! y rK   )r   ra   r9   r   r   )r   argskwargsr%   r   s       r   ra   zCaseInsensitiveDict.updateE  sA    ''t&v& 	&A$%DJJqwwy!	&r   rK   )__name__
__module____qualname____doc__r   r   r   r   r   r   r   ra   __classcell__)r   s   @r   r   r   '  s3    =E
'"
(1"& &r   r   c                   X    e Zd ZdZ	 	 d	dZd Zd Zed        Zed        Z	ed        Z
y)
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.
    Nc                 H   fd} ||      | _          ||      | _        t         ||xs i             | _         ||      | _        t        | j                        | _        g | _        i | _        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d dd d d d d d d d d d d d d d d| _	        | j                  j                  t        t        | j                                     | j                  j                  t        | j                  xs g              y )Nc                 $    rt        |       S | S rK   r   )rN   r   s    r   <lambda>z"Request.__init__.<locals>.<lambda>]  s    h:a2 A r   access_tokenclient	client_idclient_secretcodecode_challengecode_challenge_methodcode_verifierextra_credentials
grant_typeredirect_urirefresh_tokenrequest_tokenresponse_typerX   scopesstate)rg   usertoken_type_hintresponse_modenoncedisplaypromptrb   max_age
ui_localesid_token_hint
login_hint
acr_values)ru   http_methodr   headersbodyr>   decoded_bodyoauth_paramsvalidator_log_paramsra   r9   r5   	uri_query)r   ru   r   r   r   r   r   s        ` r   r   zRequest.__init__Z  s    F#;!+.*6'-R+@A4L	*4995!
D!
d!
 !
 T	!

 D!
 d!
 $T!
 T!
  !
 $!
 D!
 T!
 T!
 T!
 T!
  d!!
" T#!
$ # "!A!
D 	D4>>!:;<D!2!2!8b9:r   c                 R    || j                   v r| j                   |   S t        |      rK   )r   AttributeError)r   names     r   __getattr__zRequest.__getattr__  s(    4<<<<%% &&r   c                    t               sy| j                  }| j                  j                         }|rt        j                  dt        |            }d|v rd|d<   dj                  | j                  | j                  ||      S )Nz<oauthlib.Request SANITIZED>z<SANITIZED>Authorizationz<SANITIZED>zF<oauthlib.Request url="{}", http_method="{}", headers="{}", body="{}">)
r   r   r   copySANITIZE_PATTERNsubr   formatru   r   )r   r   r   s      r   __repr__zRequest.__repr__  sv    {1yy,,##%#''TCDg%'4GO$W^^HHd&&7 	7r   c                 T    t        j                   | j                        j                  S rK   )r1   ru   r3   r   s    r   r   zRequest.uri_query  s      *000r   c                 b    | j                   sg S t        j                  | j                   dd      S )NT)r,   strict_parsing)r   r1   r2   r   s    r   uri_query_paramszRequest.uri_query_params  s,    ~~I!!$..D157 	7r   c                    t        j                  t              }d | j                  xs g | j                  z   D        }|D ]  }||xx   dz  cc<    |j                         D cg c]  \  }}|dkD  s| c}}S c c}}w )Nc              3   &   K   | ]	  }|d      yw)r   NrB   )rM   ps     r   rQ   z+Request.duplicate_params.<locals>.<genexpr>  s      P aD Ps   r   )collectionsdefaultdictrE   r   r   r;   )r   	seen_keysall_keysr%   cs        r   duplicate_paramszRequest.duplicate_params  s{    ++C0	P"//529N9NNP 	AaLAL	'oo/9da1q5999s   %A;3A;)GETNNr   )r   r   r   r   r   r   r   propertyr   r   r   rB   r   r   r   r   K  s]     CG!0;d'
7 1 1 7 7 : :r   r   )   /)F)r[   )3r   r   r]   loggingrerF   urllib.parseparser1   r   r   r   r   r   r   rI   r   secretsr   r	   ImportErrorrandomr
   UNICODE_ASCII_CHARACTER_SETCLIENT_ID_CHARACTER_SETcompile
IGNORECASEr   r/   always_safe	getLoggerlogr   r)   r-   r!   r5   r>   rC   rA   rU   rh   rl   rn   rr   r|   r   rc   r9   r   r   rB   r   r   <module>r      s<      	    =. , N  2::GW  bjj!JK " g
#*		 $8 99
&B:9	! $? 	>$? !(? )"B$2!&$ !&He: e:k	  =<<=s   C   C0/C0