
    h                        S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
Jr  SSK
Jr  SSKJr  SSKJr  SSKJr  SSKJrJrJrJrJrJrJr   " S	 S
\5      r " S S5      r " S S5      r " S S5      r " S S\5      r  " S S\5      r! " S S\5      r"0 S4S\\#\4   S\#S\#S\\#\4   S\\\#\4      S\$4S jjr%0 S4S\\#\4   S\#S\#S\\#\4   S\\\#\4      S\$4S jjr&S\\#\$4   S\#4S  jr'S!\$S\\#\4   4S" jr(g)#a	  This module contains implementations of various third-party
authentication schemes.

All the classes in this file are class mixins designed to be used with
the `tornado.web.RequestHandler` class.  They are used in two ways:

* On a login handler, use methods such as ``authenticate_redirect()``,
  ``authorize_redirect()``, and ``get_authenticated_user()`` to
  establish the user's identity and store authentication tokens to your
  database and/or cookies.
* In non-login handlers, use methods such as ``facebook_request()``
  or ``twitter_request()`` to use the authentication tokens to make
  requests to the respective services.

They all take slightly different arguments due to the fact all these
services implement authentication and authorization slightly differently.
See the individual service classes below for complete documentation.

Example usage for Google OAuth:

.. testsetup::

    import urllib

.. testcode::

    class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
                                    tornado.auth.GoogleOAuth2Mixin):
        async def get(self):
            # Google requires an exact match for redirect_uri, so it's
            # best to get it from your app configuration instead of from
            # self.request.full_uri().
            redirect_uri = urllib.parse.urljoin(self.application.settings['redirect_base_uri'],
                self.reverse_url('google_oauth'))
            async def get(self):
                if self.get_argument('code', False):
                    access = await self.get_authenticated_user(
                        redirect_uri=redirect_uri,
                        code=self.get_argument('code'))
                    user = await self.oauth2_request(
                        "https://www.googleapis.com/oauth2/v1/userinfo",
                        access_token=access["access_token"])
                    # Save the user and access token. For example:
                    user_cookie = dict(id=user["id"], access_token=access["access_token"])
                    self.set_signed_cookie("user", json.dumps(user_cookie))
                    self.redirect("/")
                else:
                    self.authorize_redirect(
                        redirect_uri=redirect_uri,
                        client_id=self.get_google_oauth_settings()['key'],
                        scope=['profile', 'email'],
                        response_type='code',
                        extra_params={'approval_prompt': 'auto'})

    N)
httpclient)escape)
url_concat)unicode_type)RequestHandler)ListAnyDictcastIterableUnionOptionalc                       \ rS rSrSrg)	AuthErrorZ    N)__name__
__module____qualname____firstlineno____static_attributes__r       _C:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\tornado/auth.pyr   r   Z   s    r   r   c                      \ rS rSrSrS/ SQ4S\\   S\\   SS4S jjr SS	\\	R                     S\\\4   4S
 jjr/ S4S\S\\   S\\   S\\\4   4S jjrS\	R                   S\\\4   4S jrS\	R                  4S jrSrg)OpenIdMixin^   zAbstract implementation of OpenID and Attribute Exchange.

Class attributes:

* ``_OPENID_ENDPOINT``: the identity provider's URI.
N)nameemaillanguageusernamecallback_uriax_attrsreturnc                 
   [        [        U 5      nU=(       d    UR                  R                  nUc   eU R	                  XS9nU R
                  nUR                  US-   [        R                  R                  U5      -   5        g)aH  Redirects to the authentication URL for this service.

After authentication, the service will redirect back to the given
callback URI with additional parameters including ``openid.mode``.

We request the given attributes for the authenticated user by
default (name, email, language, and username). If you don't need
all those attributes for your app, you can request fewer with
the ax_attrs keyword argument.

.. versionchanged:: 6.0

    The ``callback`` argument was removed and this method no
    longer returns an awaitable object. It is now an ordinary
    synchronous function.
N)r"   ?)
r   r   requesturi_openid_args_OPENID_ENDPOINTredirecturllibparse	urlencode)selfr!   r"   handlerargsendpoints         r   authenticate_redirect!OpenIdMixin.authenticate_redirectf   st    * ~t,#:w':':'''   A((C&,,*@*@*FFGr   http_clientc                   #    [        [        U 5      nUR                  R                  R	                  5        VVs0 s H
  u  p4X4S   _M     nnnSUS'   U R
                  nUc  U R                  5       nUR                  US[        R                  R                  U5      S9I Sh  vN nU R                  U5      $ s  snnf  N7f)a  Fetches the authenticated user data upon redirect.

This method should be called by the handler that receives the
redirect from the `authenticate_redirect()` method (which is
often the same as the one that calls it; in that case you would
call `get_authenticated_user` if the ``openid.mode`` parameter
is present and `authenticate_redirect` if it is not).

The result of this method will generally be used to set a cookie.

.. versionchanged:: 6.0

    The ``callback`` argument was removed. Use the returned
    awaitable object instead.
check_authenticationopenid.modeNPOSTmethodbody)r   r   r&   	argumentsitemsr)   get_auth_http_clientfetchr+   r,   r-   _on_authentication_verified)r.   r4   r/   kvr0   urlresps           r   get_authenticated_user"OpenIdMixin.get_authenticated_user   s     $ ~t, ")!:!:!@!@!B
!BAuH!B 	 
 5]##335K &&V\\%;%;D%A ' 
 
 //55

