
    Mh;                     l   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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 ddlmZ ddlmZmZmZmZmZmZmZ  G d	 d
e          Z G d d          Z G d d          Z G d d          Z G d de          Z  G d de          Z! G d de          Z"i dfdee#ef         de#de#dee#ef         deee#ef                  de$fdZ%i dfdee#ef         de#de#dee#ef         deee#ef                  de$fdZ&dee#e$f         de#fd Z'd!e$dee#ef         fd"Z(dS )#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                       e Zd ZdS )	AuthErrorN)__name__
__module____qualname__     L/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/tornado/auth.pyr   r   Z   s        Dr   r   c                      e Zd ZdZdg dfdee         dee         ddfdZ	 ddeej	                 de
eef         fd	Zg dfdedee         d
ee         de
eef         fdZdej        de
eef         fdZdej	        fdZdS )OpenIdMixinzAbstract 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                     t          t          |           }|p|j        j        }|J |                     ||          }| j        }|                    |dz   t          j        	                    |          z              dS )a  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_redirectz!OpenIdMixin.authenticate_redirectf   s    * ~t,,#:w':'''   AA(C&,*@*@*F*FFGGGGGr   http_clientc                 d  K   t          t          |           }d |j        j                                        D             }d|d<   | j        }||                                 }|                    |dt          j	        
                    |                     d{V }|                     |          S )ak  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.
        c                 &    i | ]\  }}||d          S )r   .0kvs      r   
<dictcomp>z6OpenIdMixin.get_authenticated_user.<locals>.<dictcomp>   s/     
 
 
AAqu
 
 
r   check_authenticationopenid.modeNPOSTmethodbody)r   r   r"   	argumentsitemsr%   get_auth_http_clientfetchr'   r(   r)   _on_authentication_verified)r*   r/   r+   r,   urlresps         r   get_authenticated_userz"OpenIdMixin.get_authenticated_user   s      $ ~t,,
 
!(!:!@!@!B!B
 
 
 5]#3355K &&V\%;%;D%A%A ' 
 
 
 
 
 
 
 
 //555r   oauth_scopec                    t          t          |           }t          j                            |j                                        |          }ddd|t          j                            |d          dd}|r|                    ddd           t          |          }g }d	|v r'|h d
z  }|g dz  }|                    dddd           dddd}|D ]%}	||	         |d|	z   <   |	                    |	           &d
                    |          |d<   |r<|                    d|j        j                            d          d         |d           |S )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.realmr9   http://openid.net/srv/ax/1.0fetch_request)zopenid.ns.axzopenid.ax.moder   >   r   fullnamelastname	firstname)rO   rM   rN   $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   rF   r+   rC   r,   requiredknown_attrsr   s
             r   r$   zOpenIdMixin._openid_args   s    ~t,,l""7?#;#;#=#=|LL;!US #"L00c::*
 
  	<KK$B&5    8}}HH!!IIIIAAAA4Z3S3X    =?E K
 ! & &1<T1B&-.%%%%),(););D%& 	KK'U-4_-A-G-G-L-LQ-O*5    r   responsec                 V   t          t          |           d|j        vrt          d|j        z            d j        j        D ]<}|                    d          r%                    |          dk    r|dd           n=dt          dt          ffd} |d	          } |d
          } |d          } |d          } |d          } |d          	                                }	t                      }
g }|r||
d<   |                    |           |r||
d<   |                    |           |r||
d<   n;|rd                    |          |
d<   n |r|                    d          d         |
d<   |r||
d<   |	r|	|
d<   |r||
d<                       dd           }|r||
d<   |
S )Ns   is_valid:truezInvalid OpenID response: %rz
openid.ns.rK   
   r#   r   c                 :   sdS dz   dz   }d }j         j                                        D ]T}                    |          | k    r9|                    |          r$|t          |          d          }dz   dz   |z   } nU|sdS                     |d          S )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_argz;OpenIdMixin._on_authentication_verified.<locals>.get_ax_arg   s     r&1FG16688  ''--449P9P4F.D'%/);dBGE r''444r   rS   rQ   rP   rR   rU   rT   
