K i;dZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl mZddlmZddlmZddlmZmZmZmZmZmZmZGd d eZGd d ZGd dZGddZGddeZ GddeZ!GddeZ"idfdee#efde#de#dee#efdeee#efde$f dZ%idfdee#efde#de#dee#efdeee#efde$f dZ&dee#e$fde#fd Z'd!e$dee#effd"Z(y)#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)ListAnyDictcastIterableUnionOptionalc eZdZy) AuthErrorN)__name__ __module__ __qualname__R/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/tornado/auth.pyrrZsrrc eZdZdZdgdfdeedeeddfdZ ddeejde ee ffd Z gdfdede ed eede eeffd Zd ejde ee ffd ZdejfdZy) OpenIdMixinzAbstract implementation of OpenID and Attribute Exchange. Class attributes: * ``_OPENID_ENDPOINT``: the identity provider's URI. N)nameemaillanguageusername callback_uriax_attrsreturnctt|}|xs|jj}|J|j ||}|j }|j |dztjj|zy)aRedirects 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 rrequesturi _openid_args_OPENID_ENDPOINTredirecturllibparse urlencode)selfrrhandlerargsendpoints rauthenticate_redirectz!OpenIdMixin.authenticate_redirectfsv*~t,#:w':': '''   A((C&,,*@*@*FFGr http_clientcKtt|}|jjj Dcic] \}}||d }}}d|d<|j }||j }|j|dtjj|d{}|j|Scc}}w7w)akFetches 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.modeNPOSTmethodbody) r rr" argumentsitemsr%get_auth_http_clientfetchr'r(r)_on_authentication_verified)r*r/r+kvr,urlresps rget_authenticated_userz"OpenIdMixin.get_authenticated_users$~t,")!:!:!@!@!B AAquH  5]##  335K && V\\%;%;D%A'  //55  s8CB: AC$C%C oauth_scopecltt|}tjj |j j |}ddd|tjj |ddd}|r|jdddt|}g}d |vr#|hd z}|gd z }|jd d dddddd}|D]} || |d| z<|j|  dj||d<|r;|jd|j jjdd|d|S)Nz http://specs.openid.net/auth/2.0z2http://specs.openid.net/auth/2.0/identifier_select/ checkid_setup)z openid.nsopenid.claimed_idzopenid.identityzopenid.return_toz openid.realmr3http://openid.net/srv/ax/1.0 fetch_request)z openid.ns.axzopenid.ax.moder>rfullnamelastname firstname)rKrIrJ$http://axschema.org/namePerson/firsthttp://axschema.org/namePerson#http://axschema.org/namePerson/last)zopenid.ax.type.firstnamezopenid.ax.type.fullnamezopenid.ax.type.lastname!http://axschema.org/contact/email!http://axschema.org/pref/language'http://axschema.org/namePerson/friendly)rrrzopenid.ax.type.,zopenid.ax.requiredz,http://specs.openid.net/extensions/oauth/1.0:r)zopenid.ns.oauthzopenid.oauth.consumerzopenid.oauth.scope) r rr'r(urljoinr"full_urlupdatesetappendjoinhostsplit) r*rrrBr+r?r,required known_attrsrs rr$zOpenIdMixin._openid_argssY ~t,ll""7??#;#;#=|L;!US #"LL00c:*    KK$B&5  8}HH!IIAA 4Z3S3X=?EK ! &1.get_ax_args&1FG11668 ''-49PF .D'%/);dBG   ''4 4rrOrMrLrNrQrP first_name last_namer @rrlocalerrF claimed_id)r rr7rr"r8rerdstrlowerdictrXrYr[)r*r^keyrkrrrlrmrrpuser name_partsrqrjr+s @@rr<z'OpenIdMixin._on_authentication_verifieds~t, 8== 09HMMIJ J??,, C|,((-1OOBC   5C 5C 5>?:; FG DE GH?@FFHv !+D    j )  )D    i ( DL 88J/DL  ;;s+A.DL !DM #DN 'D ))*=tD !+D  rc*tjSzReturns the `.AsyncHTTPClient` instance to be used for auth requests. May be overridden by subclasses to use an HTTP client other than the default. rAsyncHTTPClientr*s rr:z OpenIdMixin.get_auth_http_client ))++rN)rrr__doc__rrrrr.rr{r r rAr r$ HTTPResponser<r:rrrrr^s'+GHsmHs)H  H:CG6#J$>$>?6 c3h6F#%%) 443-4c] 4 c3h 4l<"//< c3h<|,j&@&@,rrc eZdZdZ ddeedeeeefdeejddfdZ ddeejdeeeffdZ ddeedeeeefdefd Z d edeed ejddfd Zd eeefdefdZdeeeffdZdeeefdeeeffdZidfdedeeefdeeefdedeeeff dZdejfdZy) 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/rcvK|rt|ddr td||j}|Jt|dddk(r+|j|j ||d{}n'|j|j d{}|j }|j |||y7L7&w)aRRedirects 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_VERSION1.0a)rr)getattr Exceptionr:r;_oauth_request_token_url_OAUTH_AUTHORIZE_URL_on_request_token)r*rrr/r^r?s rauthorize_redirectzOAuthMixin.authorize_redirect0sB GD*?GJK K  335K&&& 4)6 2f <(..--!-L.H )..t/L/L/NOOH'' sL(; Ps$A&B9(B5)'B9B7%B97B9czKtt|}tj|j d}|j dd}|j d}|s t d|jdd|jdD\}}||k7r t dt|| }|r||d <||j}|J|j|j|d{} t| j} |j| d{} | s t d | | d <| S7F7w) aGets 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_tokenoauth_verifierN_oauth_request_tokenz"Missing OAuth request token cookiec3lK|],}tjtj|.ywr~)base64 b64decoderutf8).0is r z4OAuthMixin.get_authenticated_user..zs(% 12F  V[[^ ,% s24|z#Request token does not match cookierusecretverifierzError getting user access_token)r rrrrd get_cookier clear_cookier[rtr:r;_oauth_access_token_url_oauth_parse_responser7_oauth_get_user_future) r*r/r+ request_keyrrequest_cookie cookie_key cookie_secrettokenr^rrvs rrAz!OAuthMixin.get_authenticated_userasI$~t,kk'"6"6}"EF  --.>E ++,BC@A A34% 6D6J6J36O% ! M  $AB B=   .E*   335K&&&$**4+G+G+NOO,X]]; 00>>01 1+^ P>s$C.D;0D71-D;D9D;9D;c tt|}|j}|j}t t j |ddtttjt j tjtjjd}t|dddk(rj|dk(rd|d<n=|r;t j"j%|j&j)||d<|r|j+|t-|d ||}nt/|d ||}||d <|d zt j"j1|zS) Nru HMAC-SHA11.0)oauth_consumer_keyoauth_signature_methodoauth_timestamp oauth_nonce oauth_versionrrooboauth_callbackGEToauth_signaturer!)r r_oauth_consumer_token_OAUTH_REQUEST_TOKEN_URLrtr to_basestringrrinttimebinasciib2a_hexuuiduuid4bytesrr'r(rTr"rUrV_oauth10a_signature_oauth_signaturer))r*rrr+consumer_tokenr?r, signatures rrz#OAuthMixin._oauth_request_token_urls4 ~t,335++%33N54IJ#.DIIK 01,,X-=-=djjl>P>P-QR   4)6 2f <u$).%&)/)=)=OO,,. *%& L)+NE3MI(TJI"+ Sy6<<11$777r authorize_urlr^ctt|}t|j}t j t j|ddzt j t j|dz}|jd|t|d}|dk(r5|j|dztjj|zy|r;tjj|jj!||d<|j#|dztjj|zy) Nru|rr)rrr!r)r rrr7r b64encoderr set_cookiertfinishr'r(r)rTr"rUr&)r*rrr^r+ request_tokendatar,s rrzOAuthMixin._on_request_tokens ~t,-hmm<   V[[u)=> ? v{{=+BCD E 148 e 45 5 NN=3.1G1G1MM N  %+\\%9%9((*L&D! " ,v||/E/Ed/KKLrrc J|j}|j}ttj|dtj|ddt t tjtjtjtjjd}d|vr|d|d<t|dddk(rt|d |||}nt|d |||}||d <|d zt j"j%|zS) Nrurrrrrrrrrrrrrrr!)r_OAUTH_ACCESS_TOKEN_URLrtrrrrrrrrrrrrrrr'r(r))r*rrr?r,rs rrz"OAuthMixin._oauth_access_token_urls 335**%33N54IJ,,]5-AB#.DIIK 01,,X-=-=djjl>P>P-QR    &%2:%>D! " 4)6 2f <+sD-I)sD-I#, Sy6<<11$777rct)zSubclasses must override this to return their OAuth consumer keys. The return value should be a `dict` with keys ``key`` and ``secret``. NotImplementedErrorr|s rrz OAuthMixin._oauth_consumer_tokens "##rrcKtw)awSubclasses 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*rs rrz!OAuthMixin._oauth_get_user_futures,"##s rr? parametersr6c B|j}ttj|dtj|ddt t t j tjtjtjjd}i}|j||j|t|dddk(rt|||||}nt|||||}tj||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. rurrrrrr)rrtrrrrrrrrrrrrVrrr) r*r?rrr6r base_argsr,rs r_oauth_request_parametersz$OAuthMixin._oauth_request_parameterss335%33N54IJ,,\%-@A#.DIIK 01,,X-=-=djjl>P>P-QR   I J 4)6 2f <+T<I)T<I(.';';I'F #$rc*tjSryrzr|s rr:zOAuthMixin.get_auth_http_client"r}r)NNNr~NN)rrrrrrrr r rr{rrArrrrrrrr:rrrrrs$'+15<@ /<sm/<tCH~./<j889 /<  /$>?, c3h,`'+158sm8tCH~.8 8>MMsmM)) M  M08T#s(^884$tCH~$$ cN$ c3h$8&( ! !38n!cN !  ! c3h !F,j&@&@,rrceZdZdZ ddeedeedeedeeeefdeeed ed dfd Z ddeedeedeedeedeeeefd ef d Z dd edeedeeeefded ef dZ d e jfdZy) 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. Ncode redirect_uri client_id client_secretrscope response_typerc |tjdttt|}d|i}|||d<|||d<|r|j ||rdj ||d<|j} |jt| |y)aRedirects 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 deprecatedrrrrnr) warningswarnDeprecationWarningr rrVrYrr&r) r*rrrrrrr+r,r?s rrzOAuth2Mixin.authorize_redirect7s4  $ MM@BT U~t,/  ##/D  )D   KK % HHUODM''C./rc|j}i}|||d<|||d<|||d<|||d<|r|j|t||S)Nrrrr)rrVr)r*rrrrrr?r,s rrz$OAuth2Mixin._oauth_request_token_url`so**  ##/D  DL  )D   $$1D !  KK %#t$$rr?r post_argsr,cKi}|r||d<|j||r%|dtjj|zz }|j }|:|j |dtjj|d{}n|j |d{}t j|jS7=7%w)ajFetches 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. rr!Nr4r5) rVr'r(r)r:r;r json_decoder7)r*r?rrr,all_argshttpr^s roauth2_requestzOAuth2Mixin.oauth2_requestvsJ '3H^ $ OOD !  3//99 9C((*  !ZZF)?)? )J(H"ZZ_,H!!(--00 -s$BC  C C $C %$C  C c*tjS)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 rzr|s rr:z OAuth2Mixin.get_auth_http_clients))++r)NNNNNr)NNNNNr)rrrrrrrr r rrrrrr{r:rrrrr+sU '+#''+15%)#'0sm'0C='0 } '0 tCH~. '0 S " '0'0 '0V'+#''+"15 %sm%C=% } % sm % tCH~. % %2'+.2 31 31sm31DcN+ 31  31 31j,j&@&@,rrc eZdZdZdZdZdZdZdZdZ dd e e d dfd Z dd e d e e efde e e efded ef dZd e e effdZd e e efd e e effdZy) TwitterMixinaTwitter 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/authenticateFzhttps://api.twitter.com/1.1NrrcK|j}|j|j|d{}|j|jd|y7"w)aJust 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. )rN)r:r;rr_OAUTH_AUTHENTICATE_URL)r*rrr^s rr.z"TwitterMixin.authenticate_redirectsY ((*  ) )| ) D   t;;T8L s5AA#Apathrrr,cK|jds|jdr|}n|j|zdz}|rTi}|j||j|xsi|dnd}|j||||}|j||r%|dtj j |zz }|j} |:| j|dtj j | d{} n| j|d{} tj| jS7=7%w) 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. zhttp:zhttps:z.jsonNr4r)r6r!r5) re_TWITTER_BASE_URLrVrr'r(r)r:r;rrr7) r*rrrr,r?rr6oauthrr^s rtwitter_requestzTwitterMixin.twitter_requests-Z ??7 #tx'@C((4/'9C H OOD ! OOIO ,(4V%F22\8F3E KK   3//55 5C((*  !ZZF)?)? )J(H"ZZ_,H!!(--00 -s$C;D?=D;>D?D=$D?=D?ctt|}|jdd|jddt|jd|jdS)Ntwitter_consumer_keyz Twitter OAuthtwitter_consumer_secretr)r rrequire_settingrtsettingsr*r+s rrz"TwitterMixin._oauth_consumer_token?s[~t, 6H 9?K  !78##$=>  rc\K|jd|d{}|r|d|d<|S7w)Nz/account/verify_credentials)r screen_namer)r)r*rrvs rrz#TwitterMixin._oauth_get_user_futureHsE)) ) *   #M2D   s ,*,r~)rrrrrrrrrrrrrr.r r rrrrrrrrs!F MJDJ5M MQUM4/3 F1F138nF1DcN+ F1  F1 F1P tCH~  cN c3hrrc reZdZdZdZdZdZdZdZde e e ffdZ dd e d e d e e d e e de e e ff dZy )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_oauthrcTtt|}|j|jS)aReturn 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 rr_OAUTH_SETTINGS_KEYrs rget_google_oauth_settingsz+GoogleOAuth2Mixin.get_google_oauth_settingsqs'~t, 8 899rNrrrrcLK|||j}||d}||d}|j}tjj ||||dd}|j |j dddi| d{}tj|jS7#w) 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. Nrurauthorization_code)rrrr grant_typer4z Content-Typez!application/x-www-form-urlencoded)r6headersr7) rr:r'r(r)r;rrrr7) r*rrrrrrr7r^s rrAz(GoogleOAuth2Mixin.get_authenticated_userst   5557H $UO $ ( 2 ((*||%% ,&!.2     ( (#%HI $   !!(--00  sAB"?$B$r)rrrrrr_OAUTH_USERINFO_URLrrr rrrrr rArrrrrSs.JJI(:4S>:($('+ Q1Q1Q1C= Q1  } Q1 c3h Q1rrceZdZdZdZdZdZdZ ddeded ed ed e e ee fd e e ee ff d Z ddede ede e ee fde d e f dZ y)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?Fzhttps://graph.facebook.comNrrrr extra_fieldsrc K|j}||||d}hd}|r|j||j|jd i|d{} t j | j }|jd|jdd} | dJ|jd| dtj|jd| djdtj jd j| d{} | yi} |D]} | j| | | <| j| dt!| jdd | S7!7Xw)aHandles 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 `_ .. 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. )rrrr>idlinkrrppicturermrlNr expires_in)rrz/mer)rumsg digestmodrR)rrappsecret_prooffields)rsession_expiresr)r:rVr;rrrr7getfacebook_requesthmacnewencodehashlibsha256 hexdigestrYrr)r*rrrrr rr,rr^sessionrvfieldmapfields rrAz)FacebookGraphMixin.get_authenticated_usersj((*("*  X  MM, ' )D ) ) 1D 1  !!(--0 HH^4((<0 ~&222** 0 HH!((0N+226:!..ik88F#+    < .E"hhuoHUO .  ' 7#&w{{<'@#A  M   s&AE;E6C E; E9!AE;9E;rrrr,chK|j|z}|j|f||d|d{S7w)aFetches 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. )rrN)_FACEBOOK_BASE_URLr)r*rrrr,r?s rrz#FacebookGraphMixin.facebook_requestFsMl%%,(T((  *i CG    s )202r~r)rrrrrrrr rrrr r rArrrrrrsENC526 ggg g  g tCH~. g $sCx. !gX'+.2 9 9 sm9 DcN+ 9  9 9 rrrr6r?rrrc tjj|}|dd\}}}|jdz|jz|z} g} | j |j | j | | j dj dt|jDdj d| D} tj|dg} | j tj|r|dndd j | } tj| tj| tj}tj |j#dd S) zxCalculates the HMAC-SHA1 OAuth signature for the given request. See http://oauth.net/core/1.0/#signing_process N://&c3TK|] \}}|dtt|"yw=N _oauth_escaperrrr=r>s rrz#_oauth_signature..)WDAqA3a c!f-./W&(c32K|]}t|ywr~r)res rrz#_oauth_signature..@=+@rrb&r1)r'r(urlparsersrXupperrYsortedr9rrrrrsha1r b2a_base64digestrr6r?rrpartsschemenetlocrnormalized_url base_elems base_string key_elemsruhashs rrrs5 LL ! !# &E !9FFD\\^e+flln.r+r,c32K|]}t|ywr~r.r/s rrz&_oauth10a_signature..r1r2r~saferbr3r1)r'r(r4rsrXr5rYr6r9rrquoterrrr7rr8r9r:s rrrsc LL ! !# &E !9FFD\\^e+flln.s$=!AW,r\s 6p  '%&CCC  ~,~,BI,I,XH,H,VZ:Zz1 1Dj j b"$&* 3cN3 3 3S#X 3 DcN # 3  3F"$&* 3cN3 3 3S#X 3 DcN # 3  3B-uS%Z(-S-  $sCx. r