def authorize_redirect(self, callback_uri=None, extra_params=None, http_client=None, callback=None): """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`. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. Use the returned awaitable object instead. """ if callback_uri and getattr(self, "_OAUTH_NO_CALLBACKS", False): raise Exception("This service does not support oauth_callback") if http_client is None: http_client = self.get_auth_http_client() if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a": fut = http_client.fetch( self._oauth_request_token_url(callback_uri=callback_uri, extra_params=extra_params)) fut.add_done_callback(wrap(functools.partial( self._on_request_token, self._OAUTH_AUTHORIZE_URL, callback_uri, callback))) else: fut = http_client.fetch(self._oauth_request_token_url()) fut.add_done_callback( wrap(functools.partial( self._on_request_token, self._OAUTH_AUTHORIZE_URL, callback_uri, callback)))
def call_at(self, when, callback, *args, **kwargs): # asyncio.call_at supports *args but not **kwargs, so bind them here. # We do not synchronize self.time and asyncio_loop.time, so # convert from absolute to relative. return self.asyncio_loop.call_later( max(0, when - self.time()), self._run_callback, functools.partial(stack_context.wrap(callback), *args, **kwargs))
def get_authenticated_user(self, callback, http_client=None): """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. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. Use the returned awaitable object instead. """ # Verify the OpenID response via direct request to the OP args = dict((k, v[-1]) for k, v in self.request.arguments.items()) args["openid.mode"] = u"check_authentication" url = self._OPENID_ENDPOINT if http_client is None: http_client = self.get_auth_http_client() fut = http_client.fetch(url, method="POST", body=urllib_parse.urlencode(args)) fut.add_done_callback(wrap(functools.partial( self._on_authentication_verified, callback)))
def call_at(self, deadline, callback, *args, **kwargs): timeout = _Timeout( deadline, functools.partial(stack_context.wrap(callback), *args, **kwargs), self) heapq.heappush(self._timeouts, timeout) return timeout
def get_authenticated_user(self, redirect_uri, code, callback): """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: .. testcode:: class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): async def get(self): if self.get_argument('code', False): access = await self.get_authenticated_user( redirect_uri='http://your.site.com/auth/google', 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 with # e.g. set_secure_cookie. else: await self.authorize_redirect( redirect_uri='http://your.site.com/auth/google', client_id=self.settings['google_oauth']['key'], scope=['profile', 'email'], response_type='code', extra_params={'approval_prompt': 'auto'}) .. testoutput:: :hide: .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. Use the returned awaitable object instead. """ # noqa: E501 http = self.get_auth_http_client() body = urllib_parse.urlencode({ "redirect_uri": redirect_uri, "code": code, "client_id": self.settings[self._OAUTH_SETTINGS_KEY]['key'], "client_secret": self.settings[self._OAUTH_SETTINGS_KEY]['secret'], "grant_type": "authorization_code", }) fut = http.fetch(self._OAUTH_ACCESS_TOKEN_URL, method="POST", headers={'Content-Type': 'application/x-www-form-urlencoded'}, body=body) fut.add_done_callback(wrap(functools.partial(self._on_access_token, callback)))
def add_handler(self, fd, handler, events): if fd in self.fds: raise ValueError('fd %s added twice' % fd) fd, fileobj = self.split_fd(fd) self.fds[fd] = _FD(fd, fileobj, wrap(handler)) if events & tornado_py2.ioloop.IOLoop.READ: self.fds[fd].reading = True self.reactor.addReader(self.fds[fd]) if events & tornado_py2.ioloop.IOLoop.WRITE: self.fds[fd].writing = True self.reactor.addWriter(self.fds[fd])
def _on_access_token(self, future, response_fut): try: response = response_fut.result() except Exception: future.set_exception(AuthError("Could not fetch access token")) return access_token = _oauth_parse_response(response.body) fut = self._oauth_get_user_future(access_token) fut = gen.convert_yielded(fut) fut.add_done_callback( wrap(functools.partial(self._on_oauth_get_user, access_token, future)))
def wrapper(*args, **kwargs): future = Future() callback, args, kwargs = replacer.replace( lambda value=_NO_RESULT: future_set_result_unless_cancelled(future, value), args, kwargs) def handle_error(typ, value, tb): future_set_exc_info(future, (typ, value, tb)) return True exc_info = None esc = ExceptionStackContext(handle_error, delay_warning=True) with esc: if not warn: # HACK: In non-deprecated mode (only used in auth.py), # suppress the warning entirely. Since this is added # in a 5.1 patch release and already removed in 6.0 # I'm prioritizing a minimial change instead of a # clean solution. esc.delay_warning = False try: result = f(*args, **kwargs) if result is not None: raise ReturnValueIgnoredError( "@return_future should not be used with functions " "that return values") except: exc_info = sys.exc_info() raise if exc_info is not None: # If the initial synchronous part of f() raised an exception, # go ahead and raise it to the caller directly without waiting # for them to inspect the Future. future.result() # If the caller passed in a callback, schedule it to be called # when the future resolves. It is important that this happens # just before we return the future, or else we risk confusing # stack contexts with multiple exceptions (one here with the # immediate exception, and again when the future resolves and # the callback triggers its exception by calling future.result()). if callback is not None: warnings.warn("callback arguments are deprecated, use the returned Future instead", DeprecationWarning) def run_callback(future): result = future.result() if result is _NO_RESULT: callback() else: callback(future.result()) future_add_done_callback(future, wrap(run_callback)) return future
def wrapper(*args, **kwargs): future = func(*args, **kwargs) def final_callback(future): if future.result() is not None: raise ReturnValueIgnoredError( "@gen.engine functions cannot return values: %r" % (future.result(), )) # The engine interface doesn't give us any way to return # errors but to raise them into the stack context. # Save the stack context here to use when the Future has resolved. future_add_done_callback(future, stack_context.wrap(final_callback))
def add_callback(self, callback, *args, **kwargs): try: self.asyncio_loop.call_soon_threadsafe( self._run_callback, functools.partial(stack_context.wrap(callback), *args, **kwargs)) except RuntimeError: # "Event loop is closed". Swallow the exception for # consistency with PollIOLoop (and logical consistency # with the fact that we can't guarantee that an # add_callback that completes without error will # eventually execute). pass
def add_timeout(self, deadline, callback, *args, **kwargs): # This method could be simplified (since tornado 4.0) by # overriding call_at instead of add_timeout, but we leave it # for now as a test of backwards-compatibility. if isinstance(deadline, numbers.Real): delay = max(deadline - self.time(), 0) elif isinstance(deadline, datetime.timedelta): delay = timedelta_to_seconds(deadline) else: raise TypeError("Unsupported deadline %r") return self.reactor.callLater( delay, self._run_callback, functools.partial(wrap(callback), *args, **kwargs))
def add_handler(self, fd, handler, events): fd, fileobj = self.split_fd(fd) if fd in self.handlers: raise ValueError("fd %s added twice" % fd) self.handlers[fd] = (fileobj, stack_context.wrap(handler)) if events & IOLoop.READ: self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ) self.readers.add(fd) if events & IOLoop.WRITE: self.asyncio_loop.add_writer(fd, self._handle_events, fd, IOLoop.WRITE) self.writers.add(fd)
def set_close_callback(self, callback): """Sets a callback that will be run when the connection is closed. Note that this callback is slightly different from `.HTTPMessageDelegate.on_connection_close`: The `.HTTPMessageDelegate` method is called when the connection is closed while recieving a message. This callback is used when there is not an active delegate (for example, on the server side this callback is used if the client closes the connection after sending its request but before receiving all the response. """ self._close_callback = stack_context.wrap(callback)
def oauth2_request(self, url, callback, access_token=None, post_args=None, **args): """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? await self.authorize_redirect() return self.finish("Posted a message!") .. testoutput:: :hide: .. versionadded:: 4.3 .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. Use the returned awaitable object instead. """ all_args = {} if access_token: all_args["access_token"] = access_token all_args.update(args) if all_args: url += "?" + urllib_parse.urlencode(all_args) callback = wrap(functools.partial(self._on_oauth2_request, callback)) http = self.get_auth_http_client() if post_args is not None: fut = http.fetch(url, method="POST", body=urllib_parse.urlencode(post_args)) else: fut = http.fetch(url) fut.add_done_callback(callback)
def add_callback(self, callback, *args, **kwargs): if self._closing: return # Blindly insert into self._callbacks. This is safe even # from signal handlers because deque.append is atomic. self._callbacks.append( functools.partial(stack_context.wrap(callback), *args, **kwargs)) if thread.get_ident() != self._thread_ident: # This will write one byte but Waker.consume() reads many # at once, so it's ok to write even when not strictly # necessary. self._waker.wake() else: # If we're on the IOLoop's thread, we don't need to wake anyone. pass
def add_future(self, future, callback): """Schedules a callback on the ``IOLoop`` when the given `.Future` is finished. The callback is invoked with one argument, the `.Future`. This method only accepts `.Future` objects and not other awaitables (unlike most of Tornado where the two are interchangeable). """ assert is_future(future) callback = stack_context.wrap(callback) future_add_done_callback( future, lambda future: self.add_callback(callback, future))
def wrapper(*args, **kwargs): future = Future() callback, args, kwargs = replacer.replace(future, args, kwargs) if callback is not None: warnings.warn("callback arguments are deprecated, use the returned Future instead", DeprecationWarning) future.add_done_callback( wrap(functools.partial(_auth_future_to_callback, callback))) def handle_exception(typ, value, tb): if future.done(): return False else: future_set_exc_info(future, (typ, value, tb)) return True with ExceptionStackContext(handle_exception, delay_warning=True): f(*args, **kwargs) return future
def set_exit_callback(self, callback): """Runs ``callback`` when this process exits. The callback takes one argument, the return code of the process. This method uses a ``SIGCHLD`` handler, which is a global setting and may conflict if you have other libraries trying to handle the same signal. If you are using more than one ``IOLoop`` it may be necessary to call `Subprocess.initialize` first to designate one ``IOLoop`` to run the signal handlers. In many cases a close callback on the stdout or stderr streams can be used as an alternative to an exit callback if the signal handler is causing a problem. """ self._exit_callback = stack_context.wrap(callback) Subprocess.initialize() Subprocess._waiting[self.pid] = self Subprocess._try_cleanup_process(self.pid)
def authenticate_redirect(self, callback_uri=None, callback=None): """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`. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. Use the returned awaitable object instead. """ http = self.get_auth_http_client() fut = http.fetch(self._oauth_request_token_url(callback_uri=callback_uri)) fut.add_done_callback(wrap(functools.partial( self._on_request_token, self._OAUTH_AUTHENTICATE_URL, None, callback)))
def get_authenticated_user(self, callback, http_client=None): """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. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. Use the returned awaitable object instead. """ future = callback request_key = escape.utf8(self.get_argument("oauth_token")) oauth_verifier = self.get_argument("oauth_verifier", None) request_cookie = self.get_cookie("_oauth_request_token") if not request_cookie: future.set_exception(AuthError( "Missing OAuth request token cookie")) return self.clear_cookie("_oauth_request_token") cookie_key, cookie_secret = [ base64.b64decode(escape.utf8(i)) for i in request_cookie.split("|")] if cookie_key != request_key: future.set_exception(AuthError( "Request token does not match cookie")) return token = dict(key=cookie_key, secret=cookie_secret) if oauth_verifier: token["verifier"] = oauth_verifier if http_client is None: http_client = self.get_auth_http_client() fut = http_client.fetch(self._oauth_access_token_url(token)) fut.add_done_callback(wrap(functools.partial(self._on_access_token, callback)))
def write(self, chunk, callback=None): """Implements `.HTTPConnection.write`. For backwards compatibility it is allowed but deprecated to skip `write_headers` and instead call `write()` with a pre-encoded header block. """ future = None if self.stream.closed(): future = self._write_future = Future() self._write_future.set_exception(iostream.StreamClosedError()) self._write_future.exception() else: if callback is not None: warnings.warn( "callback argument is deprecated, use returned Future instead", DeprecationWarning) self._write_callback = stack_context.wrap(callback) else: future = self._write_future = Future() self._pending_write = self.stream.write(self._format_chunk(chunk)) self._pending_write.add_done_callback(self._on_write_complete) return future
def prepare_curl_callback(self, value): self._prepare_curl_callback = stack_context.wrap(value)
def body_producer(self, value): self._body_producer = stack_context.wrap(value)
def twitter_request(self, path, callback=None, access_token=None, post_args=None, **args): """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? yield self.authorize_redirect() return self.finish("Posted a message!") .. testoutput:: :hide: .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. Use the returned awaitable object instead. """ if path.startswith('http:') or path.startswith('https:'): # Raw urls are useful for e.g. search which doesn't follow the # usual pattern: http://search.twitter.com/search.json url = path else: url = self._TWITTER_BASE_URL + path + ".json" # Add the OAuth resource request signature if we have credentials if access_token: all_args = {} all_args.update(args) all_args.update(post_args or {}) method = "POST" if post_args is not None else "GET" oauth = self._oauth_request_parameters( url, access_token, all_args, method=method) args.update(oauth) if args: url += "?" + urllib_parse.urlencode(args) http = self.get_auth_http_client() http_callback = wrap(functools.partial(self._on_twitter_request, callback, url)) if post_args is not None: fut = http.fetch(url, method="POST", body=urllib_parse.urlencode(post_args)) else: fut = http.fetch(url) fut.add_done_callback(http_callback)
def write_headers(self, start_line, headers, chunk=None, callback=None): """Implements `.HTTPConnection.write_headers`.""" lines = [] if self.is_client: self._request_start_line = start_line lines.append( utf8('%s %s HTTP/1.1' % (start_line[0], start_line[1]))) # Client requests with a non-empty body must have either a # Content-Length or a Transfer-Encoding. self._chunking_output = (start_line.method in ('POST', 'PUT', 'PATCH') and 'Content-Length' not in headers and 'Transfer-Encoding' not in headers) else: self._response_start_line = start_line lines.append( utf8('HTTP/1.1 %d %s' % (start_line[1], start_line[2]))) self._chunking_output = ( # TODO: should this use # self._request_start_line.version or # start_line.version? self._request_start_line.version == 'HTTP/1.1' and # 1xx, 204 and 304 responses have no body (not even a zero-length # body), and so should not have either Content-Length or # Transfer-Encoding headers. start_line.code not in (204, 304) and (start_line.code < 100 or start_line.code >= 200) and # No need to chunk the output if a Content-Length is specified. 'Content-Length' not in headers and # Applications are discouraged from touching Transfer-Encoding, # but if they do, leave it alone. 'Transfer-Encoding' not in headers) # If connection to a 1.1 client will be closed, inform client if (self._request_start_line.version == 'HTTP/1.1' and self._disconnect_on_finish): headers['Connection'] = 'close' # If a 1.0 client asked for keep-alive, add the header. if (self._request_start_line.version == 'HTTP/1.0' and self._request_headers.get('Connection', '').lower() == 'keep-alive'): headers['Connection'] = 'Keep-Alive' if self._chunking_output: headers['Transfer-Encoding'] = 'chunked' if (not self.is_client and (self._request_start_line.method == 'HEAD' or start_line.code == 304)): self._expected_content_remaining = 0 elif 'Content-Length' in headers: self._expected_content_remaining = int(headers['Content-Length']) else: self._expected_content_remaining = None # TODO: headers are supposed to be of type str, but we still have some # cases that let bytes slip through. Remove these native_str calls when those # are fixed. header_lines = (native_str(n) + ": " + native_str(v) for n, v in headers.get_all()) if PY3: lines.extend(l.encode('latin1') for l in header_lines) else: lines.extend(header_lines) for line in lines: if b'\n' in line: raise ValueError('Newline in header: ' + repr(line)) future = None if self.stream.closed(): future = self._write_future = Future() future.set_exception(iostream.StreamClosedError()) future.exception() else: if callback is not None: warnings.warn( "callback argument is deprecated, use returned Future instead", DeprecationWarning) self._write_callback = stack_context.wrap(callback) else: future = self._write_future = Future() data = b"\r\n".join(lines) + b"\r\n\r\n" if chunk: data += self._format_chunk(chunk) self._pending_write = self.stream.write(data) future_add_done_callback(self._pending_write, self._on_write_complete) return future
def streaming_callback(self, value): self._streaming_callback = stack_context.wrap(value)
def add_parse_callback(self, callback): """Adds a parse callback, to be invoked when option parsing is done.""" self._parse_callbacks.append(stack_context.wrap(callback))
def get_authenticated_user(self, redirect_uri, client_id, client_secret, code, callback, extra_fields=None): """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): if self.get_argument("code", False): user = await self.get_authenticated_user( redirect_uri='/auth/facebookgraph/', 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_secure_cookie else: await self.authorize_redirect( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], extra_params={"scope": "read_stream,offline_access"}) .. testoutput:: :hide: 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. .. deprecated:: 5.1 The ``callback`` argument is deprecated and will be removed in 6.0. Use the returned awaitable object instead. """ http = self.get_auth_http_client() args = { "redirect_uri": redirect_uri, "code": code, "client_id": client_id, "client_secret": client_secret, } fields = set(['id', 'name', 'first_name', 'last_name', 'locale', 'picture', 'link']) if extra_fields: fields.update(extra_fields) fut = http.fetch(self._oauth_request_token_url(**args)) fut.add_done_callback(wrap(functools.partial(self._on_access_token, redirect_uri, client_id, client_secret, callback, fields)))
def add_callback(self, callback, *args, **kwargs): self.reactor.callFromThread( self._run_callback, functools.partial(wrap(callback), *args, **kwargs))
def header_callback(self, value): self._header_callback = stack_context.wrap(value)