first_name	last_namer    @r   r   localer   rJ   
claimed_id)r   r   r=   r   r"   r>   ri   rh   strlowerdictr\   r]   r_   )r*   rb   keyro   r   r   rp   rq   r   rt   user
name_partsru   rn   r+   s                @@r   rB   z'OpenIdMixin._on_authentication_verified   sB    ~t,,8=009HMIJJJ ?, 	 	C|,,((--1OOOBCC	5C 	5C 	5 	5 	5 	5 	5 	5 	5 
>??z:;;Z FGG
JDEE	:GHH?@@FFHHvv
 	*!+Dj))) 	) )Di((( 	/DLL 	/88J//DLL 	/ ;;s++A.DL 	"!DM 	$#DN 	('D))*=tDD
 	,!+Dr   c                 (    t          j                    S 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@   z OpenIdMixin.get_auth_http_client       )+++r   N)r   r   r   __doc__r   rv   r   r.   r   r   r
   r	   rE   r   r$   HTTPResponserB   r@   r   r   r   r   r   ^   sX         '+GGGH HsmH s)H 
	H H H H: CG6 6#J$>?6	c3h6 6 6 6F #%%)	4 44 3-4 c]	4
 
c3h4 4 4 4l<"/<	c3h< < < <|,j&@ , , , , , ,r   r   c                      e Zd ZdZ	 	 	 ddee         deeeef                  deej	                 ddfdZ
	 ddeej	                 deeef         fdZ	 	 ddee         deeeef                  defd	Zd
edee         dej        ddfdZdeeef         defdZdeeef         fdZdeeef         deeef         fdZi dfdedeeef         deeef         dedeeef         f
dZdej	        fdZdS )
OAuthMixina+  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_paramsr/   r   c                   K   |r t          | dd          rt          d          ||                                 }|J t          | dd          dk    r1|                    |                     ||                     d{V }n-|                    |                                            d{V }| j        }|                     |||           dS )aR  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@   rA   _oauth_request_token_url_OAUTH_AUTHORIZE_URL_on_request_token)r*   r   r   r/   rb   rC   s         r   authorize_redirectzOAuthMixin.authorize_redirect0  s     B  	LGD*?GG 	LJKKK3355K&&&4)622f<<(..--!-L .         HH )..t/L/L/N/NOOOOOOOOH'sL(;;;;;r   c                   K   t          t          |           }t          j        |                    d                    }|                    dd          }|                    d          }|st          d          |                    d           d |                    d          D             \  }}||k    rt          d          t          ||	          }|r||d
<   || 
                                }|J |                    |                     |                     d{V }	t          |	j                  }
|                     |
           d{V }|st          d          |
|d<   |S )a  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   b   K   | ]*}t          j        t          j        |                    V  +d S r   )base64	b64decoder   utf8)r4   is     r   	<genexpr>z4OAuthMixin.get_authenticated_user.<locals>.<genexpr>z  sF       %
 %
12FV[^^,,%
 %
 %
 %
 %
 %
r   |z#Request token does not match cookiery   secretverifierzError getting useraccess_token)r   r   r   r   rh   
get_cookier   clear_cookier_   rx   r@   rA   _oauth_access_token_url_oauth_parse_responser=   _oauth_get_user_future)r*   r/   r+   request_keyr   request_cookie
cookie_keycookie_secrettokenrb   r   rz   s               r   rE   z!OAuthMixin.get_authenticated_usera  s     $ ~t,,k'"6"6}"E"EFF --.>EE ++,BCC 	B@AAA3444%
 %
6D6J6J36O6O%
 %
 %
!
M $$ABBB=
 
 
  	/ .E*3355K&&&$**4+G+G+N+NOOOOOOOO,X];;00>>>>>>>> 	20111+^r   c                 
   t          t          |           }|                                 }| j        }t	          t          j        |d                   dt          t          t          j	                                        t          j        t          j        t          j                    j                            d          }t          | dd          dk    rr|dk    rd|d<   n<|r:t           j                            |j                                        |          |d<   |r|                    |           t-          |d	||          }nt/          |d	||          }||d