s   8CB9AC#B?$Coauth_scopec                    [        [        U 5      n[        R                  R	                  UR
                  R                  5       U5      nSSSU[        R                  R	                  US5      SS.nU(       a  UR                  SSS.5        [        U5      n/ nS	U;   a#  U1 S
k-  nU/ SQ-  nUR                  SSSS.5        SSSS.nU H  n	X   USU	-   '   UR                  U	5        M      SR                  U5      US'   U(       a;  UR                  SUR
                  R                  R                  S5      S   US.5        U$ )Nz http://specs.openid.net/auth/2.0z2http://specs.openid.net/auth/2.0/identifier_select/checkid_setup)z	openid.nsopenid.claimed_idzopenid.identityzopenid.return_tozopenid.realmr8   http://openid.net/srv/ax/1.0fetch_request)zopenid.ns.axzopenid.ax.moder   >   r   fullnamelastname	firstname)rQ   rO   rP   $http://axschema.org/namePerson/firsthttp://axschema.org/namePerson#http://axschema.org/namePerson/last)zopenid.ax.type.firstnamezopenid.ax.type.fullnamezopenid.ax.type.lastname!http://axschema.org/contact/email!http://axschema.org/pref/language'http://axschema.org/namePerson/friendly)r   r   r    zopenid.ax.type.,zopenid.ax.requiredz,http://specs.openid.net/extensions/oauth/1.0:r   )zopenid.ns.oauthzopenid.oauth.consumerzopenid.oauth.scope)r   r   r+   r,   urljoinr&   full_urlupdatesetappendjoinhostsplit)
r.   r!   r"   rH   r/   rD   r0   requiredknown_attrsr   s
             r   r(   OpenIdMixin._openid_args   sR    ~t,ll""7??#;#;#=|L;!US #"LL00c:*
 KK$B&5 8}HH!IIAA4Z3S3X =?EK
 !1<1B&-.% ! *-();D%&KK'U-4__-A-A-G-G-LQ-O*5 r   responsec                 V  ^^ [        [        U 5      mSUR                  ;  a  [        SUR                  -  5      eS mTR                  R
                   H7  nUR                  S5      (       d  M  TR                  U5      S:X  d  M2  USS  m  O   S[        S[        4UU4S jjnU" S	5      nU" S
5      nU" S5      nU" S5      nU" S5      nU" S5      R                  5       n	[        5       n
/ nU(       a  XjS'   UR                  U5        U(       a  XzS'   UR                  U5        U(       a  XZS'   O:U(       a  SR                  U5      U
S'   OU(       a  UR                  S5      S   U
S'   U(       a  XJS'   U	(       a  XS'   U(       a  XS'   TR                  SS 5      nU(       a  XS'   U
$ )Ns   is_valid:truezInvalid OpenID response: %rz
openid.ns.rM   
   r'   r#   c                 B  > T(       d  gST-   S-   nS nTR                   R                  R                  5        HK  nTR                  U5      U :X  d  M  UR	                  U5      (       d  M2  U[        U5      S  nST-   S-   U-   n  O   U(       d  gTR                  US5      $ )N zopenid.z.type.z.value.)r&   r=   keysget_argument
startswithlen)r'   prefixax_namer   partax_nsr/   s        r   
get_ax_arg;OpenIdMixin._on_authentication_verified.<locals>.get_ax_arg   s    &1FG11668''-49P9PF.D'%/);dBG	 9
 ''44r   rU   rS   rR   rT   rW   rV   
first_name	last_namer    @r   r   localer    rL   
claimed_id)r   r   r<   r   r&   r=   rl   rk   strlowerdictr^   r_   ra   )r.   re   keyrr   r   r   rt   ru   r    rx   user
name_partsry   rq   r/   s                @@r   rA   'OpenIdMixin._on_authentication_verified   s    ~t,8==09HMMIJJ ??,,C|,,((-1OOBC -	5C 	5C 	5 	5 >?:; FG
DE	GH?@FFHv
!+j) )i(L88J/DL ;;s+A.DL!M#N'))*=tD
!+r   c                 ,    [         R                  " 5       $ zReturns the `.AsyncHTTPClient` instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than
the default.
r   AsyncHTTPClientr.   s    r   r?    OpenIdMixin.get_auth_http_client       ))++r   r   N)r   r   r   r   __doc__r   rz   r   r2   r   r   r
   r	   rF   r   r(   HTTPResponserA   r?   r   r   r   r   r   r   ^   s     '+GHsmH s)H 
	H: CG6#J$>$>?6	c3h6F #%%)	44 3-4 c]	4
 
c3h4l<"//<	c3h<|,j&@&@ ,r   r   c                      \ rS rSrSr   SS\\   S\\\\4      S\\	R                     SS4S jjr SS\\	R                     S\\\4   4S	 jjr  SS\\   S\\\\4      S\4S
 jjrS\S\\   S\	R                  SS4S jrS\\\4   S\4S jrS\\\4   4S jrS\\\4   S\\\4   4S jr0 S4S\S\\\4   S\\\4   S\S\\\4   4
S jjrS\	R                  4S jrSrg)
OAuthMixini  a  Abstract implementation of OAuth 1.0 and 1.0a.

See `TwitterMixin` below for an example implementation.

Class attributes:

* ``_OAUTH_AUTHORIZE_URL``: The service's OAuth authorization url.
* ``_OAUTH_ACCESS_TOKEN_URL``: The service's OAuth access token url.
* ``_OAUTH_VERSION``: May be either "1.0" or "1.0a".
* ``_OAUTH_NO_CALLBACKS``: Set this to True if the service requires
  advance registration of callbacks.

Subclasses must also override the `_oauth_get_user_future` and
`_oauth_consumer_token` methods.
Nr!   extra_paramsr4   r#   c                   #    U(       a  [        U SS5      (       a  [        S5      eUc  U R                  5       nUc   e[        U SS5      S:X  a'  UR                  U R	                  XS95      I Sh  vN nO'UR                  U R	                  5       5      I Sh  vN nU R
                  nU R                  XQU5        g NK N%7f)a  Redirects the user to obtain OAuth authorization for this service.

The ``callback_uri`` may be omitted if you have previously
registered a callback URI with the third-party service. For
some services, you must use a previously-registered callback
URI and cannot specify a callback via this method.

This method sets a cookie called ``_oauth_request_token`` which is
subsequently used (and cleared) in `get_authenticated_user` for
security purposes.

This method is asynchronous and must be called with ``await``
or ``yield`` (This is different from other ``auth*_redirect``
methods defined in this module). It calls
`.RequestHandler.finish` for you so you should not write any
other response after it returns.

.. versionchanged:: 3.1
   Now returns a `.Future` and takes an optional callback, for
   compatibility with `.gen.coroutine`.

.. versionchanged:: 6.0

   The ``callback`` argument was removed. Use the returned
   awaitable object instead.

_OAUTH_NO_CALLBACKSFz,This service does not support oauth_callbackN_OAUTH_VERSION1.0a)r!   r   )getattr	Exceptionr?   r@   _oauth_request_token_url_OAUTH_AUTHORIZE_URL_on_request_token)r.   r!   r   r4   re   rD   s         r   authorize_redirectOAuthMixin.authorize_redirect0  s     B GD*?GGJKK335K&&&4)62f<(..--!- .  H )..t/L/L/NOOH''s(; Ps$   A/C1B=2'CB?$C?Cc                   #    [        [        U 5      n[        R                  " UR	                  S5      5      nUR	                  SS5      nUR                  S5      nU(       d  [        S5      eUR                  S5        S UR                  S5       5       u  pgXc:w  a  [        S5      e[        XgS	9nU(       a  XHS
'   Uc  U R                  5       nUc   eUR                  U R                  U5      5      I Sh  vN n	[        U	R                  5      n
U R                  U
5      I Sh  vN nU(       d  [        S5      eXS'   U$  NJ N7f)a5  Gets the OAuth authorized user and access token.

This method should be called from the handler for your
OAuth callback URL to complete the registration process. We run the
callback with the authenticated user dictionary.  This dictionary
will contain an ``access_key`` which can be used to make authorized
requests to this service on behalf of the user.  The dictionary will
also contain other fields such as ``name``, depending on the service
used.

.. versionchanged:: 6.0

   The ``callback`` argument was removed. Use the returned
   awaitable object instead.
oauth_tokenoauth_verifierN_oauth_request_tokenz"Missing OAuth request token cookiec              3   v   #    U  H/  n[         R                  " [        R                  " U5      5      v   M1     g 7fr   )base64	b64decoder   utf8).0is     r   	<genexpr>4OAuthMixin.get_authenticated_user.<locals>.<genexpr>z  s*      %
6OFV[[^,,6Os   79|z#Request token does not match cookier}   secretverifierzError getting useraccess_token)r   r   r   r   rk   
get_cookier   clear_cookiera   r|   r?   r@   _oauth_access_token_url_oauth_parse_responser<   _oauth_get_user_future)r.   r4   r/   request_keyr   request_cookie
cookie_keycookie_secrettokenre   r   r~   s               r   rF   !OAuthMixin.get_authenticated_usera  s=    $ ~t,kk'"6"6}"EF --.>E ++,BC@AA34%
6D6J6J36O%
!
 $ABB
  .*335K&&&$**4+G+G+NOO,X]];00>>011+^ P>s$   C5E7E8-E%E&EEc                    [        [        U 5      nU R                  5       nU R                  n[	        [
        R                  " US   5      S[        [        [        R                  " 5       5      5      [
        R                  " [        R                  " [        R                  " 5       R                  5      5      SS9n[        U SS5      S:X  at  US:X  a  SUS'   OBU(       a;  [         R"                  R%                  UR&                  R)                  5       U5      US'   U(       a  UR+                  U5        [-        US	XV5      nO[/        US	XV5      nXvS
'   US-   [         R"                  R1                  U5      -   $ )Nr}   	HMAC-SHA11.0)oauth_consumer_keyoauth_signature_methodoauth_timestampoauth_nonceoauth_versionr   r   ooboauth_callbackGEToauth_signaturer%   )r   r   _oauth_consumer_token_OAUTH_REQUEST_TOKEN_URLr|   r   to_basestringrz   inttimebinasciib2a_hexuuiduuid4bytesr   r+   r,   rZ   r&   r[   r\   _oauth10a_signature_oauth_signaturer-   )r.   r!   r   r/   consumer_tokenrD   r0   	signatures           r   r   #OAuthMixin._oauth_request_token_url  s.   
 ~t,335++%33N54IJ#.DIIK 01,,X-=-=djjl>P>P-QR
 4)62f<u$).%&)/)=)=OO,,.*%& L)+NE3MI(JI"+Sy6<<11$777r   authorize_urlre   c                    [        [        U 5      n[        UR                  5      n[        R
                  " [        R                  " US   5      5      S-   [        R
                  " [        R                  " US   5      5      -   nUR                  SU5        [        US   S9nUS:X  a5  UR                  US-   [        R                  R                  U5      -   5        g U(       a;  [        R                  R                  UR                  R!                  5       U5      US'   UR#                  US-   [        R                  R                  U5      -   5        g )	Nr}      |r   r   )r   r   r%   r   )r   r   r   r<   r   	b64encoder   r   
set_cookier|   finishr+   r,   r-   rZ   r&   r[   r*   )r.   r   r!   re   r/   request_tokendatar0   s           r   r   OAuthMixin._on_request_token  s    ~t,-hmm<V[[u)=>?v{{=+BCDE 	
 	148e 455 NN=3.1G1G1MMN%+\\%9%9((*L&D!" 	,v||/E/Ed/KKLr   r   c                 P   U R                  5       nU R                  n[        [        R                  " US   5      [        R                  " US   5      S[        [        [        R                  " 5       5      5      [        R                  " [        R                  " [        R                  " 5       R                  5      5      SS9nSU;   a  US   US'   [        U SS5      S:X  a  [        US	X4U5      nO[        US	X4U5      nXTS
'   US-   [         R"                  R%                  U5      -   $ )Nr}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r%   )r   _OAUTH_ACCESS_TOKEN_URLr|   r   r   rz   r   r   r   r   r   r   r   r   r   r   r+   r,   r-   )r.   r   r   rD   r0   r   s         r   r   "OAuthMixin._oauth_access_token_url  s   335**%33N54IJ,,]5-AB#.DIIK 01,,X-=-=djjl>P>P-QR
 &%2:%>D!"4)62f<+s-I )s-I #,Sy6<<11$777r   c                     [        5       e)zSubclasses must override this to return their OAuth consumer keys.

The return value should be a `dict` with keys ``key`` and ``secret``.
NotImplementedErrorr   s    r   r    OAuthMixin._oauth_consumer_token  s    
 "##r   r   c                    #    [        5       e7f)a  Subclasses must override this to get basic information about the
user.

Should be a coroutine whose result is a dictionary
containing information about the user, which may have been
retrieved by using ``access_token`` to make a request to the
service.

The access token will be added to the returned dictionary to make
the result of `get_authenticated_user`.

.. versionchanged:: 5.1

   Subclasses may also define this method with ``async def``.

.. versionchanged:: 6.0

   A synchronous fallback to ``_oauth_get_user`` was removed.
r   )r.   r   s     r   r   !OAuthMixin._oauth_get_user_future  s     , "##s   r   rD   
parametersr;   c                 D   U R                  5       n[        [        R                  " US   5      [        R                  " US   5      S[	        [        [        R                  " 5       5      5      [        R                  " [        R                  " [        R                  " 5       R                  5      5      SS9n0 nUR                  U5        UR                  U5        [        U SS5      S:X  a  [        XTXU5      nO[        XTXU5      n[        R                  " U5      US'   U$ )zReturns the OAuth parameters as a dict for the given request.

parameters should include all POST arguments and query string arguments
that will be sent with the request.
r}   r   r   r   r   r   r   )r   r|   r   r   rz   r   r   r   r   r   r   r   r\   r   r   r   )	r.   rD   r   r   r;   r   	base_argsr0   r   s	            r   _oauth_request_parameters$OAuthMixin._oauth_request_parameters  s     335%33N54IJ,,\%-@A#.DIIK 01,,X-=-=djjl>P>P-QR
	 IJ4)62f<+<I )<I (.';';I'F	#$r   c                 ,    [         R                  " 5       $ r   r   r   s    r   r?   OAuthMixin.get_auth_http_client"  r   r   r   )NNNr   NN)r   r   r   r   r   r   rz   r
   r	   r   r   r   rF   r   r   r   r   r   r   r   r?   r   r   r   r   r   r     s   $ '+15<@	/<sm/< tCH~./< j889	/<
 
/<d CG,#J$>$>?,	c3h,` '+158sm8 tCH~.8 
	8>MM smM ))	M
 
M08T#s(^ 8 84$tCH~ $$ cN$	c3h$8 &(!! 38n! cN	!
 ! 
c3h!F,j&@&@ ,r   r   c                   2   \ rS rSrSr      SS\\   S\\   S\\   S\\\\4      S	\\	\      S
\SS4S jjr
     SS\\   S\\   S\\   S\\   S\\\\4      S\4S jjr  SS\S\\   S\\\\4      S\S\4
S jjrS\R                  4S jrSrg)OAuth2Mixini+  a  Abstract implementation of OAuth 2.0.

See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example
implementations.

Class attributes:

* ``_OAUTH_AUTHORIZE_URL``: The service's authorization url.
* ``_OAUTH_ACCESS_TOKEN_URL``:  The service's access token url.
Ncoderedirect_uri	client_idclient_secretr   scoperesponse_typer#   c                 6   Ub  [         R                  " S[        5        [        [        U 5      nSU0nUb  XS'   Ub  X(S'   U(       a  UR                  U5        U(       a  SR                  U5      US'   U R                  n	UR                  [        X5      5        g)ay  Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with
your application instead of passing one via this method. You
should call this method to log the user in, and then call
``get_authenticated_user`` in the handler for your
redirect URL to complete the authorization process.

.. versionchanged:: 6.0

   The ``callback`` argument and returned awaitable were removed;
   this is now an ordinary synchronous function.

.. deprecated:: 6.4
   The ``client_secret`` argument (which has never had any effect)
   is deprecated and will be removed in Tornado 7.0.
Nz$client_secret argument is deprecatedr   r   r   rv   r   )
warningswarnDeprecationWarningr   r   r\   r_   r   r*   r   )
r.   r   r   r   r   r   r   r/   r0   rD   s
             r   r   OAuth2Mixin.authorize_redirect7  s    4 $MM@BTU~t,/##/   )KK%HHUODM''C./r   c                     U R                   n0 nUb  XS'   Ub  XGS'   Ub  X'S'   Ub  X7S'   U(       a  UR                  U5        [        Xg5      $ )Nr   r   r   r   )r   r\   r   )r.   r   r   r   r   r   rD   r0   s           r   r   $OAuth2Mixin._oauth_request_token_url`  se     **##/ L  )$$1!KK%#$$r   rD   r   	post_argsr0   c                   #    0 nU(       a  X%S'   UR                  U5        U(       a%  US[        R                  R                  U5      -   -  nU R	                  5       nUb7  UR                  US[        R                  R                  U5      S9I Sh  vN nOUR                  U5      I Sh  vN n[        R                  " UR                  5      $  N> N&7f)a  Fetches the given URL auth an OAuth2 access token.

If the request is a POST, ``post_args`` should be provided. Query
string arguments should be given as keyword arguments.

Example usage:

..testcode::

    class MainHandler(tornado.web.RequestHandler,
                      tornado.auth.FacebookGraphMixin):
        @tornado.web.authenticated
        async def get(self):
            new_entry = await self.oauth2_request(
                "https://graph.facebook.com/me/feed",
                post_args={"message": "I am posting from my Tornado application!"},
                access_token=self.current_user["access_token"])

            if not new_entry:
                # Call failed; perhaps missing permission?
                self.authorize_redirect()
                return
            self.finish("Posted a message!")

.. versionadded:: 4.3

.. versionchanged::: 6.0

   The ``callback`` argument was removed. Use the returned awaitable object instead.
r   r%   Nr9   r:   )	r\   r+   r,   r-   r?   r@   r   json_decoder<   )r.   rD   r   r   r0   all_argshttpre   s           r   oauth2_requestOAuth2Mixin.oauth2_requestv  s     J '3^$OOD!3//999C((* !ZZF)?)?	)J (  H "ZZ_,H!!(--00 -s$   BCCC+C,%CCc                 ,    [         R                  " 5       $ )zReturns the `.AsyncHTTPClient` instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than
the default.

.. versionadded:: 4.3
r   r   s    r   r?    OAuth2Mixin.get_auth_http_client  s     ))++r   r   )NNNNNr   )NNNNNr   )r   r   r   r   r   r   rz   r
   r	   r   r   r   r   r   r   r?   r   r   r   r   r   r   +  sU   	 '+#''+15%)#'0sm'0 C='0  }	'0
 tCH~.'0 S	"'0 '0 
'0V '+#''+"15%sm% C=%  }	%
 sm% tCH~.% 
%2 '+.2	3131 sm31 DcN+	31
 31 
31j,j&@&@ ,r   r   c                       \ rS rSrSrSrSrSrSrSr	Sr
SS
\\   SS	4S jjr SS\S\\\4   S\\\\4      S\S\4
S jjrS\\\4   4S jrS\\\4   S\\\4   4S jrSrg	)TwitterMixini  a  Twitter OAuth authentication.

To authenticate with Twitter, register your application with
Twitter at http://twitter.com/apps. Then copy your Consumer Key
and Consumer Secret to the application
`~tornado.web.Application.settings` ``twitter_consumer_key`` and
``twitter_consumer_secret``. Use this mixin on the handler for the
URL you registered as your application's callback URL.

When your application is set up, you can use this mixin like this
to authenticate the user with Twitter and get access to their stream:

.. testcode::

    class TwitterLoginHandler(tornado.web.RequestHandler,
                              tornado.auth.TwitterMixin):
        async def get(self):
            if self.get_argument("oauth_token", None):
                user = await self.get_authenticated_user()
                # Save the user using e.g. set_signed_cookie()
            else:
                await self.authorize_redirect()

The user object returned by `~OAuthMixin.get_authenticated_user`
includes the attributes ``username``, ``name``, ``access_token``,
and all of the custom Twitter user attributes described at
https://dev.twitter.com/docs/api/1.1/get/users/show

.. deprecated:: 6.3
   This class refers to version 1.1 of the Twitter API, which has been
   deprecated by Twitter. Since Twitter has begun to limit access to its
   API, this class will no longer be updated and will be removed in the
   future.
z+https://api.twitter.com/oauth/request_tokenz*https://api.twitter.com/oauth/access_tokenz'https://api.twitter.com/oauth/authorizez*https://api.twitter.com/oauth/authenticateFzhttps://api.twitter.com/1.1Nr!   r#   c                    #    U R                  5       nUR                  U R                  US95      I Sh  vN nU R                  U R                  SU5        g N"7f)a  Just like `~OAuthMixin.authorize_redirect`, but
auto-redirects if authorized.

This is generally the right interface to use if you are using
Twitter for single-sign on.

.. versionchanged:: 3.1
   Now returns a `.Future` and takes an optional callback, for
   compatibility with `.gen.coroutine`.

.. versionchanged:: 6.0

   The ``callback`` argument was removed. Use the returned
   awaitable object instead.
)r!   N)r?   r@   r   r   _OAUTH_AUTHENTICATE_URL)r.   r!   r   re   s       r   r2   "TwitterMixin.authenticate_redirect  sX       ((*))|)D
 
 	t;;T8L
s   2AA#Apathr   r   r0   c                   #    UR                  S5      (       d  UR                  S5      (       a  UnOU R                  U-   S-   nU(       aU  0 nUR                  U5        UR                  U=(       d    0 5        Ub  SOSnU R                  XRXgS9nUR                  U5        U(       a%  US[        R
                  R                  U5      -   -  nU R                  5       n	Ub7  U	R                  US[        R
                  R                  U5      S	9I Sh  vN n
OU	R                  U5      I Sh  vN n
[        R                  " U
R                  5      $  N> N&7f)
av  Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``

The path should not include the format or API version number.
(we automatically use JSON format and API version 1).

If the request is a POST, ``post_args`` should be provided. Query
string arguments should be given as keyword arguments.

All the Twitter methods are documented at http://dev.twitter.com/

Many methods require an OAuth access token which you can
obtain through `~OAuthMixin.authorize_redirect` and
`~OAuthMixin.get_authenticated_user`. The user returned through that
process includes an 'access_token' attribute that can be used
to make authenticated requests via this method. Example
usage:

.. testcode::

    class MainHandler(tornado.web.RequestHandler,
                      tornado.auth.TwitterMixin):
        @tornado.web.authenticated
        async def get(self):
            new_entry = await self.twitter_request(
                "/statuses/update",
                post_args={"status": "Testing Tornado Web Server"},
                access_token=self.current_user["access_token"])
            if not new_entry:
                # Call failed; perhaps missing permission?
                await self.authorize_redirect()
                return
            self.finish("Posted a message!")

.. versionchanged:: 6.0

   The ``callback`` argument was removed. Use the returned
   awaitable object instead.
zhttp:zhttps:z.jsonNr9   r   )r;   r%   r:   )rl   _TWITTER_BASE_URLr\   r   r+   r,   r-   r?   r@   r   r   r<   )r.   r  r   r   r0   rD   r   r;   oauthr   re   s              r   twitter_requestTwitterMixin.twitter_request  s-    Z ??7##tx'@'@ C((4/'9CHOOD!OOIO,(4V%F228 3 E KK3//555C((* !ZZF)?)?	)J (  H "ZZ_,H!!(--00 -s$   DEEE*E+%EEc                     [        [        U 5      nUR                  SS5        UR                  SS5        [        UR                  S   UR                  S   S9$ )Ntwitter_consumer_keyzTwitter OAuthtwitter_consumer_secretr   )r   r   require_settingr|   settingsr.   r/   s     r   r   "TwitterMixin._oauth_consumer_token?  s[    ~t, 6H 9?K  !78##$=>
 	
r   c                 `   #    U R                  SUS9I S h  vN nU(       a  US   US'   U$  N7f)Nz/account/verify_credentials)r   screen_namer    )r  )r.   r   r~   s      r   r   #TwitterMixin._oauth_get_user_futureH  sD      ))) * 
 
 #M2D
s   .,.r   r   )r   r   r   r   r   r   r   r   r  r   r
  r   rz   r2   r
   r	   r  r   r   r   r   r   r   r  r    s    !F  MJDJ5M MQU M4 /3	F1F1 38nF1 DcN+	F1
 F1 
F1P
tCH~ 
 cN	c3hr   r  c                       \ rS rSrSrSrSrSrSrSr	S\
\\4   4S	 jr  SS\S\S\\   S\\   S\
\\4   4
S jjrSrg
)GoogleOAuth2MixiniS  a  Google authentication using OAuth2.

In order to use, register your application with Google and copy the
relevant parameters to your application settings.

* Go to the Google Dev Console at http://console.developers.google.com
* Select a project, or create a new one.
* Depending on permissions required, you may need to set your app to
  "testing" mode and add your account as a test user, or go through
  a verfication process. You may also need to use the "Enable
  APIs and Services" command to enable specific services.
* In the sidebar on the left, select Credentials.
* Click CREATE CREDENTIALS and click OAuth client ID.
* Under Application type, select Web application.
* Name OAuth 2.0 client and click Create.
* Copy the "Client secret" and "Client ID" to the application settings as
  ``{"google_oauth": {"key": CLIENT_ID, "secret": CLIENT_SECRET}}``
* You must register the ``redirect_uri`` you plan to use with this class
  on the Credentials page.

.. versionadded:: 3.2
z,https://accounts.google.com/o/oauth2/v2/authz*https://www.googleapis.com/oauth2/v4/tokenz-https://www.googleapis.com/oauth2/v1/userinfoFgoogle_oauthr#   c                 T    [        [        U 5      nUR                  U R                     $ )aZ  Return the Google OAuth 2.0 credentials that you created with
[Google Cloud
Platform](https://console.cloud.google.com/apis/credentials). The dict
format is::

    {
        "key": "your_client_id", "secret": "your_client_secret"
    }

If your credentials are stored differently (e.g. in a db) you can
override this method for custom provision.
)r   r   r  _OAUTH_SETTINGS_KEYr  s     r   get_google_oauth_settings+GoogleOAuth2Mixin.get_google_oauth_settingsq  s'     ~t, 8 899r   Nr   r   r   r   c                 P  #    Ub  Uc   U R                  5       nUc  US   nUc  US   nU R                  5       n[        R                  R	                  UUUUSS.5      nUR                  U R                  SSS0US	9I Sh  vN n[        R                  " UR                  5      $  N$7f)
a  Handles the login for the Google user, returning an access token.

The result is a dictionary containing an ``access_token`` field
([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).
Unlike other ``get_authenticated_user`` methods in this package,
this method does not return any additional information about the user.
The returned access token can be used with `OAuth2Mixin.oauth2_request`
to request additional information (perhaps from
``https://www.googleapis.com/oauth2/v2/userinfo``)

Example usage:

.. testsetup::

    import urllib

.. testcode::

    class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
                                   tornado.auth.GoogleOAuth2Mixin):
        async def get(self):
            # Google requires an exact match for redirect_uri, so it's
            # best to get it from your app configuration instead of from
            # self.request.full_uri().
            redirect_uri = urllib.parse.urljoin(self.application.settings['redirect_base_uri'],
                self.reverse_url('google_oauth'))
            async def get(self):
                if self.get_argument('code', False):
                    access = await self.get_authenticated_user(
                        redirect_uri=redirect_uri,
                        code=self.get_argument('code'))
                    user = await self.oauth2_request(
                        "https://www.googleapis.com/oauth2/v1/userinfo",
                        access_token=access["access_token"])
                    # Save the user and access token. For example:
                    user_cookie = dict(id=user["id"], access_token=access["access_token"])
                    self.set_signed_cookie("user", json.dumps(user_cookie))
                    self.redirect("/")
                else:
                    self.authorize_redirect(
                        redirect_uri=redirect_uri,
                        client_id=self.get_google_oauth_settings()['key'],
                        scope=['profile', 'email'],
                        response_type='code',
                        extra_params={'approval_prompt': 'auto'})

.. versionchanged:: 6.0

   The ``callback`` argument was removed. Use the returned awaitable object instead.
Nr}   r   authorization_code)r   r   r   r   
grant_typer9   zContent-Typez!application/x-www-form-urlencoded)r;   headersr<   )
r  r?   r+   r,   r-   r@   r   r   r   r<   )	r.   r   r   r   r   r  r   r<   re   s	            r   rF   (GoogleOAuth2Mixin.get_authenticated_user  s     t  5557H $UO	$ ( 2((*||%% ,&!.2
 ((#%HI	 $ 
 
 !!(--00
s   A=B&?B$ %B&r   r   )r   r   r   r   r   r   r   _OAUTH_USERINFO_URLr   r  r
   rz   r  r   r	   rF   r   r   r   r   r  r  S  s    . JJI(:4S> :( $('+Q1Q1 Q1 C=	Q1
  }Q1 
c3hQ1 Q1r   r  c                       \ rS rSrSrSrSrSrSr SS\	S	\	S
\	S\	S\
\\	\4      S\
\\	\4      4S jjr  SS\	S\
\	   S\
\\	\4      S\S\4
S jjrSrg)FacebookGraphMixini  z;Facebook authentication using the new Graph API and OAuth2.z.https://graph.facebook.com/oauth/access_token?z&https://www.facebook.com/dialog/oauth?Fzhttps://graph.facebook.comNr   r   r   r   extra_fieldsr#   c           
        #    U R                  5       nUUUUS.n1 SknU(       a  UR                  U5        UR                  U R                  " S0 UD65      I Sh  vN n	[        R
                  " U	R                  5      nUR                  S5      UR                  S5      S.n
U
S   c   eU R                  SU
S   [        R                  " UR                  S5      U
S   R                  S5      [        R                  S	9R                  5       S
R                  U5      S9I Sh  vN nUc  g0 nU H  nUR                  U5      X'   M     UR                  U
S   [!        U
R                  S5      5      S.5        U$  GN  NZ7f)a  Handles the login for the Facebook user, returning a user object.

Example usage:

.. testcode::

    class FacebookGraphLoginHandler(tornado.web.RequestHandler,
                                    tornado.auth.FacebookGraphMixin):
      async def get(self):
        redirect_uri = urllib.parse.urljoin(
            self.application.settings['redirect_base_uri'],
            self.reverse_url('facebook_oauth'))
        if self.get_argument("code", False):
            user = await self.get_authenticated_user(
                redirect_uri=redirect_uri,
                client_id=self.settings["facebook_api_key"],
                client_secret=self.settings["facebook_secret"],
                code=self.get_argument("code"))
            # Save the user with e.g. set_signed_cookie
        else:
            self.authorize_redirect(
                redirect_uri=redirect_uri,
                client_id=self.settings["facebook_api_key"],
                extra_params={"scope": "user_posts"})

This method returns a dictionary which may contain the following fields:

* ``access_token``, a string which may be passed to `facebook_request`
* ``session_expires``, an integer encoded as a string representing
  the time until the access token expires in seconds. This field should
  be used like ``int(user['session_expires'])``; in a future version of
  Tornado it will change from a string to an integer.
* ``id``, ``name``, ``first_name``, ``last_name``, ``locale``, ``picture``,
  ``link``, plus any fields named in the ``extra_fields`` argument. These
  fields are copied from the Facebook graph API
  `user object <https://developers.facebook.com/docs/graph-api/reference/user>`_

.. versionchanged:: 4.5
   The ``session_expires`` field was updated to support changes made to the
   Facebook API in March 2017.

.. versionchanged:: 6.0

   The ``callback`` argument was removed. Use the returned awaitable object instead.
)r   r   r   r   >   idlinkr   rx   pictureru   rt   Nr   
expires_in)r   r,  z/mer   )r}   msg	digestmodrX   )r  r   appsecret_prooffields)r   session_expiresr   )r?   r\   r@   r   r   r   r<   getfacebook_requesthmacnewencodehashlibsha256	hexdigestr_   rz   )r.   r   r   r   r   r'  r   r0   r0  re   sessionr~   fieldmapfields                 r   rF   )FacebookGraphMixin.get_authenticated_user  s    j ((*("*	
 XMM,'))1D1
 
 !!(--0 HH^4((<0
 ~&222** 0 HH!((0N+226:!.. ik88F# + 	
 	
 <E"hhuoHO  	 ' 7#&w{{<'@#A	
 M
	
s&   AE?E:CE?"E=#AE?=E?r  r   r   r0   c                 f   #    U R                   U-   nU R                  " U4X#S.UD6I Sh  vN $  N7f)a  Fetches the given relative API path, e.g., "/btaylor/picture"

If the request is a POST, ``post_args`` should be provided. Query
string arguments should be given as keyword arguments.

An introduction to the Facebook Graph API can be found at
http://developers.facebook.com/docs/api

Many methods require an OAuth access token which you can
obtain through `~OAuth2Mixin.authorize_redirect` and
`get_authenticated_user`. The user returned through that
process includes an ``access_token`` attribute that can be
used to make authenticated requests via this method.

Example usage:

.. testcode::

    class MainHandler(tornado.web.RequestHandler,
                      tornado.auth.FacebookGraphMixin):
        @tornado.web.authenticated
        async def get(self):
            new_entry = await self.facebook_request(
                "/me/feed",
                post_args={"message": "I am posting from my Tornado application!"},
                access_token=self.current_user["access_token"])

            if not new_entry:
                # Call failed; perhaps missing permission?
                self.authorize_redirect()
                return
            self.finish("Posted a message!")

The given path is relative to ``self._FACEBOOK_BASE_URL``,
by default "https://graph.facebook.com".

This method is a wrapper around `OAuth2Mixin.oauth2_request`;
the only difference is that this method takes a relative path,
while ``oauth2_request`` takes a complete url.

.. versionchanged:: 3.1
   Added the ability to override ``self._FACEBOOK_BASE_URL``.

.. versionchanged:: 6.0

   The ``callback`` argument was removed. Use the returned awaitable object instead.
)r   r   N)_FACEBOOK_BASE_URLr   )r.   r  r   r   r0   rD   s         r   r3  #FacebookGraphMixin.facebook_requestF  sH     l %%,((
*
CG
 
 	
 
s   (1/1r   r   r   )r   r   r   r   r   r   r   r   r?  rz   r   r
   r	   rF   r3  r   r   r   r   r&  r&    s    ENC5 26gg g 	g
 g tCH~.g 
$sCx.	!gX '+.2	9
9
 sm9
 DcN+	9

 9
 
9
 9
r   r&  r   r;   rD   r   r   r#   c           	      (   [         R                  R                  U5      nUSS u  pgnUR                  5       S-   UR                  5       -   U-   n	/ n
U
R	                  UR                  5       5        U
R	                  U	5        U
R	                  SR                  S [        UR                  5       5       5       5      5        SR                  S U
 5       5      n[        R                  " U S   5      /nUR	                  [        R                  " U(       a  US   OS5      5        S	R                  U5      n[        R                  " U[        R                  " U5      [        R                  5      n[        R                   " UR#                  5       5      SS
 $ )zpCalculates the HMAC-SHA1 OAuth signature for the given request.

See http://oauth.net/core/1.0/#signing_process
N   ://&c              3   X   #    U  H   u  pU S [        [        U5      5       3v   M"     g7f=N_oauth_escaperz   r   rB   rC   s      r   r   #_oauth_signature.<locals>.<genexpr>  )     W<VDAA3ac!f-./<V   (*c              3   8   #    U  H  n[        U5      v   M     g 7fr   rI  r   es     r   r   rK         @Z=++Z   r   ri      &r6   )r+   r,   urlparser{   r^   upperr_   sortedr>   r   r   r4  r5  r7  sha1r   
b2a_base64digestr   r;   rD   r   r   partsschemenetlocr  normalized_url
base_elemsbase_string	key_elemsr}   hashs                  r   r   r     s3    LL!!#&E !9FD\\^e+flln<tCNJflln%n%WF:CSCSCU<VWW ((@Z@@K^H567IV[[ExrBC
))I
C88C[17<<@Dt{{}-cr22r   c           	         [         R                  R                  U5      nUSS u  pgnUR                  5       S-   UR                  5       -   U-   n	/ n
U
R	                  UR                  5       5        U
R	                  U	5        U
R	                  SR                  S [        UR                  5       5       5       5      5        SR                  S U
 5       5      n[        R                  " [         R                  R                  U S   SS	95      /nUR	                  [        R                  " U(       a!  [         R                  R                  US   SS	9OS
5      5        SR                  U5      n[        R                  " U[        R                  " U5      [        R                  5      n[         R"                  " UR%                  5       5      SS $ )zvCalculates the HMAC-SHA1 OAuth 1.0a signature for the given request.

See http://oauth.net/core/1.0a/#signing_process
NrB  rC  rD  c              3   X   #    U  H   u  pU S [        [        U5      5       3v   M"     g7frF  rH  rJ  s      r   r   &_oauth10a_signature.<locals>.<genexpr>  rL  rM  c              3   8   #    U  H  n[        U5      v   M     g 7fr   rO  rP  s     r   r   rf    rR  rS  r   ~saferi   rT  r6   )r+   r,   rU  r{   r^   rV  r_   rW  r>   r   r   quoter4  r5  r7  rX  r   rY  rZ  r[  s                  r   r   r     sa    LL!!#&E !9FD\\^e+flln<tCNJflln%n%WF:CSCSCU<VWW ((@Z@@KV\\//x0Hs/STUIUFLL&&uXS&APRS ))I
C88C[17<<@Dt{{}-cr22r   valc                     [        U [        5      (       a  U R                  S5      n [        R                  R                  U SS9$ )Nzutf-8rh  ri  )
isinstancer   r6  r+   r,   rk  )rl  s    r   rI  rI    s7    #|$$jj!<<c,,r   r<   c                    ^^ [         R                  " U 5      n[        R                  R	                  USS9m[        TS   S   TS   S   S9nSmUR                  UU4S jT 5       5        U$ )	NF)keep_blank_valuesr   r   oauth_token_secretr   )r   rq  c              3   F   >#    U  H  oT;  d  M
  UTU   S    4v   M     g7f)r   Nr   )r   rB   pspecials     r   r   (_oauth_parse_response.<locals>.<genexpr>  s$     =q!W,<!QqT!Wqs   	!!)r   
native_strr+   r,   parse_qsr|   r\   )r<   body_strr   rs  rt  s      @@r   r   r     sm       &Hh%@AQ}%a(3G1H1KLE 4G	LL=q==Lr   ))r   r   r   r7  r4  r   urllib.parser+   r   r   tornador   r   tornado.httputilr   tornado.utilr   tornado.webr   typingr   r	   r
   r   r   r   r   r   r   r   r   r   r  r  r&  rz   r   r   r   rI  r   r   r   r   <module>r     s   6p           ' % & C C C		 	~, ~,BI, I,XH, H,VZ: Zz1 1Dj
 j
b "$&*3cN33 
3 S#X	3
 DcN#3 3F "$&*3cN33 
3 S#X	3
 DcN#3 3B-uS%Z( -S - $sCx. r   