<   |dz   t           j                            |          z   S )Nry   	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_URLrx   r   to_basestringrv   inttimebinasciib2a_hexuuiduuid4bytesr   r'   r(   rX   r"   rY   rZ   _oauth10a_signature_oauth_signaturer)   )r*   r   r   r+   consumer_tokenrC   r,   	signatures           r   r   z#OAuthMixin._oauth_request_token_url  sm   
 ~t,,3355+%3N54IJJ#.DIKK 0 011,X-=djll>P-Q-QRR
 
 
 4)622f<<u$$).%&& )/)=)=O,,..* *%&  *L)))+NE3MMII(TJJI"+Sy6<11$7777r   authorize_urlrb   c                    t          t          |           }t          |j                  }t	          j        t          j        |d                             dz   t	          j        t          j        |d                             z   }|                    d|           t          |d                   }|dk    r:|
                    |dz   t          j                            |          z              d S |r:t          j                            |j                                        |          |d<   |                    |dz   t          j                            |          z              d S )	Nry      |r   r   )r   r   r!   r   )r   r   r   r=   r   	b64encoder   r   
set_cookierx   finishr'   r(   r)   rX   r"   rY   r&   )r*   r   r   rb   r+   request_tokendatar,   s           r   r   zOAuthMixin._on_request_token  sG    ~t,,-hm<<V[u)=>>??v{=+BCCDDE 	
 	14888e 45555  NN=3.1G1G1M1MMNNNF 	%+\%9%9((**L& &D!" 	,v|/E/Ed/K/KKLLLLLr   r   c                 v   |                                  }| j        }t          t          j        |d                   t          j        |d                   dt          t          t          j                                        t          j        t          j	        t          j                    j                            d          }d|v r|d         |d<   t          | dd          dk    rt          |d	|||          }nt          |d	|||          }||d
<   |dz   t           j                            |          z   S )Nry   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r!   )r   _OAUTH_ACCESS_TOKEN_URLrx   r   r   rv   r   r   r   r   r   r   r   r   r   r   r'   r(   r)   )r*   r   r   rC   r,   r   s         r   r   z"OAuthMixin._oauth_access_token_url  s/   3355*%3N54IJJ,]5-ABB#.DIKK 0 011,X-=djll>P-Q-QRR
 
 
 &&%2:%>D!"4)622f<<+sD- II )sD- I #,Sy6<11$7777r   c                     t                      )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   z OAuthMixin._oauth_consumer_token  s    
 "###r   r   c                 "   K   t                      )aw  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   z!OAuthMixin._oauth_get_user_future  s      , "###r   r   rC   
parametersr<   c                    |                                  }t          t          j        |d                   t          j        |d                   dt	          t          t          j                                        t          j        t          j        t          j
                    j                            d          }i }|                    |           |                    |           t          | dd          dk    rt          |||||          }nt          |||||          }t          j        |          |d<   |S )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.
        ry   r   r   r   r   r   r   )r   rx   r   r   rv   r   r   r   r   r   r   r   rZ   r   r   r   )	r*   rC   r   r   r<   r   	base_argsr,   r   s	            r   _oauth_request_parametersz$OAuthMixin._oauth_request_parameters  s)    3355%3N54IJJ,\%-@AA#.DIKK 0 011,X-=djll>P-Q-QRR
 
 
	 IJ4)622f<<+T< II )T< I (.';I'F'F	#$r   c                 (    t          j                    S r}   r~   r   s    r   r@   zOAuthMixin.get_auth_http_client"  r   r   )NNNr   NN)r   r   r   r   r   rv   r
   r	   r   r   r   rE   r   r   r   r   r   r   r   r@   r   r   r   r   r     sc        $ '+15<@	/< /<sm/< tCH~./< j89	/<
 
/< /< /< /<d CG, ,#J$>?,	c3h, , , ,` '+158 8sm8 tCH~.8 
	8 8 8 8>MM smM )	M
 
M M M M08T#s(^ 8 8 8 8 84$tCH~ $ $ $ $$ cN$	c3h$ $ $ $8 &(! !! 38n! cN	!
 ! 
c3h! ! ! !F,j&@ , , , , , ,r   r   c                   t   e Zd ZdZ	 	 	 	 	 	 ddee         dee         dee         deeeef                  deee                  d	ed
dfdZ		 	 	 	 	 ddee         dee         dee         dee         deeeef                  d
efdZ
	 	 ddedee         deeeef                  ded
ef
dZd
ej        fdZdS )OAuth2Mixina#  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                 B   |t          j        dt                     t          t          |           }d|i}|||d<   |||d<   |r|                    |           |rd                    |          |d<   | j        }	|                    t          |	|                     dS )a  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   rr   r   )
warningswarnDeprecationWarningr   r   rZ   r]   r   r&   r   )
r*   r   r   r   r   r   r   r+   r,   rC   s
             r   r   zOAuth2Mixin.authorize_redirect7  s    4 $M@BTUUU~t,,/##/D   )D 	&KK%%% 	,HHUOODM'C../////r   c                     | j         }i }|||d<   |||d<   |||d<   |||d<   |r|                    |           t          ||          S )Nr   r   r   r   )r   rZ   r   )r*   r   r   r   r   r   rC   r,   s           r   r   z$OAuth2Mixin._oauth_request_token_url`  sz     *##/D DL  )D$$1D! 	&KK%%%#t$$$r   rC   r   	post_argsr,   c                   K   i }|r||d<   |                     |           |r%|dt          j                            |          z   z  }|                                 }|<|                    |dt          j                            |                     d{V }n|                    |           d{V }t          j        |j                  S )aj  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!   Nr:   r;   )	rZ   r'   r(   r)   r@   rA   r   json_decoder=   )r*   rC   r   r   r,   all_argshttprb   s           r   oauth2_requestzOAuth2Mixin.oauth2_requestv  s      J  	"'3H^$OOD!!! 	:3//9999C((** !ZZF)?)?	)J)J (        HH "ZZ__,,,,,,H!(-000r   c                 (    t          j                    S )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@   z OAuth2Mixin.get_auth_http_client  s     )+++r   )NNNNNr   )NNNNNr   )r   r   r   r   r   rv   r
   r	   r   r   r   r   r   r   r@   r   r   r   r   r   +  s       	 	 '+#''+15%)#'0 '0sm'0 C='0  }	'0
 tCH~.'0 S	"'0 '0 
'0 '0 '0 '0V '+#''+"15% %sm% C=%  }	%
 sm% tCH~.% 
% % % %2 '+.2	31 3131 sm31 DcN+	31
 31 
31 31 31 31j,j&@ , , , , , ,r   r   c                       e Zd ZdZdZdZdZdZdZdZ	dd	e
e         d
dfdZ	 ddedeeef         de
eeef                  ded
ef
dZd
eeef         fdZdeeef         d
eeef         fdZdS )TwitterMixina  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                    K   |                                  }|                    |                     |                     d{V }|                     | j        d|           dS )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@   rA   r   r   _OAUTH_AUTHENTICATE_URL)r*   r   r   rb   s       r   r.   z"TwitterMixin.authenticate_redirect  s        ((**))|)DD
 
 
 
 
 
 
 
 	t;T8LLLLLr   pathr   r   r,   c                   K   |                     d          s|                     d          r|}n| j        |z   dz   }|rbi }|                    |           |                    |pi            |dnd}|                     ||||          }|                    |           |r%|dt          j                            |          z   z  }|                                 }	|<|	                    |dt          j                            |          	           d{V }
n|	                    |           d{V }
t          j
        |
j                  S )
a^  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.jsonNr:   r   )r<   r!   r;   )ri   _TWITTER_BASE_URLrZ   r   r'   r(   r)   r@   rA   r   r   r=   )r*   r   r   r   r,   rC   r   r<   oauthr   rb   s              r   twitter_requestzTwitterMixin.twitter_request  s     Z ??7## 	:tx'@'@ 	: CC(4/'9C 	HOOD!!!OOIO,,,(4VV%F22\8F 3  E KK 	63//5555C((** !ZZF)?)?	)J)J (        HH "ZZ__,,,,,,H!(-000r   c                     t          t          |           }|                    dd           |                    dd           t          |j        d         |j        d                   S )Ntwitter_consumer_keyzTwitter OAuthtwitter_consumer_secretr   )r   r   require_settingrx   settingsr*   r+   s     r   r   z"TwitterMixin._oauth_consumer_token?  sn    ~t,, 6HHH 9?KKK !78#$=>
 
 
 	
r   c                 ^   K   |                      d|           d {V }|r|d         |d<   |S )Nz/account/verify_credentials)r   screen_namer   )r   )r*   r   rz   s      r   r   z#TwitterMixin._oauth_get_user_futureH  sc       ))) * 
 
 
 
 
 
 
 
  	3#M2Dr   r   )r   r   r   r   r   r   r   r   r   r   r   rv   r.   r
   r	   r   r   r   r   r   r   r   r     s>       ! !F  MJDJ5M M MQU M M M M4 /3	F1 F1F1 38nF1 DcN+	F1
 F1 
F1 F1 F1 F1P
tCH~ 
 
 
 
 cN	c3h     r   r   c                       e Zd ZdZdZdZdZdZdZde	e
e
f         fdZ	 	 dd
e
de
dee
         dee
         de	e
ef         f
dZd	S )GoogleOAuth2Mixina"  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                 P    t          t          |           }|j        | j                 S )a  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_settingsz+GoogleOAuth2Mixin.get_google_oauth_settingsq  s$     ~t,, 899r   Nr   r   r   r   c                 N  K   ||(|                                  }||d         }||d         }|                                 }t          j                            ||||dd          }|                    | j        dddi|	           d{V }t          j        |j	                  S )
a4
  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.
        Nry   r   authorization_code)r   r   r   r   
grant_typer:   zContent-Typez!application/x-www-form-urlencoded)r<   headersr=   )
r  r@   r'   r(   r)   rA   r   r   r   r=   )	r*   r   r   r   r   r   r   r=   rb   s	            r   rE   z(GoogleOAuth2Mixin.get_authenticated_user  s      t  55577H $UO	$ ( 2((**|%% ,&!.2 
 
 (#%HI	 $ 
 
 
 
 
 
 
 
 !(-000r   r   )r   r   r   r   r   r   _OAUTH_USERINFO_URLr   r  r
   rv   r  r   r	   rE   r   r   r   r   r   S  s         . JJI(:4S> : : : :( $('+Q1 Q1Q1 Q1 C=	Q1
  }Q1 
c3hQ1 Q1 Q1 Q1 Q1 Q1r   r   c                       e Zd ZdZdZdZdZdZ	 ddeded	ed
ede	e
eef                  de	e
eef                  fdZ	 	 ddede	e         de	e
eef                  dedef
dZdS )FacebookGraphMixinz;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           
      J  K   |                                  }||||d}h d}|r|                    |           |                     | j        di |           d{V }	t	          j        |	j                  }|                    d          |                    d          d}
|
d         J |                     d|
d         t          j
        |                    d          |
d                             d          t          j        	                                          d
                    |                     d{V }|dS i }|D ]}|                    |          ||<   |                    |
d         t!          |
                    d                    d           |S )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   rt   picturerq   rp   Nr   
expires_in)r   r  z/mer   )ry   msg	digestmodrV   )r   r   appsecret_prooffields)r   session_expiresr   )r@   rZ   rA   r   r   r   r=   getfacebook_requesthmacnewencodehashlibsha256	hexdigestr]   rv   )r*   r   r   r   r   r  r   r,   r  rb   sessionrz   fieldmapfields                 r   rE   z)FacebookGraphMixin.get_authenticated_user  s     j ((**("*	
 
 XWW 	(MM,''')D)11D11
 
 
 
 
 
 
 
 !(-00 HH^44((<00
 
 ~&222** 0 H!((00N+226::!.   ikk88F## + 	
 	
 	
 	
 	
 	
 	
 	
 <4 	. 	.E"hhuooHUOO 	 ' 7#&w{{<'@'@#A#A 	
 	
 	
 r   r   r   r   r,   c                 H   K   | j         |z   } | j        |f||d| d{V S )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   r,   rC   s         r   r  z#FacebookGraphMixin.facebook_requestF  se      l %,(T(
*i
 
CG
 
 
 
 
 
 
 
 	
r   r   r   )r   r   r   r   r   r   r   r#  rv   r   r
   r	   rE   r  r   r   r   r  r    s       EENC5 26g gg g 	g
 g tCH~.g 
$sCx.	!g g g gX '+.2	9
 9
9
 sm9
 DcN+	9

 9
 
9
 9
 9
 9
 9
 9
r   r  r   r<   rC   r   r   r   c           	         t           j                            |          }|dd         \  }}}|                                dz   |                                z   |z   }	g }
|
                    |                                           |
                    |	           |
                    d                    d t          |                                          D                                  d                    d |
D                       }t          j
        | d                   g}|                    t          j
        |r|d         nd                     d	                    |          }t          j        |t          j
        |          t          j                  }t          j        |                                          dd
         S )zxCalculates the HMAC-SHA1 OAuth signature for the given request.

    See http://oauth.net/core/1.0/#signing_process
    N   ://&c              3   ^   K   | ](\  }}| d t          t          |                     V  )dS =N_oauth_escaperv   r3   s      r   r   z#_oauth_signature.<locals>.<genexpr>  B      WWDAqA//c!ff--//WWWWWWr   c              3   4   K   | ]}t          |          V  d S r   r,  r4   es     r   r   z#_oauth_signature.<locals>.<genexpr>  *      @@=++@@@@@@r   r   rf      &r2   )r'   r(   urlparserw   r\   upperr]   sortedr?   r   r   r  r  r  sha1r   
b2a_base64digestr   r<   rC   r   r   partsschemenetlocr   normalized_url
base_elemsbase_string	key_elemsry   hashs                  r   r   r     s    L!!#&&E !9FFD\\^^e+fllnn<tCNJfllnn%%%n%%%WWF:CSCSCUCU<V<VWWWWW   ((@@Z@@@@@K^H5667IV[E!AxrBBCCC
))I

C8C[117<@@Dt{{}}--crc22r   c           	         t           j                            |          }|dd         \  }}}|                                dz   |                                z   |z   }	g }
|
                    |                                           |
                    |	           |
                    d                    d t          |                                          D                                  d                    d |
D                       }t          j
        t           j                            | d         d	                    g}|                    t          j
        |r't           j                            |d         d	          nd
                     d                    |          }t          j        |t          j
        |          t          j                  }t!          j        |                                          dd         S )z~Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.

    See http://oauth.net/core/1.0a/#signing_process
    Nr%  r&  r'  c              3   ^   K   | ](\  }}| d t          t          |                     V  )dS r)  r+  r3   s      r   r   z&_oauth10a_signature.<locals>.<genexpr>  r-  r   c              3   4   K   | ]}t          |          V  d S r   r/  r0  s     r   r   z&_oauth10a_signature.<locals>.<genexpr>  r2  r   r   ~saferf   r3  r2   )r'   r(   r4  rw   r\   r5  r]   r6  r?   r   r   quoter  r  r  r7  r   r8  r9  r:  s                  r   r   r     s    L!!#&&E !9FFD\\^^e+fllnn<tCNJfllnn%%%n%%%WWF:CSCSCUCU<V<VWWWWW   ((@@Z@@@@@KV\//x0Hs/SSTTUIURFL&&uXS&AAAPRSS   ))I

C8C[117<@@Dt{{}}--crc22r   valc                     t          | t                    r|                     d          } t          j                            | d          S )Nzutf-8rF  rG  )
isinstancer   r  r'   r(   rI  )rJ  s    r   r,  r,    s@    #|$$ "jj!!<c,,,r   r=   c                    t          j        |           }t          j                            |d          t          d         d         d         d                   }d|                    fdD                        |S )	NF)keep_blank_valuesr   r   oauth_token_secretr   )r   rO  c              3   @   K   | ]}|v||         d          fV  dS )r   Nr   )r4   r5   pspecials     r   r   z(_oauth_parse_response.<locals>.<genexpr>  s9      ==!AW,<,<!QqT!W,<,<,<,<==r   )r   
native_strr'   r(   parse_qsrx   rZ   )r=   body_strr   rQ  rR  s      @@r   r   r     s      &&Hh%@@AQ}%a(3G1H1KLLLE 4G	LL=====q======Lr   ))r   r   r   r  r  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  rv   r   r   r   r,  r   r   r   r   <module>r\     s   6 6p                        ' ' ' ' ' ' % % % % % % & & & & & & C C C C C C C C C C C C C C C C C C	 	 	 	 		 	 	 	~, ~, ~, ~, ~, ~, ~, ~,BI, I, I, I, I, I, I, I,XH, H, H, H, H, H, H, H,VZ Z Z Z Z: Z Z Zz1 1 1 1 1 1 1 1Dj
 j
 j
 j
 j
 j
 j
 j
b "$&*3 3cN33 
3 S#X	3
 DcN#3 3 3 3 3F "$&*3 3cN33 
3 S#X	3
 DcN#3 3 3 3 3B-uS%Z( -S - - - - $sCx.      r   