{
    "file_diffs": [
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"This module contains implementations of various third-party\nauthentication schemes.\n\nAll the classes in this file are class mixins designed to be used with\nthe `tornado.web.RequestHandler` class.  They are used in two ways:\n\n* On a login handler, use methods such as ``authenticate_redirect()``,\n  ``authorize_redirect()``, and ``get_authenticated_user()`` to\n  establish the user's identity and store authentication tokens to your\n  database and/or cookies.\n* In non-login handlers, use methods such as ``facebook_request()``\n  or ``twitter_request()`` to use the authentication tokens to make\n  requests to the respective services.\n\nThey all take slightly different arguments due to the fact all these\nservices implement authentication and authorization slightly differently.\nSee the individual service classes below for complete documentation.\n\nExample usage for Google OAuth:\n\n.. testcode::\n\n    class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n                                   tornado.auth.GoogleOAuth2Mixin):\n        @tornado.gen.coroutine\n        def get(self):\n            if self.get_argument('code', False):\n                user = yield self.get_authenticated_user(\n                    redirect_uri='http://your.site.com/auth/google',\n                    code=self.get_argument('code'))\n                # Save the user with e.g. set_secure_cookie\n            else:\n                yield self.authorize_redirect(\n                    redirect_uri='http://your.site.com/auth/google',\n                    client_id=self.settings['google_oauth']['key'],\n                    scope=['profile', 'email'],\n                    response_type='code',\n                    extra_params={'approval_prompt': 'auto'})\n\n.. testoutput::\n   :hide:\n\n\n.. versionchanged:: 4.0\n   All of the callback interfaces in this module are now guaranteed\n   to run their callback with an argument of ``None`` on error.\n   Previously some functions would do this while others would simply\n   terminate the request on their own.  This change also ensures that\n   errors are more consistently reported through the ``Future`` interfaces.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport base64\nimport binascii\nimport functools\nimport hashlib\nimport hmac\nimport time\nimport uuid\n\nfrom tornado.concurrent import TracebackFuture, return_future\nfrom tornado import gen\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.log import gen_log\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.util import u, unicode_type, ArgReplacer\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\ntry:\n    import urllib.parse as urllib_parse  # py3\nexcept ImportError:\n    import urllib as urllib_parse  # py2\n\ntry:\n    long  # py2\nexcept NameError:\n    long = int  # py3\n\n\nclass AuthError(Exception):\n    pass\n\n\ndef _auth_future_to_callback(callback, future):\n    try:\n        result = future.result()\n    except AuthError as e:\n        gen_log.warning(str(e))\n        result = None\n    callback(result)\n\n\ndef _auth_return_future(f):\n    \"\"\"Similar to tornado.concurrent.return_future, but uses the auth\n    module's legacy callback interface.\n\n    Note that when using this decorator the ``callback`` parameter\n    inside the function will actually be a future.\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = TracebackFuture()\n        callback, args, kwargs = replacer.replace(future, args, kwargs)\n        if callback is not None:\n            future.add_done_callback(\n                functools.partial(_auth_future_to_callback, callback))\n\n        def handle_exception(typ, value, tb):\n            if future.done():\n                return False\n            else:\n                future.set_exc_info((typ, value, tb))\n                return True\n        with ExceptionStackContext(handle_exception):\n            f(*args, **kwargs)\n        return future\n    return wrapper\n\n\nclass OpenIdMixin(object):\n    \"\"\"Abstract implementation of OpenID and Attribute Exchange.\n\n    Class attributes:\n\n    * ``_OPENID_ENDPOINT``: the identity provider's URI.\n    \"\"\"\n    @return_future\n    def authenticate_redirect(self, callback_uri=None,\n                              ax_attrs=[\"name\", \"email\", \"language\", \"username\"],\n                              callback=None):\n        \"\"\"Redirects to the authentication URL for this service.\n\n        After authentication, the service will redirect back to the given\n        callback URI with additional parameters including ``openid.mode``.\n\n        We request the given attributes for the authenticated user by\n        default (name, email, language, and username). If you don't need\n        all those attributes for your app, you can request fewer with\n        the ax_attrs keyword argument.\n\n        .. versionchanged:: 3.1\n           Returns a `.Future` and takes an optional callback.  These are\n           not strictly necessary as this method is synchronous,\n           but they are supplied for consistency with\n           `OAuthMixin.authorize_redirect`.\n        \"\"\"\n        callback_uri = callback_uri or self.request.uri\n        args = self._openid_args(callback_uri, ax_attrs=ax_attrs)\n        self.redirect(self._OPENID_ENDPOINT + \"?\" + urllib_parse.urlencode(args))\n        callback()\n\n    @_auth_return_future\n    def get_authenticated_user(self, callback, http_client=None):\n        \"\"\"Fetches the authenticated user data upon redirect.\n\n        This method should be called by the handler that receives the\n        redirect from the `authenticate_redirect()` method (which is\n        often the same as the one that calls it; in that case you would\n        call `get_authenticated_user` if the ``openid.mode`` parameter\n        is present and `authenticate_redirect` if it is not).\n\n        The result of this method will generally be used to set a cookie.\n        \"\"\"\n        # Verify the OpenID response via direct request to the OP\n        args = dict((k, v[-1]) for k, v in self.request.arguments.items())\n        args[\"openid.mode\"] = u(\"check_authentication\")\n        url = self._OPENID_ENDPOINT\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        http_client.fetch(url, functools.partial(\n            self._on_authentication_verified, callback),\n            method=\"POST\", body=urllib_parse.urlencode(args))\n\n    def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):\n        url = urlparse.urljoin(self.request.full_url(), callback_uri)\n        args = {\n            \"openid.ns\": \"http://specs.openid.net/auth/2.0\",\n            \"openid.claimed_id\":\n            \"http://specs.openid.net/auth/2.0/identifier_select\",\n            \"openid.identity\":\n            \"http://specs.openid.net/auth/2.0/identifier_select\",\n            \"openid.return_to\": url,\n            \"openid.realm\": urlparse.urljoin(url, '/'),\n            \"openid.mode\": \"checkid_setup\",\n        }\n        if ax_attrs:\n            args.update({\n                \"openid.ns.ax\": \"http://openid.net/srv/ax/1.0\",\n                \"openid.ax.mode\": \"fetch_request\",\n            })\n            ax_attrs = set(ax_attrs)\n            required = []\n            if \"name\" in ax_attrs:\n                ax_attrs -= set([\"name\", \"firstname\", \"fullname\", \"lastname\"])\n                required += [\"firstname\", \"fullname\", \"lastname\"]\n                args.update({\n                    \"openid.ax.type.firstname\":\n                    \"http://axschema.org/namePerson/first\",\n                    \"openid.ax.type.fullname\":\n                    \"http://axschema.org/namePerson\",\n                    \"openid.ax.type.lastname\":\n                    \"http://axschema.org/namePerson/last\",\n                })\n            known_attrs = {\n                \"email\": \"http://axschema.org/contact/email\",\n                \"language\": \"http://axschema.org/pref/language\",\n                \"username\": \"http://axschema.org/namePerson/friendly\",\n            }\n            for name in ax_attrs:\n                args[\"openid.ax.type.\" + name] = known_attrs[name]\n                required.append(name)\n            args[\"openid.ax.required\"] = \",\".join(required)\n        if oauth_scope:\n            args.update({\n                \"openid.ns.oauth\":\n                \"http://specs.openid.net/extensions/oauth/1.0\",\n                \"openid.oauth.consumer\": self.request.host.split(\":\")[0],\n                \"openid.oauth.scope\": oauth_scope,\n            })\n        return args\n\n    def _on_authentication_verified(self, future, response):\n        if response.error or b\"is_valid:true\" not in response.body:\n            future.set_exception(AuthError(\n                \"Invalid OpenID response: %s\" % (response.error or\n                                                 response.body)))\n            return\n\n        # Make sure we got back at least an email from attribute exchange\n        ax_ns = None\n        for name in self.request.arguments:\n            if name.startswith(\"openid.ns.\") and \\\n                    self.get_argument(name) == u(\"http://openid.net/srv/ax/1.0\"):\n                ax_ns = name[10:]\n                break\n\n        def get_ax_arg(uri):\n            if not ax_ns:\n                return u(\"\")\n            prefix = \"openid.\" + ax_ns + \".type.\"\n            ax_name = None\n            for name in self.request.arguments.keys():\n                if self.get_argument(name) == uri and name.startswith(prefix):\n                    part = name[len(prefix):]\n                    ax_name = \"openid.\" + ax_ns + \".value.\" + part\n                    break\n            if not ax_name:\n                return u(\"\")\n            return self.get_argument(ax_name, u(\"\"))\n\n        email = get_ax_arg(\"http://axschema.org/contact/email\")\n        name = get_ax_arg(\"http://axschema.org/namePerson\")\n        first_name = get_ax_arg(\"http://axschema.org/namePerson/first\")\n        last_name = get_ax_arg(\"http://axschema.org/namePerson/last\")\n        username = get_ax_arg(\"http://axschema.org/namePerson/friendly\")\n        locale = get_ax_arg(\"http://axschema.org/pref/language\").lower()\n        user = dict()\n        name_parts = []\n        if first_name:\n            user[\"first_name\"] = first_name\n            name_parts.append(first_name)\n        if last_name:\n            user[\"last_name\"] = last_name\n            name_parts.append(last_name)\n        if name:\n            user[\"name\"] = name\n        elif name_parts:\n            user[\"name\"] = u(\" \").join(name_parts)\n        elif email:\n            user[\"name\"] = email.split(\"@\")[0]\n        if email:\n            user[\"email\"] = email\n        if locale:\n            user[\"locale\"] = locale\n        if username:\n            user[\"username\"] = username\n        claimed_id = self.get_argument(\"openid.claimed_id\", None)\n        if claimed_id:\n            user[\"claimed_id\"] = claimed_id\n        future.set_result(user)\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass OAuthMixin(object):\n    \"\"\"Abstract implementation of OAuth 1.0 and 1.0a.\n\n    See `TwitterMixin` below for an example implementation.\n\n    Class attributes:\n\n    * ``_OAUTH_AUTHORIZE_URL``: The service's OAuth authorization url.\n    * ``_OAUTH_ACCESS_TOKEN_URL``: The service's OAuth access token url.\n    * ``_OAUTH_VERSION``: May be either \"1.0\" or \"1.0a\".\n    * ``_OAUTH_NO_CALLBACKS``: Set this to True if the service requires\n      advance registration of callbacks.\n\n    Subclasses must also override the `_oauth_get_user_future` and\n    `_oauth_consumer_token` methods.\n    \"\"\"\n    @return_future\n    def authorize_redirect(self, callback_uri=None, extra_params=None,\n                           http_client=None, callback=None):\n        \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n        The ``callback_uri`` may be omitted if you have previously\n        registered a callback URI with the third-party service.  For\n        some services (including Friendfeed), you must use a\n        previously-registered callback URI and cannot specify a\n        callback via this method.\n\n        This method sets a cookie called ``_oauth_request_token`` which is\n        subsequently used (and cleared) in `get_authenticated_user` for\n        security purposes.\n\n        Note that this method is asynchronous, although it calls\n        `.RequestHandler.finish` for you so it may not be necessary\n        to pass a callback or use the `.Future` it returns.  However,\n        if this method is called from a function decorated with\n        `.gen.coroutine`, you must call it with ``yield`` to keep the\n        response from being closed prematurely.\n\n        .. versionchanged:: 3.1\n           Now returns a `.Future` and takes an optional callback, for\n           compatibility with `.gen.coroutine`.\n        \"\"\"\n        if callback_uri and getattr(self, \"_OAUTH_NO_CALLBACKS\", False):\n            raise Exception(\"This service does not support oauth_callback\")\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            http_client.fetch(\n                self._oauth_request_token_url(callback_uri=callback_uri,\n                                              extra_params=extra_params),\n                functools.partial(\n                    self._on_request_token,\n                    self._OAUTH_AUTHORIZE_URL,\n                    callback_uri,\n                    callback))\n        else:\n            http_client.fetch(\n                self._oauth_request_token_url(),\n                functools.partial(\n                    self._on_request_token, self._OAUTH_AUTHORIZE_URL,\n                    callback_uri,\n                    callback))\n\n    @_auth_return_future\n    def get_authenticated_user(self, callback, http_client=None):\n        \"\"\"Gets the OAuth authorized user and access token.\n\n        This method should be called from the handler for your\n        OAuth callback URL to complete the registration process. We run the\n        callback with the authenticated user dictionary.  This dictionary\n        will contain an ``access_key`` which can be used to make authorized\n        requests to this service on behalf of the user.  The dictionary will\n        also contain other fields such as ``name``, depending on the service\n        used.\n        \"\"\"\n        future = callback\n        request_key = escape.utf8(self.get_argument(\"oauth_token\"))\n        oauth_verifier = self.get_argument(\"oauth_verifier\", None)\n        request_cookie = self.get_cookie(\"_oauth_request_token\")\n        if not request_cookie:\n            future.set_exception(AuthError(\n                \"Missing OAuth request token cookie\"))\n            return\n        self.clear_cookie(\"_oauth_request_token\")\n        cookie_key, cookie_secret = [base64.b64decode(escape.utf8(i)) for i in request_cookie.split(\"|\")]\n        if cookie_key != request_key:\n            future.set_exception(AuthError(\n                \"Request token does not match cookie\"))\n            return\n        token = dict(key=cookie_key, secret=cookie_secret)\n        if oauth_verifier:\n            token[\"verifier\"] = oauth_verifier\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        http_client.fetch(self._oauth_access_token_url(token),\n                          functools.partial(self._on_access_token, callback))\n\n    def _oauth_request_token_url(self, callback_uri=None, extra_params=None):\n        consumer_token = self._oauth_consumer_token()\n        url = self._OAUTH_REQUEST_TOKEN_URL\n        args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            if callback_uri == \"oob\":\n                args[\"oauth_callback\"] = \"oob\"\n            elif callback_uri:\n                args[\"oauth_callback\"] = urlparse.urljoin(\n                    self.request.full_url(), callback_uri)\n            if extra_params:\n                args.update(extra_params)\n            signature = _oauth10a_signature(consumer_token, \"GET\", url, args)\n        else:\n            signature = _oauth_signature(consumer_token, \"GET\", url, args)\n\n        args[\"oauth_signature\"] = signature\n        return url + \"?\" + urllib_parse.urlencode(args)\n\n    def _on_request_token(self, authorize_url, callback_uri, callback,\n                          response):\n        if response.error:\n            raise Exception(\"Could not get request token: %s\" % response.error)\n        request_token = _oauth_parse_response(response.body)\n        data = (base64.b64encode(escape.utf8(request_token[\"key\"])) + b\"|\" +\n                base64.b64encode(escape.utf8(request_token[\"secret\"])))\n        self.set_cookie(\"_oauth_request_token\", data)\n        args = dict(oauth_token=request_token[\"key\"])\n        if callback_uri == \"oob\":\n            self.finish(authorize_url + \"?\" + urllib_parse.urlencode(args))\n            callback()\n            return\n        elif callback_uri:\n            args[\"oauth_callback\"] = urlparse.urljoin(\n                self.request.full_url(), callback_uri)\n        self.redirect(authorize_url + \"?\" + urllib_parse.urlencode(args))\n        callback()\n\n    def _oauth_access_token_url(self, request_token):\n        consumer_token = self._oauth_consumer_token()\n        url = self._OAUTH_ACCESS_TOKEN_URL\n        args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_token=escape.to_basestring(request_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        if \"verifier\" in request_token:\n            args[\"oauth_verifier\"] = request_token[\"verifier\"]\n\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            signature = _oauth10a_signature(consumer_token, \"GET\", url, args,\n                                            request_token)\n        else:\n            signature = _oauth_signature(consumer_token, \"GET\", url, args,\n                                         request_token)\n\n        args[\"oauth_signature\"] = signature\n        return url + \"?\" + urllib_parse.urlencode(args)\n\n    def _on_access_token(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\"Could not fetch access token\"))\n            return\n\n        access_token = _oauth_parse_response(response.body)\n        self._oauth_get_user_future(access_token).add_done_callback(\n            functools.partial(self._on_oauth_get_user, access_token, future))\n\n    def _oauth_consumer_token(self):\n        \"\"\"Subclasses must override this to return their OAuth consumer keys.\n\n        The return value should be a `dict` with keys ``key`` and ``secret``.\n        \"\"\"\n        raise NotImplementedError()\n\n    @return_future\n    def _oauth_get_user_future(self, access_token, callback):\n        \"\"\"Subclasses must override this to get basic information about the\n        user.\n\n        Should return a `.Future` whose result is a dictionary\n        containing information about the user, which may have been\n        retrieved by using ``access_token`` to make a request to the\n        service.\n\n        The access token will be added to the returned dictionary to make\n        the result of `get_authenticated_user`.\n\n        For backwards compatibility, the callback-based ``_oauth_get_user``\n        method is also supported.\n        \"\"\"\n        # By default, call the old-style _oauth_get_user, but new code\n        # should override this method instead.\n        self._oauth_get_user(access_token, callback)\n\n    def _oauth_get_user(self, access_token, callback):\n        raise NotImplementedError()\n\n    def _on_oauth_get_user(self, access_token, future, user_future):\n        if user_future.exception() is not None:\n            future.set_exception(user_future.exception())\n            return\n        user = user_future.result()\n        if not user:\n            future.set_exception(AuthError(\"Error getting user\"))\n            return\n        user[\"access_token\"] = access_token\n        future.set_result(user)\n\n    def _oauth_request_parameters(self, url, access_token, parameters={},\n                                  method=\"GET\"):\n        \"\"\"Returns the OAuth parameters as a dict for the given request.\n\n        parameters should include all POST arguments and query string arguments\n        that will be sent with the request.\n        \"\"\"\n        consumer_token = self._oauth_consumer_token()\n        base_args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_token=escape.to_basestring(access_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        args = {}\n        args.update(base_args)\n        args.update(parameters)\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            signature = _oauth10a_signature(consumer_token, method, url, args,\n                                            access_token)\n        else:\n            signature = _oauth_signature(consumer_token, method, url, args,\n                                         access_token)\n        base_args[\"oauth_signature\"] = escape.to_basestring(signature)\n        return base_args\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass OAuth2Mixin(object):\n    \"\"\"Abstract implementation of OAuth 2.0.\n\n    See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example\n    implementations.\n\n    Class attributes:\n\n    * ``_OAUTH_AUTHORIZE_URL``: The service's authorization url.\n    * ``_OAUTH_ACCESS_TOKEN_URL``:  The service's access token url.\n    \"\"\"\n    @return_future\n    def authorize_redirect(self, redirect_uri=None, client_id=None,\n                           client_secret=None, extra_params=None,\n                           callback=None, scope=None, response_type=\"code\"):\n        \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n        Some providers require that you register a redirect URL with\n        your application instead of passing one via this method. You\n        should call this method to log the user in, and then call\n        ``get_authenticated_user`` in the handler for your\n        redirect URL to complete the authorization process.\n\n        .. versionchanged:: 3.1\n           Returns a `.Future` and takes an optional callback.  These are\n           not strictly necessary as this method is synchronous,\n           but they are supplied for consistency with\n           `OAuthMixin.authorize_redirect`.\n        \"\"\"\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"client_id\": client_id,\n            \"response_type\": response_type\n        }\n        if extra_params:\n            args.update(extra_params)\n        if scope:\n            args['scope'] = ' '.join(scope)\n        self.redirect(\n            url_concat(self._OAUTH_AUTHORIZE_URL, args))\n        callback()\n\n    def _oauth_request_token_url(self, redirect_uri=None, client_id=None,\n                                 client_secret=None, code=None,\n                                 extra_params=None):\n        url = self._OAUTH_ACCESS_TOKEN_URL\n        args = dict(\n            redirect_uri=redirect_uri,\n            code=code,\n            client_id=client_id,\n            client_secret=client_secret,\n        )\n        if extra_params:\n            args.update(extra_params)\n        return url_concat(url, args)\n\n    @_auth_return_future\n    def oauth2_request(self, url, callback, access_token=None,\n                       post_args=None, **args):\n        \"\"\"Fetches the given URL auth an OAuth2 access token.\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.oauth2_request(\n                        \"https://graph.facebook.com/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        .. versionadded:: 4.3\n        \"\"\"\n        all_args = {}\n        if access_token:\n            all_args[\"access_token\"] = access_token\n            all_args.update(args)\n\n        if all_args:\n            url += \"?\" + urllib_parse.urlencode(all_args)\n        callback = functools.partial(self._on_oauth2_request, callback)\n        http = self.get_auth_http_client()\n        if post_args is not None:\n            http.fetch(url, method=\"POST\", body=urllib_parse.urlencode(post_args),\n                       callback=callback)\n        else:\n            http.fetch(url, callback=callback)\n\n    def _on_oauth2_request(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\"Error response %s fetching %s\" %\n                                           (response.error, response.request.url)))\n            return\n\n        future.set_result(escape.json_decode(response.body))\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n\n        .. versionadded:: 4.3\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass TwitterMixin(OAuthMixin):\n    \"\"\"Twitter OAuth authentication.\n\n    To authenticate with Twitter, register your application with\n    Twitter at http://twitter.com/apps. Then copy your Consumer Key\n    and Consumer Secret to the application\n    `~tornado.web.Application.settings` ``twitter_consumer_key`` and\n    ``twitter_consumer_secret``. Use this mixin on the handler for the\n    URL you registered as your application's callback URL.\n\n    When your application is set up, you can use this mixin like this\n    to authenticate the user with Twitter and get access to their stream:\n\n    .. testcode::\n\n        class TwitterLoginHandler(tornado.web.RequestHandler,\n                                  tornado.auth.TwitterMixin):\n            @tornado.gen.coroutine\n            def get(self):\n                if self.get_argument(\"oauth_token\", None):\n                    user = yield self.get_authenticated_user()\n                    # Save the user using e.g. set_secure_cookie()\n                else:\n                    yield self.authorize_redirect()\n\n    .. testoutput::\n       :hide:\n\n    The user object returned by `~OAuthMixin.get_authenticated_user`\n    includes the attributes ``username``, ``name``, ``access_token``,\n    and all of the custom Twitter user attributes described at\n    https://dev.twitter.com/docs/api/1.1/get/users/show\n    \"\"\"\n    _OAUTH_REQUEST_TOKEN_URL = \"https://api.twitter.com/oauth/request_token\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://api.twitter.com/oauth/access_token\"\n    _OAUTH_AUTHORIZE_URL = \"https://api.twitter.com/oauth/authorize\"\n    _OAUTH_AUTHENTICATE_URL = \"https://api.twitter.com/oauth/authenticate\"\n    _OAUTH_NO_CALLBACKS = False\n    _TWITTER_BASE_URL = \"https://api.twitter.com/1.1\"\n\n    @return_future\n    def authenticate_redirect(self, callback_uri=None, callback=None):\n        \"\"\"Just like `~OAuthMixin.authorize_redirect`, but\n        auto-redirects if authorized.\n\n        This is generally the right interface to use if you are using\n        Twitter for single-sign on.\n\n        .. versionchanged:: 3.1\n           Now returns a `.Future` and takes an optional callback, for\n           compatibility with `.gen.coroutine`.\n        \"\"\"\n        http = self.get_auth_http_client()\n        http.fetch(self._oauth_request_token_url(callback_uri=callback_uri),\n                   functools.partial(\n                       self._on_request_token, self._OAUTH_AUTHENTICATE_URL,\n                       None, callback))\n\n    @_auth_return_future\n    def twitter_request(self, path, callback=None, access_token=None,\n                        post_args=None, **args):\n        \"\"\"Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``\n\n        The path should not include the format or API version number.\n        (we automatically use JSON format and API version 1).\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        All the Twitter methods are documented at http://dev.twitter.com/\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuthMixin.authorize_redirect` and\n        `~OAuthMixin.get_authenticated_user`. The user returned through that\n        process includes an 'access_token' attribute that can be used\n        to make authenticated requests via this method. Example\n        usage:\n\n        .. testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.TwitterMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.twitter_request(\n                        \"/statuses/update\",\n                        post_args={\"status\": \"Testing Tornado Web Server\"},\n                        access_token=self.current_user[\"access_token\"])\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        if path.startswith('http:') or path.startswith('https:'):\n            # Raw urls are useful for e.g. search which doesn't follow the\n            # usual pattern: http://search.twitter.com/search.json\n            url = path\n        else:\n            url = self._TWITTER_BASE_URL + path + \".json\"\n        # Add the OAuth resource request signature if we have credentials\n        if access_token:\n            all_args = {}\n            all_args.update(args)\n            all_args.update(post_args or {})\n            method = \"POST\" if post_args is not None else \"GET\"\n            oauth = self._oauth_request_parameters(\n                url, access_token, all_args, method=method)\n            args.update(oauth)\n        if args:\n            url += \"?\" + urllib_parse.urlencode(args)\n        http = self.get_auth_http_client()\n        http_callback = functools.partial(self._on_twitter_request, callback)\n        if post_args is not None:\n            http.fetch(url, method=\"POST\", body=urllib_parse.urlencode(post_args),\n                       callback=http_callback)\n        else:\n            http.fetch(url, callback=http_callback)\n\n    def _on_twitter_request(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\n                \"Error response %s fetching %s\" % (response.error,\n                                                   response.request.url)))\n            return\n        future.set_result(escape.json_decode(response.body))\n\n    def _oauth_consumer_token(self):\n        self.require_setting(\"twitter_consumer_key\", \"Twitter OAuth\")\n        self.require_setting(\"twitter_consumer_secret\", \"Twitter OAuth\")\n        return dict(\n            key=self.settings[\"twitter_consumer_key\"],\n            secret=self.settings[\"twitter_consumer_secret\"])\n\n    @gen.coroutine\n    def _oauth_get_user_future(self, access_token):\n        user = yield self.twitter_request(\n            \"/account/verify_credentials\",\n            access_token=access_token)\n        if user:\n            user[\"username\"] = user[\"screen_name\"]\n        raise gen.Return(user)\n\n\nclass GoogleOAuth2Mixin(OAuth2Mixin):\n    \"\"\"Google authentication using OAuth2.\n\n    In order to use, register your application with Google and copy the\n    relevant parameters to your application settings.\n\n    * Go to the Google Dev Console at http://console.developers.google.com\n    * Select a project, or create a new one.\n    * In the sidebar on the left, select APIs & Auth.\n    * In the list of APIs, find the Google+ API service and set it to ON.\n    * In the sidebar on the left, select Credentials.\n    * In the OAuth section of the page, select Create New Client ID.\n    * Set the Redirect URI to point to your auth handler\n    * Copy the \"Client secret\" and \"Client ID\" to the application settings as\n      {\"google_oauth\": {\"key\": CLIENT_ID, \"secret\": CLIENT_SECRET}}\n\n    .. versionadded:: 3.2\n    \"\"\"\n    _OAUTH_AUTHORIZE_URL = \"https://accounts.google.com/o/oauth2/auth\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://accounts.google.com/o/oauth2/token\"\n    _OAUTH_USERINFO_URL = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n    _OAUTH_NO_CALLBACKS = False\n    _OAUTH_SETTINGS_KEY = 'google_oauth'\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, code, callback):\n        \"\"\"Handles the login for the Google user, returning an access token.\n\n        The result is a dictionary containing an ``access_token`` field\n        ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).\n        Unlike other ``get_authenticated_user`` methods in this package,\n        this method does not return any additional information about the user.\n        The returned access token can be used with `OAuth2Mixin.oauth2_request`\n        to request additional information (perhaps from\n        ``https://www.googleapis.com/oauth2/v2/userinfo``)\n\n        Example usage:\n\n        .. testcode::\n\n            class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n                                           tornado.auth.GoogleOAuth2Mixin):\n                @tornado.gen.coroutine\n                def get(self):\n                    if self.get_argument('code', False):\n                        access = yield self.get_authenticated_user(\n                            redirect_uri='http://your.site.com/auth/google',\n                            code=self.get_argument('code'))\n                        user = yield self.oauth2_request(\n                            \"https://www.googleapis.com/oauth2/v1/userinfo\",\n                            access_token=access[\"access_token\"])\n                        # Save the user and access token with\n                        # e.g. set_secure_cookie.\n                    else:\n                        yield self.authorize_redirect(\n                            redirect_uri='http://your.site.com/auth/google',\n                            client_id=self.settings['google_oauth']['key'],\n                            scope=['profile', 'email'],\n                            response_type='code',\n                            extra_params={'approval_prompt': 'auto'})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        body = urllib_parse.urlencode({\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": self.settings[self._OAUTH_SETTINGS_KEY]['key'],\n            \"client_secret\": self.settings[self._OAUTH_SETTINGS_KEY]['secret'],\n            \"grant_type\": \"authorization_code\",\n        })\n\n        http.fetch(self._OAUTH_ACCESS_TOKEN_URL,\n                   functools.partial(self._on_access_token, callback),\n                   method=\"POST\", headers={'Content-Type': 'application/x-www-form-urlencoded'}, body=body)\n\n    def _on_access_token(self, future, response):\n        \"\"\"Callback function for the exchange to the access token.\"\"\"\n        if response.error:\n            future.set_exception(AuthError('Google auth error: %s' % str(response)))\n            return\n\n        args = escape.json_decode(response.body)\n        future.set_result(args)\n\n\nclass FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = escape.parse_qs_bytes(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        return self.oauth2_request(url, callback, access_token,\n                                   post_args, **args)\n\n\ndef _oauth_signature(consumer_token, method, url, parameters={}, token=None):\n    \"\"\"Calculates the HMAC-SHA1 OAuth signature for the given request.\n\n    See http://oauth.net/core/1.0/#signing_process\n    \"\"\"\n    parts = urlparse.urlparse(url)\n    scheme, netloc, path = parts[:3]\n    normalized_url = scheme.lower() + \"://\" + netloc.lower() + path\n\n    base_elems = []\n    base_elems.append(method.upper())\n    base_elems.append(normalized_url)\n    base_elems.append(\"&\".join(\"%s=%s\" % (k, _oauth_escape(str(v)))\n                               for k, v in sorted(parameters.items())))\n    base_string = \"&\".join(_oauth_escape(e) for e in base_elems)\n\n    key_elems = [escape.utf8(consumer_token[\"secret\"])]\n    key_elems.append(escape.utf8(token[\"secret\"] if token else \"\"))\n    key = b\"&\".join(key_elems)\n\n    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)\n    return binascii.b2a_base64(hash.digest())[:-1]\n\n\ndef _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):\n    \"\"\"Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.\n\n    See http://oauth.net/core/1.0a/#signing_process\n    \"\"\"\n    parts = urlparse.urlparse(url)\n    scheme, netloc, path = parts[:3]\n    normalized_url = scheme.lower() + \"://\" + netloc.lower() + path\n\n    base_elems = []\n    base_elems.append(method.upper())\n    base_elems.append(normalized_url)\n    base_elems.append(\"&\".join(\"%s=%s\" % (k, _oauth_escape(str(v)))\n                               for k, v in sorted(parameters.items())))\n\n    base_string = \"&\".join(_oauth_escape(e) for e in base_elems)\n    key_elems = [escape.utf8(urllib_parse.quote(consumer_token[\"secret\"], safe='~'))]\n    key_elems.append(escape.utf8(urllib_parse.quote(token[\"secret\"], safe='~') if token else \"\"))\n    key = b\"&\".join(key_elems)\n\n    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)\n    return binascii.b2a_base64(hash.digest())[:-1]\n\n\ndef _oauth_escape(val):\n    if isinstance(val, unicode_type):\n        val = val.encode(\"utf-8\")\n    return urllib_parse.quote(val, safe=\"~\")\n\n\ndef _oauth_parse_response(body):\n    # I can't find an officially-defined encoding for oauth responses and\n    # have never seen anyone use non-ascii.  Leave the response in a byte\n    # string for python 2, and use utf8 on python 3.\n    body = escape.native_str(body)\n    p = urlparse.parse_qs(body, keep_blank_values=False)\n    token = dict(key=p[\"oauth_token\"][0], secret=p[\"oauth_token_secret\"][0])\n\n    # Add the extra parameters the Provider included to the token\n    special = (\"oauth_token\", \"oauth_token_secret\")\n    token.update((k, p[k][0]) for k in p if k not in special)\n    return token\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"This module contains implementations of various third-party\nauthentication schemes.\n\nAll the classes in this file are class mixins designed to be used with\nthe `tornado.web.RequestHandler` class.  They are used in two ways:\n\n* On a login handler, use methods such as ``authenticate_redirect()``,\n  ``authorize_redirect()``, and ``get_authenticated_user()`` to\n  establish the user's identity and store authentication tokens to your\n  database and/or cookies.\n* In non-login handlers, use methods such as ``facebook_request()``\n  or ``twitter_request()`` to use the authentication tokens to make\n  requests to the respective services.\n\nThey all take slightly different arguments due to the fact all these\nservices implement authentication and authorization slightly differently.\nSee the individual service classes below for complete documentation.\n\nExample usage for Google OAuth:\n\n.. testcode::\n\n    class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n                                   tornado.auth.GoogleOAuth2Mixin):\n        @tornado.gen.coroutine\n        def get(self):\n            if self.get_argument('code', False):\n                user = yield self.get_authenticated_user(\n                    redirect_uri='http://your.site.com/auth/google',\n                    code=self.get_argument('code'))\n                # Save the user with e.g. set_secure_cookie\n            else:\n                yield self.authorize_redirect(\n                    redirect_uri='http://your.site.com/auth/google',\n                    client_id=self.settings['google_oauth']['key'],\n                    scope=['profile', 'email'],\n                    response_type='code',\n                    extra_params={'approval_prompt': 'auto'})\n\n.. testoutput::\n   :hide:\n\n\n.. versionchanged:: 4.0\n   All of the callback interfaces in this module are now guaranteed\n   to run their callback with an argument of ``None`` on error.\n   Previously some functions would do this while others would simply\n   terminate the request on their own.  This change also ensures that\n   errors are more consistently reported through the ``Future`` interfaces.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport base64\nimport binascii\nimport functools\nimport hashlib\nimport hmac\nimport time\nimport uuid\n\nfrom tornado.concurrent import TracebackFuture, return_future, chain_future\nfrom tornado import gen\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.log import gen_log\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.util import u, unicode_type, ArgReplacer\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\ntry:\n    import urllib.parse as urllib_parse  # py3\nexcept ImportError:\n    import urllib as urllib_parse  # py2\n\ntry:\n    long  # py2\nexcept NameError:\n    long = int  # py3\n\n\nclass AuthError(Exception):\n    pass\n\n\ndef _auth_future_to_callback(callback, future):\n    try:\n        result = future.result()\n    except AuthError as e:\n        gen_log.warning(str(e))\n        result = None\n    callback(result)\n\n\ndef _auth_return_future(f):\n    \"\"\"Similar to tornado.concurrent.return_future, but uses the auth\n    module's legacy callback interface.\n\n    Note that when using this decorator the ``callback`` parameter\n    inside the function will actually be a future.\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = TracebackFuture()\n        callback, args, kwargs = replacer.replace(future, args, kwargs)\n        if callback is not None:\n            future.add_done_callback(\n                functools.partial(_auth_future_to_callback, callback))\n\n        def handle_exception(typ, value, tb):\n            if future.done():\n                return False\n            else:\n                future.set_exc_info((typ, value, tb))\n                return True\n        with ExceptionStackContext(handle_exception):\n            f(*args, **kwargs)\n        return future\n    return wrapper\n\n\nclass OpenIdMixin(object):\n    \"\"\"Abstract implementation of OpenID and Attribute Exchange.\n\n    Class attributes:\n\n    * ``_OPENID_ENDPOINT``: the identity provider's URI.\n    \"\"\"\n    @return_future\n    def authenticate_redirect(self, callback_uri=None,\n                              ax_attrs=[\"name\", \"email\", \"language\", \"username\"],\n                              callback=None):\n        \"\"\"Redirects to the authentication URL for this service.\n\n        After authentication, the service will redirect back to the given\n        callback URI with additional parameters including ``openid.mode``.\n\n        We request the given attributes for the authenticated user by\n        default (name, email, language, and username). If you don't need\n        all those attributes for your app, you can request fewer with\n        the ax_attrs keyword argument.\n\n        .. versionchanged:: 3.1\n           Returns a `.Future` and takes an optional callback.  These are\n           not strictly necessary as this method is synchronous,\n           but they are supplied for consistency with\n           `OAuthMixin.authorize_redirect`.\n        \"\"\"\n        callback_uri = callback_uri or self.request.uri\n        args = self._openid_args(callback_uri, ax_attrs=ax_attrs)\n        self.redirect(self._OPENID_ENDPOINT + \"?\" + urllib_parse.urlencode(args))\n        callback()\n\n    @_auth_return_future\n    def get_authenticated_user(self, callback, http_client=None):\n        \"\"\"Fetches the authenticated user data upon redirect.\n\n        This method should be called by the handler that receives the\n        redirect from the `authenticate_redirect()` method (which is\n        often the same as the one that calls it; in that case you would\n        call `get_authenticated_user` if the ``openid.mode`` parameter\n        is present and `authenticate_redirect` if it is not).\n\n        The result of this method will generally be used to set a cookie.\n        \"\"\"\n        # Verify the OpenID response via direct request to the OP\n        args = dict((k, v[-1]) for k, v in self.request.arguments.items())\n        args[\"openid.mode\"] = u(\"check_authentication\")\n        url = self._OPENID_ENDPOINT\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        http_client.fetch(url, functools.partial(\n            self._on_authentication_verified, callback),\n            method=\"POST\", body=urllib_parse.urlencode(args))\n\n    def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):\n        url = urlparse.urljoin(self.request.full_url(), callback_uri)\n        args = {\n            \"openid.ns\": \"http://specs.openid.net/auth/2.0\",\n            \"openid.claimed_id\":\n            \"http://specs.openid.net/auth/2.0/identifier_select\",\n            \"openid.identity\":\n            \"http://specs.openid.net/auth/2.0/identifier_select\",\n            \"openid.return_to\": url,\n            \"openid.realm\": urlparse.urljoin(url, '/'),\n            \"openid.mode\": \"checkid_setup\",\n        }\n        if ax_attrs:\n            args.update({\n                \"openid.ns.ax\": \"http://openid.net/srv/ax/1.0\",\n                \"openid.ax.mode\": \"fetch_request\",\n            })\n            ax_attrs = set(ax_attrs)\n            required = []\n            if \"name\" in ax_attrs:\n                ax_attrs -= set([\"name\", \"firstname\", \"fullname\", \"lastname\"])\n                required += [\"firstname\", \"fullname\", \"lastname\"]\n                args.update({\n                    \"openid.ax.type.firstname\":\n                    \"http://axschema.org/namePerson/first\",\n                    \"openid.ax.type.fullname\":\n                    \"http://axschema.org/namePerson\",\n                    \"openid.ax.type.lastname\":\n                    \"http://axschema.org/namePerson/last\",\n                })\n            known_attrs = {\n                \"email\": \"http://axschema.org/contact/email\",\n                \"language\": \"http://axschema.org/pref/language\",\n                \"username\": \"http://axschema.org/namePerson/friendly\",\n            }\n            for name in ax_attrs:\n                args[\"openid.ax.type.\" + name] = known_attrs[name]\n                required.append(name)\n            args[\"openid.ax.required\"] = \",\".join(required)\n        if oauth_scope:\n            args.update({\n                \"openid.ns.oauth\":\n                \"http://specs.openid.net/extensions/oauth/1.0\",\n                \"openid.oauth.consumer\": self.request.host.split(\":\")[0],\n                \"openid.oauth.scope\": oauth_scope,\n            })\n        return args\n\n    def _on_authentication_verified(self, future, response):\n        if response.error or b\"is_valid:true\" not in response.body:\n            future.set_exception(AuthError(\n                \"Invalid OpenID response: %s\" % (response.error or\n                                                 response.body)))\n            return\n\n        # Make sure we got back at least an email from attribute exchange\n        ax_ns = None\n        for name in self.request.arguments:\n            if name.startswith(\"openid.ns.\") and \\\n                    self.get_argument(name) == u(\"http://openid.net/srv/ax/1.0\"):\n                ax_ns = name[10:]\n                break\n\n        def get_ax_arg(uri):\n            if not ax_ns:\n                return u(\"\")\n            prefix = \"openid.\" + ax_ns + \".type.\"\n            ax_name = None\n            for name in self.request.arguments.keys():\n                if self.get_argument(name) == uri and name.startswith(prefix):\n                    part = name[len(prefix):]\n                    ax_name = \"openid.\" + ax_ns + \".value.\" + part\n                    break\n            if not ax_name:\n                return u(\"\")\n            return self.get_argument(ax_name, u(\"\"))\n\n        email = get_ax_arg(\"http://axschema.org/contact/email\")\n        name = get_ax_arg(\"http://axschema.org/namePerson\")\n        first_name = get_ax_arg(\"http://axschema.org/namePerson/first\")\n        last_name = get_ax_arg(\"http://axschema.org/namePerson/last\")\n        username = get_ax_arg(\"http://axschema.org/namePerson/friendly\")\n        locale = get_ax_arg(\"http://axschema.org/pref/language\").lower()\n        user = dict()\n        name_parts = []\n        if first_name:\n            user[\"first_name\"] = first_name\n            name_parts.append(first_name)\n        if last_name:\n            user[\"last_name\"] = last_name\n            name_parts.append(last_name)\n        if name:\n            user[\"name\"] = name\n        elif name_parts:\n            user[\"name\"] = u(\" \").join(name_parts)\n        elif email:\n            user[\"name\"] = email.split(\"@\")[0]\n        if email:\n            user[\"email\"] = email\n        if locale:\n            user[\"locale\"] = locale\n        if username:\n            user[\"username\"] = username\n        claimed_id = self.get_argument(\"openid.claimed_id\", None)\n        if claimed_id:\n            user[\"claimed_id\"] = claimed_id\n        future.set_result(user)\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass OAuthMixin(object):\n    \"\"\"Abstract implementation of OAuth 1.0 and 1.0a.\n\n    See `TwitterMixin` below for an example implementation.\n\n    Class attributes:\n\n    * ``_OAUTH_AUTHORIZE_URL``: The service's OAuth authorization url.\n    * ``_OAUTH_ACCESS_TOKEN_URL``: The service's OAuth access token url.\n    * ``_OAUTH_VERSION``: May be either \"1.0\" or \"1.0a\".\n    * ``_OAUTH_NO_CALLBACKS``: Set this to True if the service requires\n      advance registration of callbacks.\n\n    Subclasses must also override the `_oauth_get_user_future` and\n    `_oauth_consumer_token` methods.\n    \"\"\"\n    @return_future\n    def authorize_redirect(self, callback_uri=None, extra_params=None,\n                           http_client=None, callback=None):\n        \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n        The ``callback_uri`` may be omitted if you have previously\n        registered a callback URI with the third-party service.  For\n        some services (including Friendfeed), you must use a\n        previously-registered callback URI and cannot specify a\n        callback via this method.\n\n        This method sets a cookie called ``_oauth_request_token`` which is\n        subsequently used (and cleared) in `get_authenticated_user` for\n        security purposes.\n\n        Note that this method is asynchronous, although it calls\n        `.RequestHandler.finish` for you so it may not be necessary\n        to pass a callback or use the `.Future` it returns.  However,\n        if this method is called from a function decorated with\n        `.gen.coroutine`, you must call it with ``yield`` to keep the\n        response from being closed prematurely.\n\n        .. versionchanged:: 3.1\n           Now returns a `.Future` and takes an optional callback, for\n           compatibility with `.gen.coroutine`.\n        \"\"\"\n        if callback_uri and getattr(self, \"_OAUTH_NO_CALLBACKS\", False):\n            raise Exception(\"This service does not support oauth_callback\")\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            http_client.fetch(\n                self._oauth_request_token_url(callback_uri=callback_uri,\n                                              extra_params=extra_params),\n                functools.partial(\n                    self._on_request_token,\n                    self._OAUTH_AUTHORIZE_URL,\n                    callback_uri,\n                    callback))\n        else:\n            http_client.fetch(\n                self._oauth_request_token_url(),\n                functools.partial(\n                    self._on_request_token, self._OAUTH_AUTHORIZE_URL,\n                    callback_uri,\n                    callback))\n\n    @_auth_return_future\n    def get_authenticated_user(self, callback, http_client=None):\n        \"\"\"Gets the OAuth authorized user and access token.\n\n        This method should be called from the handler for your\n        OAuth callback URL to complete the registration process. We run the\n        callback with the authenticated user dictionary.  This dictionary\n        will contain an ``access_key`` which can be used to make authorized\n        requests to this service on behalf of the user.  The dictionary will\n        also contain other fields such as ``name``, depending on the service\n        used.\n        \"\"\"\n        future = callback\n        request_key = escape.utf8(self.get_argument(\"oauth_token\"))\n        oauth_verifier = self.get_argument(\"oauth_verifier\", None)\n        request_cookie = self.get_cookie(\"_oauth_request_token\")\n        if not request_cookie:\n            future.set_exception(AuthError(\n                \"Missing OAuth request token cookie\"))\n            return\n        self.clear_cookie(\"_oauth_request_token\")\n        cookie_key, cookie_secret = [base64.b64decode(escape.utf8(i)) for i in request_cookie.split(\"|\")]\n        if cookie_key != request_key:\n            future.set_exception(AuthError(\n                \"Request token does not match cookie\"))\n            return\n        token = dict(key=cookie_key, secret=cookie_secret)\n        if oauth_verifier:\n            token[\"verifier\"] = oauth_verifier\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        http_client.fetch(self._oauth_access_token_url(token),\n                          functools.partial(self._on_access_token, callback))\n\n    def _oauth_request_token_url(self, callback_uri=None, extra_params=None):\n        consumer_token = self._oauth_consumer_token()\n        url = self._OAUTH_REQUEST_TOKEN_URL\n        args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            if callback_uri == \"oob\":\n                args[\"oauth_callback\"] = \"oob\"\n            elif callback_uri:\n                args[\"oauth_callback\"] = urlparse.urljoin(\n                    self.request.full_url(), callback_uri)\n            if extra_params:\n                args.update(extra_params)\n            signature = _oauth10a_signature(consumer_token, \"GET\", url, args)\n        else:\n            signature = _oauth_signature(consumer_token, \"GET\", url, args)\n\n        args[\"oauth_signature\"] = signature\n        return url + \"?\" + urllib_parse.urlencode(args)\n\n    def _on_request_token(self, authorize_url, callback_uri, callback,\n                          response):\n        if response.error:\n            raise Exception(\"Could not get request token: %s\" % response.error)\n        request_token = _oauth_parse_response(response.body)\n        data = (base64.b64encode(escape.utf8(request_token[\"key\"])) + b\"|\" +\n                base64.b64encode(escape.utf8(request_token[\"secret\"])))\n        self.set_cookie(\"_oauth_request_token\", data)\n        args = dict(oauth_token=request_token[\"key\"])\n        if callback_uri == \"oob\":\n            self.finish(authorize_url + \"?\" + urllib_parse.urlencode(args))\n            callback()\n            return\n        elif callback_uri:\n            args[\"oauth_callback\"] = urlparse.urljoin(\n                self.request.full_url(), callback_uri)\n        self.redirect(authorize_url + \"?\" + urllib_parse.urlencode(args))\n        callback()\n\n    def _oauth_access_token_url(self, request_token):\n        consumer_token = self._oauth_consumer_token()\n        url = self._OAUTH_ACCESS_TOKEN_URL\n        args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_token=escape.to_basestring(request_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        if \"verifier\" in request_token:\n            args[\"oauth_verifier\"] = request_token[\"verifier\"]\n\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            signature = _oauth10a_signature(consumer_token, \"GET\", url, args,\n                                            request_token)\n        else:\n            signature = _oauth_signature(consumer_token, \"GET\", url, args,\n                                         request_token)\n\n        args[\"oauth_signature\"] = signature\n        return url + \"?\" + urllib_parse.urlencode(args)\n\n    def _on_access_token(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\"Could not fetch access token\"))\n            return\n\n        access_token = _oauth_parse_response(response.body)\n        self._oauth_get_user_future(access_token).add_done_callback(\n            functools.partial(self._on_oauth_get_user, access_token, future))\n\n    def _oauth_consumer_token(self):\n        \"\"\"Subclasses must override this to return their OAuth consumer keys.\n\n        The return value should be a `dict` with keys ``key`` and ``secret``.\n        \"\"\"\n        raise NotImplementedError()\n\n    @return_future\n    def _oauth_get_user_future(self, access_token, callback):\n        \"\"\"Subclasses must override this to get basic information about the\n        user.\n\n        Should return a `.Future` whose result is a dictionary\n        containing information about the user, which may have been\n        retrieved by using ``access_token`` to make a request to the\n        service.\n\n        The access token will be added to the returned dictionary to make\n        the result of `get_authenticated_user`.\n\n        For backwards compatibility, the callback-based ``_oauth_get_user``\n        method is also supported.\n        \"\"\"\n        # By default, call the old-style _oauth_get_user, but new code\n        # should override this method instead.\n        self._oauth_get_user(access_token, callback)\n\n    def _oauth_get_user(self, access_token, callback):\n        raise NotImplementedError()\n\n    def _on_oauth_get_user(self, access_token, future, user_future):\n        if user_future.exception() is not None:\n            future.set_exception(user_future.exception())\n            return\n        user = user_future.result()\n        if not user:\n            future.set_exception(AuthError(\"Error getting user\"))\n            return\n        user[\"access_token\"] = access_token\n        future.set_result(user)\n\n    def _oauth_request_parameters(self, url, access_token, parameters={},\n                                  method=\"GET\"):\n        \"\"\"Returns the OAuth parameters as a dict for the given request.\n\n        parameters should include all POST arguments and query string arguments\n        that will be sent with the request.\n        \"\"\"\n        consumer_token = self._oauth_consumer_token()\n        base_args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_token=escape.to_basestring(access_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        args = {}\n        args.update(base_args)\n        args.update(parameters)\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            signature = _oauth10a_signature(consumer_token, method, url, args,\n                                            access_token)\n        else:\n            signature = _oauth_signature(consumer_token, method, url, args,\n                                         access_token)\n        base_args[\"oauth_signature\"] = escape.to_basestring(signature)\n        return base_args\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass OAuth2Mixin(object):\n    \"\"\"Abstract implementation of OAuth 2.0.\n\n    See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example\n    implementations.\n\n    Class attributes:\n\n    * ``_OAUTH_AUTHORIZE_URL``: The service's authorization url.\n    * ``_OAUTH_ACCESS_TOKEN_URL``:  The service's access token url.\n    \"\"\"\n    @return_future\n    def authorize_redirect(self, redirect_uri=None, client_id=None,\n                           client_secret=None, extra_params=None,\n                           callback=None, scope=None, response_type=\"code\"):\n        \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n        Some providers require that you register a redirect URL with\n        your application instead of passing one via this method. You\n        should call this method to log the user in, and then call\n        ``get_authenticated_user`` in the handler for your\n        redirect URL to complete the authorization process.\n\n        .. versionchanged:: 3.1\n           Returns a `.Future` and takes an optional callback.  These are\n           not strictly necessary as this method is synchronous,\n           but they are supplied for consistency with\n           `OAuthMixin.authorize_redirect`.\n        \"\"\"\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"client_id\": client_id,\n            \"response_type\": response_type\n        }\n        if extra_params:\n            args.update(extra_params)\n        if scope:\n            args['scope'] = ' '.join(scope)\n        self.redirect(\n            url_concat(self._OAUTH_AUTHORIZE_URL, args))\n        callback()\n\n    def _oauth_request_token_url(self, redirect_uri=None, client_id=None,\n                                 client_secret=None, code=None,\n                                 extra_params=None):\n        url = self._OAUTH_ACCESS_TOKEN_URL\n        args = dict(\n            redirect_uri=redirect_uri,\n            code=code,\n            client_id=client_id,\n            client_secret=client_secret,\n        )\n        if extra_params:\n            args.update(extra_params)\n        return url_concat(url, args)\n\n    @_auth_return_future\n    def oauth2_request(self, url, callback, access_token=None,\n                       post_args=None, **args):\n        \"\"\"Fetches the given URL auth an OAuth2 access token.\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.oauth2_request(\n                        \"https://graph.facebook.com/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        .. versionadded:: 4.3\n        \"\"\"\n        all_args = {}\n        if access_token:\n            all_args[\"access_token\"] = access_token\n            all_args.update(args)\n\n        if all_args:\n            url += \"?\" + urllib_parse.urlencode(all_args)\n        callback = functools.partial(self._on_oauth2_request, callback)\n        http = self.get_auth_http_client()\n        if post_args is not None:\n            http.fetch(url, method=\"POST\", body=urllib_parse.urlencode(post_args),\n                       callback=callback)\n        else:\n            http.fetch(url, callback=callback)\n\n    def _on_oauth2_request(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\"Error response %s fetching %s\" %\n                                           (response.error, response.request.url)))\n            return\n\n        future.set_result(escape.json_decode(response.body))\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n\n        .. versionadded:: 4.3\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass TwitterMixin(OAuthMixin):\n    \"\"\"Twitter OAuth authentication.\n\n    To authenticate with Twitter, register your application with\n    Twitter at http://twitter.com/apps. Then copy your Consumer Key\n    and Consumer Secret to the application\n    `~tornado.web.Application.settings` ``twitter_consumer_key`` and\n    ``twitter_consumer_secret``. Use this mixin on the handler for the\n    URL you registered as your application's callback URL.\n\n    When your application is set up, you can use this mixin like this\n    to authenticate the user with Twitter and get access to their stream:\n\n    .. testcode::\n\n        class TwitterLoginHandler(tornado.web.RequestHandler,\n                                  tornado.auth.TwitterMixin):\n            @tornado.gen.coroutine\n            def get(self):\n                if self.get_argument(\"oauth_token\", None):\n                    user = yield self.get_authenticated_user()\n                    # Save the user using e.g. set_secure_cookie()\n                else:\n                    yield self.authorize_redirect()\n\n    .. testoutput::\n       :hide:\n\n    The user object returned by `~OAuthMixin.get_authenticated_user`\n    includes the attributes ``username``, ``name``, ``access_token``,\n    and all of the custom Twitter user attributes described at\n    https://dev.twitter.com/docs/api/1.1/get/users/show\n    \"\"\"\n    _OAUTH_REQUEST_TOKEN_URL = \"https://api.twitter.com/oauth/request_token\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://api.twitter.com/oauth/access_token\"\n    _OAUTH_AUTHORIZE_URL = \"https://api.twitter.com/oauth/authorize\"\n    _OAUTH_AUTHENTICATE_URL = \"https://api.twitter.com/oauth/authenticate\"\n    _OAUTH_NO_CALLBACKS = False\n    _TWITTER_BASE_URL = \"https://api.twitter.com/1.1\"\n\n    @return_future\n    def authenticate_redirect(self, callback_uri=None, callback=None):\n        \"\"\"Just like `~OAuthMixin.authorize_redirect`, but\n        auto-redirects if authorized.\n\n        This is generally the right interface to use if you are using\n        Twitter for single-sign on.\n\n        .. versionchanged:: 3.1\n           Now returns a `.Future` and takes an optional callback, for\n           compatibility with `.gen.coroutine`.\n        \"\"\"\n        http = self.get_auth_http_client()\n        http.fetch(self._oauth_request_token_url(callback_uri=callback_uri),\n                   functools.partial(\n                       self._on_request_token, self._OAUTH_AUTHENTICATE_URL,\n                       None, callback))\n\n    @_auth_return_future\n    def twitter_request(self, path, callback=None, access_token=None,\n                        post_args=None, **args):\n        \"\"\"Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``\n\n        The path should not include the format or API version number.\n        (we automatically use JSON format and API version 1).\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        All the Twitter methods are documented at http://dev.twitter.com/\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuthMixin.authorize_redirect` and\n        `~OAuthMixin.get_authenticated_user`. The user returned through that\n        process includes an 'access_token' attribute that can be used\n        to make authenticated requests via this method. Example\n        usage:\n\n        .. testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.TwitterMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.twitter_request(\n                        \"/statuses/update\",\n                        post_args={\"status\": \"Testing Tornado Web Server\"},\n                        access_token=self.current_user[\"access_token\"])\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        if path.startswith('http:') or path.startswith('https:'):\n            # Raw urls are useful for e.g. search which doesn't follow the\n            # usual pattern: http://search.twitter.com/search.json\n            url = path\n        else:\n            url = self._TWITTER_BASE_URL + path + \".json\"\n        # Add the OAuth resource request signature if we have credentials\n        if access_token:\n            all_args = {}\n            all_args.update(args)\n            all_args.update(post_args or {})\n            method = \"POST\" if post_args is not None else \"GET\"\n            oauth = self._oauth_request_parameters(\n                url, access_token, all_args, method=method)\n            args.update(oauth)\n        if args:\n            url += \"?\" + urllib_parse.urlencode(args)\n        http = self.get_auth_http_client()\n        http_callback = functools.partial(self._on_twitter_request, callback)\n        if post_args is not None:\n            http.fetch(url, method=\"POST\", body=urllib_parse.urlencode(post_args),\n                       callback=http_callback)\n        else:\n            http.fetch(url, callback=http_callback)\n\n    def _on_twitter_request(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\n                \"Error response %s fetching %s\" % (response.error,\n                                                   response.request.url)))\n            return\n        future.set_result(escape.json_decode(response.body))\n\n    def _oauth_consumer_token(self):\n        self.require_setting(\"twitter_consumer_key\", \"Twitter OAuth\")\n        self.require_setting(\"twitter_consumer_secret\", \"Twitter OAuth\")\n        return dict(\n            key=self.settings[\"twitter_consumer_key\"],\n            secret=self.settings[\"twitter_consumer_secret\"])\n\n    @gen.coroutine\n    def _oauth_get_user_future(self, access_token):\n        user = yield self.twitter_request(\n            \"/account/verify_credentials\",\n            access_token=access_token)\n        if user:\n            user[\"username\"] = user[\"screen_name\"]\n        raise gen.Return(user)\n\n\nclass GoogleOAuth2Mixin(OAuth2Mixin):\n    \"\"\"Google authentication using OAuth2.\n\n    In order to use, register your application with Google and copy the\n    relevant parameters to your application settings.\n\n    * Go to the Google Dev Console at http://console.developers.google.com\n    * Select a project, or create a new one.\n    * In the sidebar on the left, select APIs & Auth.\n    * In the list of APIs, find the Google+ API service and set it to ON.\n    * In the sidebar on the left, select Credentials.\n    * In the OAuth section of the page, select Create New Client ID.\n    * Set the Redirect URI to point to your auth handler\n    * Copy the \"Client secret\" and \"Client ID\" to the application settings as\n      {\"google_oauth\": {\"key\": CLIENT_ID, \"secret\": CLIENT_SECRET}}\n\n    .. versionadded:: 3.2\n    \"\"\"\n    _OAUTH_AUTHORIZE_URL = \"https://accounts.google.com/o/oauth2/auth\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://accounts.google.com/o/oauth2/token\"\n    _OAUTH_USERINFO_URL = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n    _OAUTH_NO_CALLBACKS = False\n    _OAUTH_SETTINGS_KEY = 'google_oauth'\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, code, callback):\n        \"\"\"Handles the login for the Google user, returning an access token.\n\n        The result is a dictionary containing an ``access_token`` field\n        ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).\n        Unlike other ``get_authenticated_user`` methods in this package,\n        this method does not return any additional information about the user.\n        The returned access token can be used with `OAuth2Mixin.oauth2_request`\n        to request additional information (perhaps from\n        ``https://www.googleapis.com/oauth2/v2/userinfo``)\n\n        Example usage:\n\n        .. testcode::\n\n            class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n                                           tornado.auth.GoogleOAuth2Mixin):\n                @tornado.gen.coroutine\n                def get(self):\n                    if self.get_argument('code', False):\n                        access = yield self.get_authenticated_user(\n                            redirect_uri='http://your.site.com/auth/google',\n                            code=self.get_argument('code'))\n                        user = yield self.oauth2_request(\n                            \"https://www.googleapis.com/oauth2/v1/userinfo\",\n                            access_token=access[\"access_token\"])\n                        # Save the user and access token with\n                        # e.g. set_secure_cookie.\n                    else:\n                        yield self.authorize_redirect(\n                            redirect_uri='http://your.site.com/auth/google',\n                            client_id=self.settings['google_oauth']['key'],\n                            scope=['profile', 'email'],\n                            response_type='code',\n                            extra_params={'approval_prompt': 'auto'})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        body = urllib_parse.urlencode({\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": self.settings[self._OAUTH_SETTINGS_KEY]['key'],\n            \"client_secret\": self.settings[self._OAUTH_SETTINGS_KEY]['secret'],\n            \"grant_type\": \"authorization_code\",\n        })\n\n        http.fetch(self._OAUTH_ACCESS_TOKEN_URL,\n                   functools.partial(self._on_access_token, callback),\n                   method=\"POST\", headers={'Content-Type': 'application/x-www-form-urlencoded'}, body=body)\n\n    def _on_access_token(self, future, response):\n        \"\"\"Callback function for the exchange to the access token.\"\"\"\n        if response.error:\n            future.set_exception(AuthError('Google auth error: %s' % str(response)))\n            return\n\n        args = escape.json_decode(response.body)\n        future.set_result(args)\n\n\nclass FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = urlparse.parse_qs(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        # Thanks to the _auth_return_future decorator, our \"callback\"\n        # argument is a Future, which we cannot pass as a callback to\n        # oauth2_request. Instead, have oauth2_request return a\n        # future and chain them together.\n        oauth_future = self.oauth2_request(url, access_token=access_token,\n                                           post_args=post_args, **args)\n        chain_future(oauth_future, callback)\n\n\ndef _oauth_signature(consumer_token, method, url, parameters={}, token=None):\n    \"\"\"Calculates the HMAC-SHA1 OAuth signature for the given request.\n\n    See http://oauth.net/core/1.0/#signing_process\n    \"\"\"\n    parts = urlparse.urlparse(url)\n    scheme, netloc, path = parts[:3]\n    normalized_url = scheme.lower() + \"://\" + netloc.lower() + path\n\n    base_elems = []\n    base_elems.append(method.upper())\n    base_elems.append(normalized_url)\n    base_elems.append(\"&\".join(\"%s=%s\" % (k, _oauth_escape(str(v)))\n                               for k, v in sorted(parameters.items())))\n    base_string = \"&\".join(_oauth_escape(e) for e in base_elems)\n\n    key_elems = [escape.utf8(consumer_token[\"secret\"])]\n    key_elems.append(escape.utf8(token[\"secret\"] if token else \"\"))\n    key = b\"&\".join(key_elems)\n\n    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)\n    return binascii.b2a_base64(hash.digest())[:-1]\n\n\ndef _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):\n    \"\"\"Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.\n\n    See http://oauth.net/core/1.0a/#signing_process\n    \"\"\"\n    parts = urlparse.urlparse(url)\n    scheme, netloc, path = parts[:3]\n    normalized_url = scheme.lower() + \"://\" + netloc.lower() + path\n\n    base_elems = []\n    base_elems.append(method.upper())\n    base_elems.append(normalized_url)\n    base_elems.append(\"&\".join(\"%s=%s\" % (k, _oauth_escape(str(v)))\n                               for k, v in sorted(parameters.items())))\n\n    base_string = \"&\".join(_oauth_escape(e) for e in base_elems)\n    key_elems = [escape.utf8(urllib_parse.quote(consumer_token[\"secret\"], safe='~'))]\n    key_elems.append(escape.utf8(urllib_parse.quote(token[\"secret\"], safe='~') if token else \"\"))\n    key = b\"&\".join(key_elems)\n\n    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)\n    return binascii.b2a_base64(hash.digest())[:-1]\n\n\ndef _oauth_escape(val):\n    if isinstance(val, unicode_type):\n        val = val.encode(\"utf-8\")\n    return urllib_parse.quote(val, safe=\"~\")\n\n\ndef _oauth_parse_response(body):\n    # I can't find an officially-defined encoding for oauth responses and\n    # have never seen anyone use non-ascii.  Leave the response in a byte\n    # string for python 2, and use utf8 on python 3.\n    body = escape.native_str(body)\n    p = urlparse.parse_qs(body, keep_blank_values=False)\n    token = dict(key=p[\"oauth_token\"][0], secret=p[\"oauth_token_secret\"][0])\n\n    # Add the extra parameters the Provider included to the token\n    special = (\"oauth_token\", \"oauth_token_secret\")\n    token.update((k, p[k][0]) for k in p if k not in special)\n    return token\n",
            "header": {
                "file": {
                    "path": "tornado/auth.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "32d0e226",
                "new_commit_hash": "ff7172aa",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/auth.py"
            },
            "plus_file": {
                "path": "b/tornado/auth.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 75,
                            "length": 7
                        },
                        "new_range": {
                            "start": 75,
                            "length": 7
                        },
                        "section": "import hmac"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import time",
                                "type": "context"
                            },
                            {
                                "content": "import uuid",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.concurrent import TracebackFuture, return_future",
                                "type": "deleted"
                            },
                            {
                                "content": "from tornado.concurrent import TracebackFuture, return_future, chain_future",
                                "type": "added"
                            },
                            {
                                "content": "from tornado import gen",
                                "type": "context"
                            },
                            {
                                "content": "from tornado import httpclient",
                                "type": "context"
                            },
                            {
                                "content": "from tornado import escape",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/auth.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.concurrent import TracebackFuture, return_future, chain_future",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 78,
                            "end_lineno": 78,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "tornado/auth.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.concurrent import TracebackFuture, return_future",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 78,
                            "end_lineno": 78,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 985,
                            "length": 7
                        },
                        "new_range": {
                            "start": 985,
                            "length": 7
                        },
                        "section": "class FacebookGraphMixin(OAuth2Mixin):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))",
                                "type": "context"
                            },
                            {
                                "content": "            return",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        args = escape.parse_qs_bytes(escape.native_str(response.body))",
                                "type": "deleted"
                            },
                            {
                                "content": "        args = urlparse.parse_qs(escape.native_str(response.body))",
                                "type": "added"
                            },
                            {
                                "content": "        session = {",
                                "type": "context"
                            },
                            {
                                "content": "            \"access_token\": args[\"access_token\"][-1],",
                                "type": "context"
                            },
                            {
                                "content": "            \"expires\": args.get(\"expires\")",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/auth.py",
                            "type": "method",
                            "name": "FacebookGraphMixin._on_access_token",
                            "content": "class FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = escape.parse_qs_bytes(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        return self.oauth2_request(url, callback, access_token,\n                                   post_args, **args)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 982,
                            "end_lineno": 1000,
                            "parent": {
                                "file_name": "tornado/auth.py",
                                "type": "class",
                                "name": "FacebookGraphMixin",
                                "content": "class FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = escape.parse_qs_bytes(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        return self.oauth2_request(url, callback, access_token,\n                                   post_args, **args)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 928,
                                "end_lineno": 1066,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/auth.py",
                            "type": "class",
                            "name": "FacebookGraphMixin",
                            "content": "class FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = escape.parse_qs_bytes(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        return self.oauth2_request(url, callback, access_token,\n                                   post_args, **args)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 928,
                            "end_lineno": 1066,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1062,
                            "length": 8
                        },
                        "new_range": {
                            "start": 1062,
                            "length": 13
                        },
                        "section": "class FacebookGraphMixin(OAuth2Mixin):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "           Added the ability to override ``self._FACEBOOK_BASE_URL``.",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "        url = self._FACEBOOK_BASE_URL + path",
                                "type": "context"
                            },
                            {
                                "content": "        return self.oauth2_request(url, callback, access_token,",
                                "type": "deleted"
                            },
                            {
                                "content": "                                   post_args, **args)",
                                "type": "deleted"
                            },
                            {
                                "content": "        # Thanks to the _auth_return_future decorator, our \"callback\"",
                                "type": "added"
                            },
                            {
                                "content": "        # argument is a Future, which we cannot pass as a callback to",
                                "type": "added"
                            },
                            {
                                "content": "        # oauth2_request. Instead, have oauth2_request return a",
                                "type": "added"
                            },
                            {
                                "content": "        # future and chain them together.",
                                "type": "added"
                            },
                            {
                                "content": "        oauth_future = self.oauth2_request(url, access_token=access_token,",
                                "type": "added"
                            },
                            {
                                "content": "                                           post_args=post_args, **args)",
                                "type": "added"
                            },
                            {
                                "content": "        chain_future(oauth_future, callback)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def _oauth_signature(consumer_token, method, url, parameters={}, token=None):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/auth.py",
                            "type": "class",
                            "name": "FacebookGraphMixin",
                            "content": "class FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = escape.parse_qs_bytes(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        return self.oauth2_request(url, callback, access_token,\n                                   post_args, **args)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 928,
                            "end_lineno": 1066,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/auth.py",
                            "type": "method",
                            "name": "FacebookGraphMixin.facebook_request",
                            "content": "class FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = escape.parse_qs_bytes(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        return self.oauth2_request(url, callback, access_token,\n                                   post_args, **args)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1015,
                            "end_lineno": 1066,
                            "parent": {
                                "file_name": "tornado/auth.py",
                                "type": "class",
                                "name": "FacebookGraphMixin",
                                "content": "class FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = escape.parse_qs_bytes(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        return self.oauth2_request(url, callback, access_token,\n                                   post_args, **args)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 928,
                                "end_lineno": 1066,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "# These tests do not currently do much to verify the correct implementation\n# of the openid/oauth protocols, they just exercise the major code paths\n# and ensure that it doesn't blow up (e.g. with unicode/bytes issues in\n# python 3)\n\n\nfrom __future__ import absolute_import, division, print_function, with_statement\nfrom tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin\nfrom tornado.concurrent import Future\nfrom tornado.escape import json_decode\nfrom tornado import gen\nfrom tornado.httputil import url_concat\nfrom tornado.log import gen_log\nfrom tornado.testing import AsyncHTTPTestCase, ExpectLog\nfrom tornado.util import u\nfrom tornado.web import RequestHandler, Application, asynchronous, HTTPError\n\n\nclass OpenIdClientLoginHandler(RequestHandler, OpenIdMixin):\n    def initialize(self, test):\n        self._OPENID_ENDPOINT = test.get_url('/openid/server/authenticate')\n\n    @asynchronous\n    def get(self):\n        if self.get_argument('openid.mode', None):\n            self.get_authenticated_user(\n                self.on_user, http_client=self.settings['http_client'])\n            return\n        res = self.authenticate_redirect()\n        assert isinstance(res, Future)\n        assert res.done()\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n\nclass OpenIdServerAuthenticateHandler(RequestHandler):\n    def post(self):\n        if self.get_argument('openid.mode') != 'check_authentication':\n            raise Exception(\"incorrect openid.mode %r\")\n        self.write('is_valid:true')\n\n\nclass OAuth1ClientLoginHandler(RequestHandler, OAuthMixin):\n    def initialize(self, test, version):\n        self._OAUTH_VERSION = version\n        self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth1/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/oauth1/server/access_token')\n\n    def _oauth_consumer_token(self):\n        return dict(key='asdf', secret='qwer')\n\n    @asynchronous\n    def get(self):\n        if self.get_argument('oauth_token', None):\n            self.get_authenticated_user(\n                self.on_user, http_client=self.settings['http_client'])\n            return\n        res = self.authorize_redirect(http_client=self.settings['http_client'])\n        assert isinstance(res, Future)\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n    def _oauth_get_user(self, access_token, callback):\n        if self.get_argument('fail_in_get_user', None):\n            raise Exception(\"failing in get_user\")\n        if access_token != dict(key='uiop', secret='5678'):\n            raise Exception(\"incorrect access token %r\" % access_token)\n        callback(dict(email='foo@example.com'))\n\n\nclass OAuth1ClientLoginCoroutineHandler(OAuth1ClientLoginHandler):\n    \"\"\"Replaces OAuth1ClientLoginCoroutineHandler's get() with a coroutine.\"\"\"\n    @gen.coroutine\n    def get(self):\n        if self.get_argument('oauth_token', None):\n            # Ensure that any exceptions are set on the returned Future,\n            # not simply thrown into the surrounding StackContext.\n            try:\n                yield self.get_authenticated_user()\n            except Exception as e:\n                self.set_status(503)\n                self.write(\"got exception: %s\" % e)\n        else:\n            yield self.authorize_redirect()\n\n\nclass OAuth1ClientRequestParametersHandler(RequestHandler, OAuthMixin):\n    def initialize(self, version):\n        self._OAUTH_VERSION = version\n\n    def _oauth_consumer_token(self):\n        return dict(key='asdf', secret='qwer')\n\n    def get(self):\n        params = self._oauth_request_parameters(\n            'http://www.example.com/api/asdf',\n            dict(key='uiop', secret='5678'),\n            parameters=dict(foo='bar'))\n        self.write(params)\n\n\nclass OAuth1ServerRequestTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=zxcv&oauth_token_secret=1234')\n\n\nclass OAuth1ServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=uiop&oauth_token_secret=5678')\n\n\nclass OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth2/server/authorize')\n\n    def get(self):\n        res = self.authorize_redirect()\n        assert isinstance(res, Future)\n        assert res.done()\n\n\nclass TwitterClientHandler(RequestHandler, TwitterMixin):\n    def initialize(self, test):\n        self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/twitter/server/access_token')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth1/server/authorize')\n        self._TWITTER_BASE_URL = test.get_url('/twitter/api')\n\n    def get_auth_http_client(self):\n        return self.settings['http_client']\n\n\nclass TwitterClientLoginHandler(TwitterClientHandler):\n    @asynchronous\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            self.get_authenticated_user(self.on_user)\n            return\n        self.authorize_redirect()\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n\nclass TwitterClientLoginGenEngineHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            user = yield self.get_authenticated_user()\n            self.finish(user)\n        else:\n            # Old style: with @gen.engine we can ignore the Future from\n            # authorize_redirect.\n            self.authorize_redirect()\n\n\nclass TwitterClientLoginGenCoroutineHandler(TwitterClientHandler):\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            user = yield self.get_authenticated_user()\n            self.finish(user)\n        else:\n            # New style: with @gen.coroutine the result must be yielded\n            # or else the request will be auto-finished too soon.\n            yield self.authorize_redirect()\n\n\nclass TwitterClientShowUserHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # TODO: would be nice to go through the login flow instead of\n        # cheating with a hard-coded access token.\n        response = yield gen.Task(self.twitter_request,\n                                  '/users/show/%s' % self.get_argument('name'),\n                                  access_token=dict(key='hjkl', secret='vbnm'))\n        if response is None:\n            self.set_status(500)\n            self.finish('error from twitter request')\n        else:\n            self.finish(response)\n\n\nclass TwitterClientShowUserFutureHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        try:\n            response = yield self.twitter_request(\n                '/users/show/%s' % self.get_argument('name'),\n                access_token=dict(key='hjkl', secret='vbnm'))\n        except AuthError as e:\n            self.set_status(500)\n            self.finish(str(e))\n            return\n        assert response is not None\n        self.finish(response)\n\n\nclass TwitterServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=hjkl&oauth_token_secret=vbnm&screen_name=foo')\n\n\nclass TwitterServerShowUserHandler(RequestHandler):\n    def get(self, screen_name):\n        if screen_name == 'error':\n            raise HTTPError(500)\n        assert 'oauth_nonce' in self.request.arguments\n        assert 'oauth_timestamp' in self.request.arguments\n        assert 'oauth_signature' in self.request.arguments\n        assert self.get_argument('oauth_consumer_key') == 'test_twitter_consumer_key'\n        assert self.get_argument('oauth_signature_method') == 'HMAC-SHA1'\n        assert self.get_argument('oauth_version') == '1.0'\n        assert self.get_argument('oauth_token') == 'hjkl'\n        self.write(dict(screen_name=screen_name, name=screen_name.capitalize()))\n\n\nclass TwitterServerVerifyCredentialsHandler(RequestHandler):\n    def get(self):\n        assert 'oauth_nonce' in self.request.arguments\n        assert 'oauth_timestamp' in self.request.arguments\n        assert 'oauth_signature' in self.request.arguments\n        assert self.get_argument('oauth_consumer_key') == 'test_twitter_consumer_key'\n        assert self.get_argument('oauth_signature_method') == 'HMAC-SHA1'\n        assert self.get_argument('oauth_version') == '1.0'\n        assert self.get_argument('oauth_token') == 'hjkl'\n        self.write(dict(screen_name='foo', name='Foo'))\n\n\nclass AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)\n\n\nclass GoogleLoginHandler(RequestHandler, GoogleOAuth2Mixin):\n    def initialize(self, test):\n        self.test = test\n        self._OAUTH_REDIRECT_URI = test.get_url('/client/login')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/google/oauth2/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/google/oauth2/token')\n\n    @gen.coroutine\n    def get(self):\n        code = self.get_argument('code', None)\n        if code is not None:\n            # retrieve authenticate google user\n            access = yield self.get_authenticated_user(self._OAUTH_REDIRECT_URI,\n                                                       code)\n            user = yield self.oauth2_request(\n                self.test.get_url(\"/google/oauth2/userinfo\"),\n                access_token=access[\"access_token\"])\n            # return the user and access token as json\n            user[\"access_token\"] = access[\"access_token\"]\n            self.write(user)\n        else:\n            yield self.authorize_redirect(\n                redirect_uri=self._OAUTH_REDIRECT_URI,\n                client_id=self.settings['google_oauth']['key'],\n                client_secret=self.settings['google_oauth']['secret'],\n                scope=['profile', 'email'],\n                response_type='code',\n                extra_params={'prompt': 'select_account'})\n\n\nclass GoogleOAuth2AuthorizeHandler(RequestHandler):\n    def get(self):\n        # issue a fake auth code and redirect to redirect_uri\n        code = 'fake-authorization-code'\n        self.redirect(url_concat(self.get_argument('redirect_uri'),\n                                 dict(code=code)))\n\n\nclass GoogleOAuth2TokenHandler(RequestHandler):\n    def post(self):\n        assert self.get_argument('code') == 'fake-authorization-code'\n        # issue a fake token\n        self.finish({\n            'access_token': 'fake-access-token',\n            'expires_in': 'never-expires'\n        })\n\n\nclass GoogleOAuth2UserinfoHandler(RequestHandler):\n    def get(self):\n        assert self.get_argument('access_token') == 'fake-access-token'\n        # return a fake user\n        self.finish({\n                'name': 'Foo',\n                'email': 'foo@example.com'\n                })\n\n\nclass GoogleOAuth2Test(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/client/login', GoogleLoginHandler, dict(test=self)),\n\n                # simulated google authorization server endpoints\n                ('/google/oauth2/authorize', GoogleOAuth2AuthorizeHandler),\n                ('/google/oauth2/token', GoogleOAuth2TokenHandler),\n                ('/google/oauth2/userinfo', GoogleOAuth2UserinfoHandler),\n            ],\n            google_oauth={\n                \"key\": 'fake_google_client_id',\n                \"secret\": 'fake_google_client_secret'\n            })\n\n    def test_google_login(self):\n        response = self.fetch('/client/login')\n        self.assertDictEqual({\n            u('name'): u('Foo'),\n            u('email'): u('foo@example.com'),\n            u('access_token'): u('fake-access-token'),\n        }, json_decode(response.body))\n",
            "new_file_content": "# These tests do not currently do much to verify the correct implementation\n# of the openid/oauth protocols, they just exercise the major code paths\n# and ensure that it doesn't blow up (e.g. with unicode/bytes issues in\n# python 3)\n\n\nfrom __future__ import absolute_import, division, print_function, with_statement\nfrom tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin, FacebookGraphMixin\nfrom tornado.concurrent import Future\nfrom tornado.escape import json_decode\nfrom tornado import gen\nfrom tornado.httputil import url_concat\nfrom tornado.log import gen_log\nfrom tornado.testing import AsyncHTTPTestCase, ExpectLog\nfrom tornado.util import u\nfrom tornado.web import RequestHandler, Application, asynchronous, HTTPError\n\n\nclass OpenIdClientLoginHandler(RequestHandler, OpenIdMixin):\n    def initialize(self, test):\n        self._OPENID_ENDPOINT = test.get_url('/openid/server/authenticate')\n\n    @asynchronous\n    def get(self):\n        if self.get_argument('openid.mode', None):\n            self.get_authenticated_user(\n                self.on_user, http_client=self.settings['http_client'])\n            return\n        res = self.authenticate_redirect()\n        assert isinstance(res, Future)\n        assert res.done()\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n\nclass OpenIdServerAuthenticateHandler(RequestHandler):\n    def post(self):\n        if self.get_argument('openid.mode') != 'check_authentication':\n            raise Exception(\"incorrect openid.mode %r\")\n        self.write('is_valid:true')\n\n\nclass OAuth1ClientLoginHandler(RequestHandler, OAuthMixin):\n    def initialize(self, test, version):\n        self._OAUTH_VERSION = version\n        self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth1/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/oauth1/server/access_token')\n\n    def _oauth_consumer_token(self):\n        return dict(key='asdf', secret='qwer')\n\n    @asynchronous\n    def get(self):\n        if self.get_argument('oauth_token', None):\n            self.get_authenticated_user(\n                self.on_user, http_client=self.settings['http_client'])\n            return\n        res = self.authorize_redirect(http_client=self.settings['http_client'])\n        assert isinstance(res, Future)\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n    def _oauth_get_user(self, access_token, callback):\n        if self.get_argument('fail_in_get_user', None):\n            raise Exception(\"failing in get_user\")\n        if access_token != dict(key='uiop', secret='5678'):\n            raise Exception(\"incorrect access token %r\" % access_token)\n        callback(dict(email='foo@example.com'))\n\n\nclass OAuth1ClientLoginCoroutineHandler(OAuth1ClientLoginHandler):\n    \"\"\"Replaces OAuth1ClientLoginCoroutineHandler's get() with a coroutine.\"\"\"\n    @gen.coroutine\n    def get(self):\n        if self.get_argument('oauth_token', None):\n            # Ensure that any exceptions are set on the returned Future,\n            # not simply thrown into the surrounding StackContext.\n            try:\n                yield self.get_authenticated_user()\n            except Exception as e:\n                self.set_status(503)\n                self.write(\"got exception: %s\" % e)\n        else:\n            yield self.authorize_redirect()\n\n\nclass OAuth1ClientRequestParametersHandler(RequestHandler, OAuthMixin):\n    def initialize(self, version):\n        self._OAUTH_VERSION = version\n\n    def _oauth_consumer_token(self):\n        return dict(key='asdf', secret='qwer')\n\n    def get(self):\n        params = self._oauth_request_parameters(\n            'http://www.example.com/api/asdf',\n            dict(key='uiop', secret='5678'),\n            parameters=dict(foo='bar'))\n        self.write(params)\n\n\nclass OAuth1ServerRequestTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=zxcv&oauth_token_secret=1234')\n\n\nclass OAuth1ServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=uiop&oauth_token_secret=5678')\n\n\nclass OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth2/server/authorize')\n\n    def get(self):\n        res = self.authorize_redirect()\n        assert isinstance(res, Future)\n        assert res.done()\n\n\nclass FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')\n        self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')\n\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"code\", None):\n            user = yield self.get_authenticated_user(\n                redirect_uri=self.request.full_url(),\n                client_id=self.settings[\"facebook_api_key\"],\n                client_secret=self.settings[\"facebook_secret\"],\n                code=self.get_argument(\"code\"))\n            self.write(user)\n        else:\n                yield self.authorize_redirect(\n                    redirect_uri=self.request.full_url(),\n                    client_id=self.settings[\"facebook_api_key\"],\n                    extra_params={\"scope\": \"read_stream,offline_access\"})\n\n\nclass FacebookServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('access_token=asdf')\n\n\nclass FacebookServerMeHandler(RequestHandler):\n    def get(self):\n        self.write('{}')\n\n\nclass TwitterClientHandler(RequestHandler, TwitterMixin):\n    def initialize(self, test):\n        self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/twitter/server/access_token')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth1/server/authorize')\n        self._TWITTER_BASE_URL = test.get_url('/twitter/api')\n\n    def get_auth_http_client(self):\n        return self.settings['http_client']\n\n\nclass TwitterClientLoginHandler(TwitterClientHandler):\n    @asynchronous\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            self.get_authenticated_user(self.on_user)\n            return\n        self.authorize_redirect()\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n\nclass TwitterClientLoginGenEngineHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            user = yield self.get_authenticated_user()\n            self.finish(user)\n        else:\n            # Old style: with @gen.engine we can ignore the Future from\n            # authorize_redirect.\n            self.authorize_redirect()\n\n\nclass TwitterClientLoginGenCoroutineHandler(TwitterClientHandler):\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            user = yield self.get_authenticated_user()\n            self.finish(user)\n        else:\n            # New style: with @gen.coroutine the result must be yielded\n            # or else the request will be auto-finished too soon.\n            yield self.authorize_redirect()\n\n\nclass TwitterClientShowUserHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # TODO: would be nice to go through the login flow instead of\n        # cheating with a hard-coded access token.\n        response = yield gen.Task(self.twitter_request,\n                                  '/users/show/%s' % self.get_argument('name'),\n                                  access_token=dict(key='hjkl', secret='vbnm'))\n        if response is None:\n            self.set_status(500)\n            self.finish('error from twitter request')\n        else:\n            self.finish(response)\n\n\nclass TwitterClientShowUserFutureHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        try:\n            response = yield self.twitter_request(\n                '/users/show/%s' % self.get_argument('name'),\n                access_token=dict(key='hjkl', secret='vbnm'))\n        except AuthError as e:\n            self.set_status(500)\n            self.finish(str(e))\n            return\n        assert response is not None\n        self.finish(response)\n\n\nclass TwitterServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=hjkl&oauth_token_secret=vbnm&screen_name=foo')\n\n\nclass TwitterServerShowUserHandler(RequestHandler):\n    def get(self, screen_name):\n        if screen_name == 'error':\n            raise HTTPError(500)\n        assert 'oauth_nonce' in self.request.arguments\n        assert 'oauth_timestamp' in self.request.arguments\n        assert 'oauth_signature' in self.request.arguments\n        assert self.get_argument('oauth_consumer_key') == 'test_twitter_consumer_key'\n        assert self.get_argument('oauth_signature_method') == 'HMAC-SHA1'\n        assert self.get_argument('oauth_version') == '1.0'\n        assert self.get_argument('oauth_token') == 'hjkl'\n        self.write(dict(screen_name=screen_name, name=screen_name.capitalize()))\n\n\nclass TwitterServerVerifyCredentialsHandler(RequestHandler):\n    def get(self):\n        assert 'oauth_nonce' in self.request.arguments\n        assert 'oauth_timestamp' in self.request.arguments\n        assert 'oauth_signature' in self.request.arguments\n        assert self.get_argument('oauth_consumer_key') == 'test_twitter_consumer_key'\n        assert self.get_argument('oauth_signature_method') == 'HMAC-SHA1'\n        assert self.get_argument('oauth_version') == '1.0'\n        assert self.get_argument('oauth_token') == 'hjkl'\n        self.write(dict(screen_name='foo', name='Foo'))\n\n\nclass AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),\n                ('/facebook/server/me', FacebookServerMeHandler),\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret',\n            facebook_api_key='test_facebook_api_key',\n            facebook_secret='test_facebook_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def test_facebook_login(self):\n        response = self.fetch('/facebook/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])\n        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)\n\n\nclass GoogleLoginHandler(RequestHandler, GoogleOAuth2Mixin):\n    def initialize(self, test):\n        self.test = test\n        self._OAUTH_REDIRECT_URI = test.get_url('/client/login')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/google/oauth2/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/google/oauth2/token')\n\n    @gen.coroutine\n    def get(self):\n        code = self.get_argument('code', None)\n        if code is not None:\n            # retrieve authenticate google user\n            access = yield self.get_authenticated_user(self._OAUTH_REDIRECT_URI,\n                                                       code)\n            user = yield self.oauth2_request(\n                self.test.get_url(\"/google/oauth2/userinfo\"),\n                access_token=access[\"access_token\"])\n            # return the user and access token as json\n            user[\"access_token\"] = access[\"access_token\"]\n            self.write(user)\n        else:\n            yield self.authorize_redirect(\n                redirect_uri=self._OAUTH_REDIRECT_URI,\n                client_id=self.settings['google_oauth']['key'],\n                client_secret=self.settings['google_oauth']['secret'],\n                scope=['profile', 'email'],\n                response_type='code',\n                extra_params={'prompt': 'select_account'})\n\n\nclass GoogleOAuth2AuthorizeHandler(RequestHandler):\n    def get(self):\n        # issue a fake auth code and redirect to redirect_uri\n        code = 'fake-authorization-code'\n        self.redirect(url_concat(self.get_argument('redirect_uri'),\n                                 dict(code=code)))\n\n\nclass GoogleOAuth2TokenHandler(RequestHandler):\n    def post(self):\n        assert self.get_argument('code') == 'fake-authorization-code'\n        # issue a fake token\n        self.finish({\n            'access_token': 'fake-access-token',\n            'expires_in': 'never-expires'\n        })\n\n\nclass GoogleOAuth2UserinfoHandler(RequestHandler):\n    def get(self):\n        assert self.get_argument('access_token') == 'fake-access-token'\n        # return a fake user\n        self.finish({\n                'name': 'Foo',\n                'email': 'foo@example.com'\n                })\n\n\nclass GoogleOAuth2Test(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/client/login', GoogleLoginHandler, dict(test=self)),\n\n                # simulated google authorization server endpoints\n                ('/google/oauth2/authorize', GoogleOAuth2AuthorizeHandler),\n                ('/google/oauth2/token', GoogleOAuth2TokenHandler),\n                ('/google/oauth2/userinfo', GoogleOAuth2UserinfoHandler),\n            ],\n            google_oauth={\n                \"key\": 'fake_google_client_id',\n                \"secret\": 'fake_google_client_secret'\n            })\n\n    def test_google_login(self):\n        response = self.fetch('/client/login')\n        self.assertDictEqual({\n            u('name'): u('Foo'),\n            u('email'): u('foo@example.com'),\n            u('access_token'): u('fake-access-token'),\n        }, json_decode(response.body))\n",
            "header": {
                "file": {
                    "path": "tornado/test/auth_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "56de93a5",
                "new_commit_hash": "3ed40e45",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/auth_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/auth_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 5,
                            "length": 7
                        },
                        "new_range": {
                            "start": 5,
                            "length": 7
                        },
                        "section": ""
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from __future__ import absolute_import, division, print_function, with_statement",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin",
                                "type": "deleted"
                            },
                            {
                                "content": "from tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin, FacebookGraphMixin",
                                "type": "added"
                            },
                            {
                                "content": "from tornado.concurrent import Future",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.escape import json_decode",
                                "type": "context"
                            },
                            {
                                "content": "from tornado import gen",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin, FacebookGraphMixin",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 8,
                            "end_lineno": 8,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 8,
                            "end_lineno": 8,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 126,
                            "length": 6
                        },
                        "new_range": {
                            "start": 126,
                            "length": 38
                        },
                        "section": "class OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        assert res.done()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):",
                                "type": "added"
                            },
                            {
                                "content": "    def initialize(self, test):",
                                "type": "added"
                            },
                            {
                                "content": "        self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')",
                                "type": "added"
                            },
                            {
                                "content": "        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')",
                                "type": "added"
                            },
                            {
                                "content": "        self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    @gen.coroutine",
                                "type": "added"
                            },
                            {
                                "content": "    def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "        if self.get_argument(\"code\", None):",
                                "type": "added"
                            },
                            {
                                "content": "            user = yield self.get_authenticated_user(",
                                "type": "added"
                            },
                            {
                                "content": "                redirect_uri=self.request.full_url(),",
                                "type": "added"
                            },
                            {
                                "content": "                client_id=self.settings[\"facebook_api_key\"],",
                                "type": "added"
                            },
                            {
                                "content": "                client_secret=self.settings[\"facebook_secret\"],",
                                "type": "added"
                            },
                            {
                                "content": "                code=self.get_argument(\"code\"))",
                                "type": "added"
                            },
                            {
                                "content": "            self.write(user)",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "                yield self.authorize_redirect(",
                                "type": "added"
                            },
                            {
                                "content": "                    redirect_uri=self.request.full_url(),",
                                "type": "added"
                            },
                            {
                                "content": "                    client_id=self.settings[\"facebook_api_key\"],",
                                "type": "added"
                            },
                            {
                                "content": "                    extra_params={\"scope\": \"read_stream,offline_access\"})",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class FacebookServerAccessTokenHandler(RequestHandler):",
                                "type": "added"
                            },
                            {
                                "content": "    def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.write('access_token=asdf')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class FacebookServerMeHandler(RequestHandler):",
                                "type": "added"
                            },
                            {
                                "content": "    def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.write('{}')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class TwitterClientHandler(RequestHandler, TwitterMixin):",
                                "type": "context"
                            },
                            {
                                "content": "    def initialize(self, test):",
                                "type": "context"
                            },
                            {
                                "content": "        self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "class",
                            "name": "FacebookClientLoginHandler",
                            "content": "class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')\n        self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')\n\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"code\", None):\n            user = yield self.get_authenticated_user(\n                redirect_uri=self.request.full_url(),\n                client_id=self.settings[\"facebook_api_key\"],\n                client_secret=self.settings[\"facebook_secret\"],\n                code=self.get_argument(\"code\"))\n            self.write(user)\n        else:\n                yield self.authorize_redirect(\n                    redirect_uri=self.request.full_url(),\n                    client_id=self.settings[\"facebook_api_key\"],\n                    extra_params={\"scope\": \"read_stream,offline_access\"})",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 129,
                            "end_lineno": 148,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "class",
                            "name": "FacebookServerMeHandler",
                            "content": "class FacebookServerMeHandler(RequestHandler):\n    def get(self):\n        self.write('{}')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 156,
                            "end_lineno": 158,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "method",
                            "name": "FacebookClientLoginHandler.get",
                            "content": "class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')\n        self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')\n\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"code\", None):\n            user = yield self.get_authenticated_user(\n                redirect_uri=self.request.full_url(),\n                client_id=self.settings[\"facebook_api_key\"],\n                client_secret=self.settings[\"facebook_secret\"],\n                code=self.get_argument(\"code\"))\n            self.write(user)\n        else:\n                yield self.authorize_redirect(\n                    redirect_uri=self.request.full_url(),\n                    client_id=self.settings[\"facebook_api_key\"],\n                    extra_params={\"scope\": \"read_stream,offline_access\"})",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 136,
                            "end_lineno": 148,
                            "parent": {
                                "file_name": "tornado/test/auth_test.py",
                                "type": "class",
                                "name": "FacebookClientLoginHandler",
                                "content": "class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')\n        self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')\n\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"code\", None):\n            user = yield self.get_authenticated_user(\n                redirect_uri=self.request.full_url(),\n                client_id=self.settings[\"facebook_api_key\"],\n                client_secret=self.settings[\"facebook_secret\"],\n                code=self.get_argument(\"code\"))\n            self.write(user)\n        else:\n                yield self.authorize_redirect(\n                    redirect_uri=self.request.full_url(),\n                    client_id=self.settings[\"facebook_api_key\"],\n                    extra_params={\"scope\": \"read_stream,offline_access\"})",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 129,
                                "end_lineno": 148,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "method",
                            "name": "FacebookServerAccessTokenHandler.get",
                            "content": "class FacebookServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('access_token=asdf')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 152,
                            "end_lineno": 153,
                            "parent": {
                                "file_name": "tornado/test/auth_test.py",
                                "type": "class",
                                "name": "FacebookServerAccessTokenHandler",
                                "content": "class FacebookServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('access_token=asdf')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 151,
                                "end_lineno": 153,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "class",
                            "name": "FacebookServerAccessTokenHandler",
                            "content": "class FacebookServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('access_token=asdf')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 151,
                            "end_lineno": 153,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "method",
                            "name": "FacebookClientLoginHandler.initialize",
                            "content": "class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')\n        self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')\n\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"code\", None):\n            user = yield self.get_authenticated_user(\n                redirect_uri=self.request.full_url(),\n                client_id=self.settings[\"facebook_api_key\"],\n                client_secret=self.settings[\"facebook_secret\"],\n                code=self.get_argument(\"code\"))\n            self.write(user)\n        else:\n                yield self.authorize_redirect(\n                    redirect_uri=self.request.full_url(),\n                    client_id=self.settings[\"facebook_api_key\"],\n                    extra_params={\"scope\": \"read_stream,offline_access\"})",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 130,
                            "end_lineno": 133,
                            "parent": {
                                "file_name": "tornado/test/auth_test.py",
                                "type": "class",
                                "name": "FacebookClientLoginHandler",
                                "content": "class FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')\n        self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')\n\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"code\", None):\n            user = yield self.get_authenticated_user(\n                redirect_uri=self.request.full_url(),\n                client_id=self.settings[\"facebook_api_key\"],\n                client_secret=self.settings[\"facebook_secret\"],\n                code=self.get_argument(\"code\"))\n            self.write(user)\n        else:\n                yield self.authorize_redirect(\n                    redirect_uri=self.request.full_url(),\n                    client_id=self.settings[\"facebook_api_key\"],\n                    extra_params={\"scope\": \"read_stream,offline_access\"})",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 129,
                                "end_lineno": 148,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "method",
                            "name": "FacebookServerMeHandler.get",
                            "content": "class FacebookServerMeHandler(RequestHandler):\n    def get(self):\n        self.write('{}')",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 157,
                            "end_lineno": 158,
                            "parent": {
                                "file_name": "tornado/test/auth_test.py",
                                "type": "class",
                                "name": "FacebookServerMeHandler",
                                "content": "class FacebookServerMeHandler(RequestHandler):\n    def get(self):\n        self.write('{}')",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 156,
                                "end_lineno": 158,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 260,
                            "length": 6
                        },
                        "new_range": {
                            "start": 292,
                            "length": 8
                        },
                        "section": "class AuthTest(AsyncHTTPTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                 dict(version='1.0a')),",
                                "type": "context"
                            },
                            {
                                "content": "                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),",
                                "type": "context"
                            },
                            {
                                "content": "                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),",
                                "type": "context"
                            },
                            {
                                "content": "                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "method",
                            "name": "AuthTest.get_app",
                            "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),\n                ('/facebook/server/me', FacebookServerMeHandler),\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret',\n            facebook_api_key='test_facebook_api_key',\n            facebook_secret='test_facebook_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def test_facebook_login(self):\n        response = self.fetch('/facebook/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])\n        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 275,
                            "end_lineno": 318,
                            "parent": {
                                "file_name": "tornado/test/auth_test.py",
                                "type": "class",
                                "name": "AuthTest",
                                "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),\n                ('/facebook/server/me', FacebookServerMeHandler),\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret',\n            facebook_api_key='test_facebook_api_key',\n            facebook_secret='test_facebook_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def test_facebook_login(self):\n        response = self.fetch('/facebook/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])\n        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 274,
                                "end_lineno": 461,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "class",
                            "name": "AuthTest",
                            "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),\n                ('/facebook/server/me', FacebookServerMeHandler),\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret',\n            facebook_api_key='test_facebook_api_key',\n            facebook_secret='test_facebook_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def test_facebook_login(self):\n        response = self.fetch('/facebook/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])\n        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 274,
                            "end_lineno": 461,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 271,
                            "length": 13
                        },
                        "new_range": {
                            "start": 305,
                            "length": 17
                        },
                        "section": "class AuthTest(AsyncHTTPTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),",
                                "type": "context"
                            },
                            {
                                "content": "                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),",
                                "type": "added"
                            },
                            {
                                "content": "                ('/facebook/server/me', FacebookServerMeHandler),",
                                "type": "added"
                            },
                            {
                                "content": "                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),",
                                "type": "context"
                            },
                            {
                                "content": "                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),",
                                "type": "context"
                            },
                            {
                                "content": "                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),",
                                "type": "context"
                            },
                            {
                                "content": "            ],",
                                "type": "context"
                            },
                            {
                                "content": "            http_client=self.http_client,",
                                "type": "context"
                            },
                            {
                                "content": "            twitter_consumer_key='test_twitter_consumer_key',",
                                "type": "context"
                            },
                            {
                                "content": "            twitter_consumer_secret='test_twitter_consumer_secret')",
                                "type": "deleted"
                            },
                            {
                                "content": "            twitter_consumer_secret='test_twitter_consumer_secret',",
                                "type": "added"
                            },
                            {
                                "content": "            facebook_api_key='test_facebook_api_key',",
                                "type": "added"
                            },
                            {
                                "content": "            facebook_secret='test_facebook_secret')",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_openid_redirect(self):",
                                "type": "context"
                            },
                            {
                                "content": "        response = self.fetch('/openid/client/login', follow_redirects=False)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "method",
                            "name": "AuthTest.get_app",
                            "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 243,
                            "end_lineno": 280,
                            "parent": {
                                "file_name": "tornado/test/auth_test.py",
                                "type": "class",
                                "name": "AuthTest",
                                "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 242,
                                "end_lineno": 416,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "class",
                            "name": "AuthTest",
                            "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 242,
                            "end_lineno": 416,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 358,
                            "length": 6
                        },
                        "new_range": {
                            "start": 396,
                            "length": 13
                        },
                        "section": "class AuthTest(AsyncHTTPTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.assertEqual(response.code, 302)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_facebook_login(self):",
                                "type": "added"
                            },
                            {
                                "content": "        response = self.fetch('/facebook/client/login', follow_redirects=False)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(response.code, 302)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])",
                                "type": "added"
                            },
                            {
                                "content": "        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(response.code, 200)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def base_twitter_redirect(self, url):",
                                "type": "context"
                            },
                            {
                                "content": "        # Same as test_oauth10a_redirect",
                                "type": "context"
                            },
                            {
                                "content": "        response = self.fetch(url, follow_redirects=False)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "class",
                            "name": "AuthTest",
                            "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),\n                ('/facebook/server/me', FacebookServerMeHandler),\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret',\n            facebook_api_key='test_facebook_api_key',\n            facebook_secret='test_facebook_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def test_facebook_login(self):\n        response = self.fetch('/facebook/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])\n        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 274,
                            "end_lineno": 461,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/auth_test.py",
                            "type": "method",
                            "name": "AuthTest.test_facebook_login",
                            "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),\n                ('/facebook/server/me', FacebookServerMeHandler),\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret',\n            facebook_api_key='test_facebook_api_key',\n            facebook_secret='test_facebook_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def test_facebook_login(self):\n        response = self.fetch('/facebook/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])\n        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 399,
                            "end_lineno": 404,
                            "parent": {
                                "file_name": "tornado/test/auth_test.py",
                                "type": "class",
                                "name": "AuthTest",
                                "content": "class AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),\n                ('/facebook/server/me', FacebookServerMeHandler),\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret',\n            facebook_api_key='test_facebook_api_key',\n            facebook_secret='test_facebook_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def test_facebook_login(self):\n        response = self.fetch('/facebook/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])\n        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 274,
                                "end_lineno": 461,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "301f52b532c071a0d2fec1eb7c23f2714bb38567^",
    "new_commit_hash": "301f52b532c071a0d2fec1eb7c23f2714bb38567",
    "commit_message": "Fix a regression in FacebookGraphMixin in the 4.3 dev series.\n\nReturn access tokens as strings instead of bytes on python 3,\nmaking the user objects json-encodable.\n\nAdd a basic test for FacebookGraphMixin.\n\nFixes #1532",
    "commit_date": "2015-09-28T22:39:29-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "301f52b532c071a0d2fec1eb7c23f2714bb38567",
    "test_file_codes": [
        "# These tests do not currently do much to verify the correct implementation\n# of the openid/oauth protocols, they just exercise the major code paths\n# and ensure that it doesn't blow up (e.g. with unicode/bytes issues in\n# python 3)\n\n\nfrom __future__ import absolute_import, division, print_function, with_statement\nfrom tornado.auth import OpenIdMixin, OAuthMixin, OAuth2Mixin, TwitterMixin, AuthError, GoogleOAuth2Mixin, FacebookGraphMixin\nfrom tornado.concurrent import Future\nfrom tornado.escape import json_decode\nfrom tornado import gen\nfrom tornado.httputil import url_concat\nfrom tornado.log import gen_log\nfrom tornado.testing import AsyncHTTPTestCase, ExpectLog\nfrom tornado.util import u\nfrom tornado.web import RequestHandler, Application, asynchronous, HTTPError\n\n\nclass OpenIdClientLoginHandler(RequestHandler, OpenIdMixin):\n    def initialize(self, test):\n        self._OPENID_ENDPOINT = test.get_url('/openid/server/authenticate')\n\n    @asynchronous\n    def get(self):\n        if self.get_argument('openid.mode', None):\n            self.get_authenticated_user(\n                self.on_user, http_client=self.settings['http_client'])\n            return\n        res = self.authenticate_redirect()\n        assert isinstance(res, Future)\n        assert res.done()\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n\nclass OpenIdServerAuthenticateHandler(RequestHandler):\n    def post(self):\n        if self.get_argument('openid.mode') != 'check_authentication':\n            raise Exception(\"incorrect openid.mode %r\")\n        self.write('is_valid:true')\n\n\nclass OAuth1ClientLoginHandler(RequestHandler, OAuthMixin):\n    def initialize(self, test, version):\n        self._OAUTH_VERSION = version\n        self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth1/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/oauth1/server/access_token')\n\n    def _oauth_consumer_token(self):\n        return dict(key='asdf', secret='qwer')\n\n    @asynchronous\n    def get(self):\n        if self.get_argument('oauth_token', None):\n            self.get_authenticated_user(\n                self.on_user, http_client=self.settings['http_client'])\n            return\n        res = self.authorize_redirect(http_client=self.settings['http_client'])\n        assert isinstance(res, Future)\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n    def _oauth_get_user(self, access_token, callback):\n        if self.get_argument('fail_in_get_user', None):\n            raise Exception(\"failing in get_user\")\n        if access_token != dict(key='uiop', secret='5678'):\n            raise Exception(\"incorrect access token %r\" % access_token)\n        callback(dict(email='foo@example.com'))\n\n\nclass OAuth1ClientLoginCoroutineHandler(OAuth1ClientLoginHandler):\n    \"\"\"Replaces OAuth1ClientLoginCoroutineHandler's get() with a coroutine.\"\"\"\n    @gen.coroutine\n    def get(self):\n        if self.get_argument('oauth_token', None):\n            # Ensure that any exceptions are set on the returned Future,\n            # not simply thrown into the surrounding StackContext.\n            try:\n                yield self.get_authenticated_user()\n            except Exception as e:\n                self.set_status(503)\n                self.write(\"got exception: %s\" % e)\n        else:\n            yield self.authorize_redirect()\n\n\nclass OAuth1ClientRequestParametersHandler(RequestHandler, OAuthMixin):\n    def initialize(self, version):\n        self._OAUTH_VERSION = version\n\n    def _oauth_consumer_token(self):\n        return dict(key='asdf', secret='qwer')\n\n    def get(self):\n        params = self._oauth_request_parameters(\n            'http://www.example.com/api/asdf',\n            dict(key='uiop', secret='5678'),\n            parameters=dict(foo='bar'))\n        self.write(params)\n\n\nclass OAuth1ServerRequestTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=zxcv&oauth_token_secret=1234')\n\n\nclass OAuth1ServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=uiop&oauth_token_secret=5678')\n\n\nclass OAuth2ClientLoginHandler(RequestHandler, OAuth2Mixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth2/server/authorize')\n\n    def get(self):\n        res = self.authorize_redirect()\n        assert isinstance(res, Future)\n        assert res.done()\n\n\nclass FacebookClientLoginHandler(RequestHandler, FacebookGraphMixin):\n    def initialize(self, test):\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/facebook/server/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/facebook/server/access_token')\n        self._FACEBOOK_BASE_URL = test.get_url('/facebook/server')\n\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"code\", None):\n            user = yield self.get_authenticated_user(\n                redirect_uri=self.request.full_url(),\n                client_id=self.settings[\"facebook_api_key\"],\n                client_secret=self.settings[\"facebook_secret\"],\n                code=self.get_argument(\"code\"))\n            self.write(user)\n        else:\n                yield self.authorize_redirect(\n                    redirect_uri=self.request.full_url(),\n                    client_id=self.settings[\"facebook_api_key\"],\n                    extra_params={\"scope\": \"read_stream,offline_access\"})\n\n\nclass FacebookServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('access_token=asdf')\n\n\nclass FacebookServerMeHandler(RequestHandler):\n    def get(self):\n        self.write('{}')\n\n\nclass TwitterClientHandler(RequestHandler, TwitterMixin):\n    def initialize(self, test):\n        self._OAUTH_REQUEST_TOKEN_URL = test.get_url('/oauth1/server/request_token')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/twitter/server/access_token')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth1/server/authorize')\n        self._TWITTER_BASE_URL = test.get_url('/twitter/api')\n\n    def get_auth_http_client(self):\n        return self.settings['http_client']\n\n\nclass TwitterClientLoginHandler(TwitterClientHandler):\n    @asynchronous\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            self.get_authenticated_user(self.on_user)\n            return\n        self.authorize_redirect()\n\n    def on_user(self, user):\n        if user is None:\n            raise Exception(\"user is None\")\n        self.finish(user)\n\n\nclass TwitterClientLoginGenEngineHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            user = yield self.get_authenticated_user()\n            self.finish(user)\n        else:\n            # Old style: with @gen.engine we can ignore the Future from\n            # authorize_redirect.\n            self.authorize_redirect()\n\n\nclass TwitterClientLoginGenCoroutineHandler(TwitterClientHandler):\n    @gen.coroutine\n    def get(self):\n        if self.get_argument(\"oauth_token\", None):\n            user = yield self.get_authenticated_user()\n            self.finish(user)\n        else:\n            # New style: with @gen.coroutine the result must be yielded\n            # or else the request will be auto-finished too soon.\n            yield self.authorize_redirect()\n\n\nclass TwitterClientShowUserHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        # TODO: would be nice to go through the login flow instead of\n        # cheating with a hard-coded access token.\n        response = yield gen.Task(self.twitter_request,\n                                  '/users/show/%s' % self.get_argument('name'),\n                                  access_token=dict(key='hjkl', secret='vbnm'))\n        if response is None:\n            self.set_status(500)\n            self.finish('error from twitter request')\n        else:\n            self.finish(response)\n\n\nclass TwitterClientShowUserFutureHandler(TwitterClientHandler):\n    @asynchronous\n    @gen.engine\n    def get(self):\n        try:\n            response = yield self.twitter_request(\n                '/users/show/%s' % self.get_argument('name'),\n                access_token=dict(key='hjkl', secret='vbnm'))\n        except AuthError as e:\n            self.set_status(500)\n            self.finish(str(e))\n            return\n        assert response is not None\n        self.finish(response)\n\n\nclass TwitterServerAccessTokenHandler(RequestHandler):\n    def get(self):\n        self.write('oauth_token=hjkl&oauth_token_secret=vbnm&screen_name=foo')\n\n\nclass TwitterServerShowUserHandler(RequestHandler):\n    def get(self, screen_name):\n        if screen_name == 'error':\n            raise HTTPError(500)\n        assert 'oauth_nonce' in self.request.arguments\n        assert 'oauth_timestamp' in self.request.arguments\n        assert 'oauth_signature' in self.request.arguments\n        assert self.get_argument('oauth_consumer_key') == 'test_twitter_consumer_key'\n        assert self.get_argument('oauth_signature_method') == 'HMAC-SHA1'\n        assert self.get_argument('oauth_version') == '1.0'\n        assert self.get_argument('oauth_token') == 'hjkl'\n        self.write(dict(screen_name=screen_name, name=screen_name.capitalize()))\n\n\nclass TwitterServerVerifyCredentialsHandler(RequestHandler):\n    def get(self):\n        assert 'oauth_nonce' in self.request.arguments\n        assert 'oauth_timestamp' in self.request.arguments\n        assert 'oauth_signature' in self.request.arguments\n        assert self.get_argument('oauth_consumer_key') == 'test_twitter_consumer_key'\n        assert self.get_argument('oauth_signature_method') == 'HMAC-SHA1'\n        assert self.get_argument('oauth_version') == '1.0'\n        assert self.get_argument('oauth_token') == 'hjkl'\n        self.write(dict(screen_name='foo', name='Foo'))\n\n\nclass AuthTest(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/openid/client/login', OpenIdClientLoginHandler, dict(test=self)),\n                ('/oauth10/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0')),\n                ('/oauth10/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0')),\n                ('/oauth10a/client/login', OAuth1ClientLoginHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/login_coroutine',\n                 OAuth1ClientLoginCoroutineHandler,\n                 dict(test=self, version='1.0a')),\n                ('/oauth10a/client/request_params',\n                 OAuth1ClientRequestParametersHandler,\n                 dict(version='1.0a')),\n                ('/oauth2/client/login', OAuth2ClientLoginHandler, dict(test=self)),\n\n                ('/facebook/client/login', FacebookClientLoginHandler, dict(test=self)),\n\n                ('/twitter/client/login', TwitterClientLoginHandler, dict(test=self)),\n                ('/twitter/client/login_gen_engine', TwitterClientLoginGenEngineHandler, dict(test=self)),\n                ('/twitter/client/login_gen_coroutine', TwitterClientLoginGenCoroutineHandler, dict(test=self)),\n                ('/twitter/client/show_user', TwitterClientShowUserHandler, dict(test=self)),\n                ('/twitter/client/show_user_future', TwitterClientShowUserFutureHandler, dict(test=self)),\n\n                # simulated servers\n                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler),\n                ('/oauth1/server/request_token', OAuth1ServerRequestTokenHandler),\n                ('/oauth1/server/access_token', OAuth1ServerAccessTokenHandler),\n\n                ('/facebook/server/access_token', FacebookServerAccessTokenHandler),\n                ('/facebook/server/me', FacebookServerMeHandler),\n                ('/twitter/server/access_token', TwitterServerAccessTokenHandler),\n                (r'/twitter/api/users/show/(.*)\\.json', TwitterServerShowUserHandler),\n                (r'/twitter/api/account/verify_credentials\\.json', TwitterServerVerifyCredentialsHandler),\n            ],\n            http_client=self.http_client,\n            twitter_consumer_key='test_twitter_consumer_key',\n            twitter_consumer_secret='test_twitter_consumer_secret',\n            facebook_api_key='test_facebook_api_key',\n            facebook_secret='test_facebook_secret')\n\n    def test_openid_redirect(self):\n        response = self.fetch('/openid/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(\n            '/openid/server/authenticate?' in response.headers['Location'])\n\n    def test_openid_get_user(self):\n        response = self.fetch('/openid/client/login?openid.mode=blah&openid.ns.ax=http://openid.net/srv/ax/1.0&openid.ax.type.email=http://axschema.org/contact/email&openid.ax.value.email=foo@example.com')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed[\"email\"], \"foo@example.com\")\n\n    def test_oauth10_redirect(self):\n        response = self.fetch('/oauth10/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10_get_user(self):\n        response = self.fetch(\n            '/oauth10/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10_request_parameters(self):\n        response = self.fetch('/oauth10/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_redirect(self):\n        response = self.fetch('/oauth10a/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_oauth10a_get_user(self):\n        response = self.fetch(\n            '/oauth10a/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['email'], 'foo@example.com')\n        self.assertEqual(parsed['access_token'], dict(key='uiop', secret='5678'))\n\n    def test_oauth10a_request_parameters(self):\n        response = self.fetch('/oauth10a/client/request_params')\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed['oauth_consumer_key'], 'asdf')\n        self.assertEqual(parsed['oauth_token'], 'uiop')\n        self.assertTrue('oauth_nonce' in parsed)\n        self.assertTrue('oauth_signature' in parsed)\n\n    def test_oauth10a_get_user_coroutine_exception(self):\n        response = self.fetch(\n            '/oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        self.assertEqual(response.code, 503)\n\n    def test_oauth2_redirect(self):\n        response = self.fetch('/oauth2/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/oauth2/server/authorize?' in response.headers['Location'])\n\n    def test_facebook_login(self):\n        response = self.fetch('/facebook/client/login', follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue('/facebook/server/authorize?' in response.headers['Location'])\n        response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n        self.assertEqual(response.code, 200)\n\n    def base_twitter_redirect(self, url):\n        # Same as test_oauth10a_redirect\n        response = self.fetch(url, follow_redirects=False)\n        self.assertEqual(response.code, 302)\n        self.assertTrue(response.headers['Location'].endswith(\n            '/oauth1/server/authorize?oauth_token=zxcv'))\n        # the cookie is base64('zxcv')|base64('1234')\n        self.assertTrue(\n            '_oauth_request_token=\"enhjdg==|MTIzNA==\"' in response.headers['Set-Cookie'],\n            response.headers['Set-Cookie'])\n\n    def test_twitter_redirect(self):\n        self.base_twitter_redirect('/twitter/client/login')\n\n    def test_twitter_redirect_gen_engine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_engine')\n\n    def test_twitter_redirect_gen_coroutine(self):\n        self.base_twitter_redirect('/twitter/client/login_gen_coroutine')\n\n    def test_twitter_get_user(self):\n        response = self.fetch(\n            '/twitter/client/login?oauth_token=zxcv',\n            headers={'Cookie': '_oauth_request_token=enhjdg==|MTIzNA=='})\n        response.rethrow()\n        parsed = json_decode(response.body)\n        self.assertEqual(parsed,\n                         {u('access_token'): {u('key'): u('hjkl'),\n                                              u('screen_name'): u('foo'),\n                                              u('secret'): u('vbnm')},\n                          u('name'): u('Foo'),\n                          u('screen_name'): u('foo'),\n                          u('username'): u('foo')})\n\n    def test_twitter_show_user(self):\n        response = self.fetch('/twitter/client/show_user?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_error(self):\n        with ExpectLog(gen_log, 'Error response HTTP 500'):\n            response = self.fetch('/twitter/client/show_user?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertEqual(response.body, b'error from twitter request')\n\n    def test_twitter_show_user_future(self):\n        response = self.fetch('/twitter/client/show_user_future?name=somebody')\n        response.rethrow()\n        self.assertEqual(json_decode(response.body),\n                         {'name': 'Somebody', 'screen_name': 'somebody'})\n\n    def test_twitter_show_user_future_error(self):\n        response = self.fetch('/twitter/client/show_user_future?name=error')\n        self.assertEqual(response.code, 500)\n        self.assertIn(b'Error response HTTP 500', response.body)\n\n\nclass GoogleLoginHandler(RequestHandler, GoogleOAuth2Mixin):\n    def initialize(self, test):\n        self.test = test\n        self._OAUTH_REDIRECT_URI = test.get_url('/client/login')\n        self._OAUTH_AUTHORIZE_URL = test.get_url('/google/oauth2/authorize')\n        self._OAUTH_ACCESS_TOKEN_URL = test.get_url('/google/oauth2/token')\n\n    @gen.coroutine\n    def get(self):\n        code = self.get_argument('code', None)\n        if code is not None:\n            # retrieve authenticate google user\n            access = yield self.get_authenticated_user(self._OAUTH_REDIRECT_URI,\n                                                       code)\n            user = yield self.oauth2_request(\n                self.test.get_url(\"/google/oauth2/userinfo\"),\n                access_token=access[\"access_token\"])\n            # return the user and access token as json\n            user[\"access_token\"] = access[\"access_token\"]\n            self.write(user)\n        else:\n            yield self.authorize_redirect(\n                redirect_uri=self._OAUTH_REDIRECT_URI,\n                client_id=self.settings['google_oauth']['key'],\n                client_secret=self.settings['google_oauth']['secret'],\n                scope=['profile', 'email'],\n                response_type='code',\n                extra_params={'prompt': 'select_account'})\n\n\nclass GoogleOAuth2AuthorizeHandler(RequestHandler):\n    def get(self):\n        # issue a fake auth code and redirect to redirect_uri\n        code = 'fake-authorization-code'\n        self.redirect(url_concat(self.get_argument('redirect_uri'),\n                                 dict(code=code)))\n\n\nclass GoogleOAuth2TokenHandler(RequestHandler):\n    def post(self):\n        assert self.get_argument('code') == 'fake-authorization-code'\n        # issue a fake token\n        self.finish({\n            'access_token': 'fake-access-token',\n            'expires_in': 'never-expires'\n        })\n\n\nclass GoogleOAuth2UserinfoHandler(RequestHandler):\n    def get(self):\n        assert self.get_argument('access_token') == 'fake-access-token'\n        # return a fake user\n        self.finish({\n                'name': 'Foo',\n                'email': 'foo@example.com'\n                })\n\n\nclass GoogleOAuth2Test(AsyncHTTPTestCase):\n    def get_app(self):\n        return Application(\n            [\n                # test endpoints\n                ('/client/login', GoogleLoginHandler, dict(test=self)),\n\n                # simulated google authorization server endpoints\n                ('/google/oauth2/authorize', GoogleOAuth2AuthorizeHandler),\n                ('/google/oauth2/token', GoogleOAuth2TokenHandler),\n                ('/google/oauth2/userinfo', GoogleOAuth2UserinfoHandler),\n            ],\n            google_oauth={\n                \"key\": 'fake_google_client_id',\n                \"secret\": 'fake_google_client_secret'\n            })\n\n    def test_google_login(self):\n        response = self.fetch('/client/login')\n        self.assertDictEqual({\n            u('name'): u('Foo'),\n            u('email'): u('foo@example.com'),\n            u('access_token'): u('fake-access-token'),\n        }, json_decode(response.body))\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 665ms\nPrepared 1 package in 1.12s\nInstalled 1 package in 0.66ms\n + tornado==4.3.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567)\nResolved 29 packages in 15ms\nInstalled 29 packages in 95ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567\n....................\ncollected 20 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::AuthTest::test_facebook_login\nPASSED r2e_tests.test_1::AuthTest::test_oauth10_get_user\nPASSED r2e_tests.test_1::AuthTest::test_oauth10_redirect\nPASSED r2e_tests.test_1::AuthTest::test_oauth10_request_parameters\nPASSED r2e_tests.test_1::AuthTest::test_oauth10a_get_user\nPASSED r2e_tests.test_1::AuthTest::test_oauth10a_get_user_coroutine_exception\nPASSED r2e_tests.test_1::AuthTest::test_oauth10a_redirect\nPASSED r2e_tests.test_1::AuthTest::test_oauth10a_request_parameters\nPASSED r2e_tests.test_1::AuthTest::test_oauth2_redirect\nPASSED r2e_tests.test_1::AuthTest::test_openid_get_user\nPASSED r2e_tests.test_1::AuthTest::test_openid_redirect\nPASSED r2e_tests.test_1::AuthTest::test_twitter_get_user\nPASSED r2e_tests.test_1::AuthTest::test_twitter_redirect\nPASSED r2e_tests.test_1::AuthTest::test_twitter_redirect_gen_coroutine\nPASSED r2e_tests.test_1::AuthTest::test_twitter_redirect_gen_engine\nPASSED r2e_tests.test_1::AuthTest::test_twitter_show_user\nPASSED r2e_tests.test_1::AuthTest::test_twitter_show_user_error\nPASSED r2e_tests.test_1::AuthTest::test_twitter_show_user_future\nPASSED r2e_tests.test_1::AuthTest::test_twitter_show_user_future_error\nPASSED r2e_tests.test_1::GoogleOAuth2Test::test_google_login\n=================== 20 passed in 0.09s ===================\n",
    "new_commit_res_stderr": "ERROR:tornado.access:503 GET /oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true (127.0.0.1) 2.35ms\nERROR:tornado.access:500 GET /twitter/api/users/show/error.json?oauth_consumer_key=test_twitter_consumer_key&oauth_token=hjkl&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1735739610&oauth_nonce=aa6e8590f9e94fdaaacba4373db12610&oauth_version=1.0&oauth_signature=hjrTPXMxzCSX%2Beu%2FJX%2BoYHHwRZA%3D (127.0.0.1) 0.29ms\nERROR:tornado.access:500 GET /twitter/client/show_user?name=error (127.0.0.1) 1.93ms\nERROR:tornado.access:500 GET /twitter/api/users/show/error.json?oauth_consumer_key=test_twitter_consumer_key&oauth_token=hjkl&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1735739610&oauth_nonce=fd61984854b1458999cb5844092450f0&oauth_version=1.0&oauth_signature=Ium8%2BzTU3ZZq9ToU2ZPXUMwk2rA%3D (127.0.0.1) 0.24ms\nERROR:tornado.access:500 GET /twitter/client/show_user_future?name=error (127.0.0.1) 1.51ms\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567\n....................\ncollected 20 items\n\n=================================== FAILURES ===================================\n__________ AuthTest.test_facebook_login __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567/tornado/testing.py\", line 125, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567/r2e_tests/test_1.py\", line 403, in test_facebook_login\n    response = self.fetch('/facebook/client/login?code=1234', follow_redirects=False)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567/tornado/testing.py\", line 395, in fetch\n    return self.wait()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567/tornado/testing.py\", line 325, in wait\n    self.__rethrow()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567/tornado/testing.py\", line 261, in __rethrow\n    raise_exc_info(failure)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567/tornado/testing.py\", line 307, in timeout_func\n    raise self.failureException(\nAssertionError: Async operation timed out after 5 seconds\n\n==================== short test summary info ====================\nFAILED r2e_tests.test_1::AuthTest::test_facebook_login\nPASSED r2e_tests.test_1::AuthTest::test_oauth10_get_user\nPASSED r2e_tests.test_1::AuthTest::test_oauth10_redirect\nPASSED r2e_tests.test_1::AuthTest::test_oauth10_request_parameters\nPASSED r2e_tests.test_1::AuthTest::test_oauth10a_get_user\nPASSED r2e_tests.test_1::AuthTest::test_oauth10a_get_user_coroutine_exception\nPASSED r2e_tests.test_1::AuthTest::test_oauth10a_redirect\nPASSED r2e_tests.test_1::AuthTest::test_oauth10a_request_parameters\nPASSED r2e_tests.test_1::AuthTest::test_oauth2_redirect\nPASSED r2e_tests.test_1::AuthTest::test_openid_get_user\nPASSED r2e_tests.test_1::AuthTest::test_openid_redirect\nPASSED r2e_tests.test_1::AuthTest::test_twitter_get_user\nPASSED r2e_tests.test_1::AuthTest::test_twitter_redirect\nPASSED r2e_tests.test_1::AuthTest::test_twitter_redirect_gen_coroutine\nPASSED r2e_tests.test_1::AuthTest::test_twitter_redirect_gen_engine\nPASSED r2e_tests.test_1::AuthTest::test_twitter_show_user\nPASSED r2e_tests.test_1::AuthTest::test_twitter_show_user_error\nPASSED r2e_tests.test_1::AuthTest::test_twitter_show_user_future\nPASSED r2e_tests.test_1::AuthTest::test_twitter_show_user_future_error\nPASSED r2e_tests.test_1::GoogleOAuth2Test::test_google_login\n=================== 1 failed, 19 passed in 5.07s ===================\n",
    "old_commit_res_stderr": "ERROR:tornado.application:Exception in callback functools.partial(<function _auth_future_to_callback at 0x75adfcb5a820>, <tornado.concurrent.Future object at 0x75adfc5a13d0>) for <tornado.concurrent.Future object at 0x75adfc59a490>\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567/tornado/concurrent.py\", line 317, in _set_done\n    cb(self)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_301f52b532c071a0d2fec1eb7c23f2714bb38567/tornado/auth.py\", line 113, in _auth_future_to_callback\n    callback(result)\nTypeError: 'Future' object is not callable\nERROR:tornado.access:503 GET /oauth10a/client/login_coroutine?oauth_token=zxcv&fail_in_get_user=true (127.0.0.1) 1.62ms\nERROR:tornado.access:500 GET /twitter/api/users/show/error.json?oauth_consumer_key=test_twitter_consumer_key&oauth_token=hjkl&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1735739616&oauth_nonce=591f940ca26a41a4905a12a139d3d07d&oauth_version=1.0&oauth_signature=5508QyncGO%2F2HEhD%2FpLk7LfMusU%3D (127.0.0.1) 0.22ms\nERROR:tornado.access:500 GET /twitter/client/show_user?name=error (127.0.0.1) 1.49ms\nERROR:tornado.access:500 GET /twitter/api/users/show/error.json?oauth_consumer_key=test_twitter_consumer_key&oauth_token=hjkl&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1735739616&oauth_nonce=311c66b01e06421f80f5e9457149c30d&oauth_version=1.0&oauth_signature=ImY%2BW1nMzo%2BMRGPpCyX9Yv0txhA%3D (127.0.0.1) 0.22ms\nERROR:tornado.access:500 GET /twitter/client/show_user_future?name=error (127.0.0.1) 1.43ms\n"
}
tornado/auth.py tornado/test/auth_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Facebook login request hangs and results in timeout

**Description:**
When attempting to authenticate via Facebook, the login request does not complete and eventually times out. This issue occurs when access tokens are returned as bytes, causing the user objects to be non-JSON-encodable and disrupting the authentication flow.

**Example Code:**
```python
response = fetch('/facebook/client/login', follow_redirects=False)
if response.code == 302:
    response = fetch('/facebook/client/login?code=1234', follow_redirects=False)
    # The operation times out here
```

**Expected Behavior:**
After initiating the Facebook login with a valid authentication code, the server should process the request successfully and respond with a status code of 200, completing the user authentication.

**Actual Behavior:**
The authentication request hangs and times out after 5 seconds without completing, preventing the user from being authenticated.
[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/auth.py
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""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:

.. testcode::

    class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
                                   tornado.auth.GoogleOAuth2Mixin):
        @tornado.gen.coroutine
        def get(self):
            if self.get_argument('code', False):
                user = yield self.get_authenticated_user(
                    redirect_uri='http://your.site.com/auth/google',
                    code=self.get_argument('code'))
                # Save the user with e.g. set_secure_cookie
            else:
                yield 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:


.. versionchanged:: 4.0
   All of the callback interfaces in this module are now guaranteed
   to run their callback with an argument of ``None`` on error.
   Previously some functions would do this while others would simply
   terminate the request on their own.  This change also ensures that
   errors are more consistently reported through the ``Future`` interfaces.
"""

from __future__ import absolute_import, division, print_function, with_statement

import base64
import binascii
import functools
import hashlib
import hmac
import time
import uuid

from tornado.concurrent import TracebackFuture, return_future
from tornado import gen
from tornado import httpclient
from tornado import escape
from tornado.httputil import url_concat
from tornado.log import gen_log
from tornado.stack_context import ExceptionStackContext
from tornado.util import u, unicode_type, ArgReplacer

try:
    import urlparse  # py2
except ImportError:
    import urllib.parse as urlparse  # py3

try:
    import urllib.parse as urllib_parse  # py3
except ImportError:
    import urllib as urllib_parse  # py2

try:
    long  # py2
except NameError:
    long = int  # py3


class AuthError(Exception):
    pass


def _auth_future_to_callback(callback, future):
    try:
        result = future.result()
    except AuthError as e:
        gen_log.warning(str(e))
        result = None
    callback(result)


def _auth_return_future(f):
    """Similar to tornado.concurrent.return_future, but uses the auth
    module's legacy callback interface.

    Note that when using this decorator the ``callback`` parameter
    inside the function will actually be a future.
    """
    replacer = ArgReplacer(f, 'callback')

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        future = TracebackFuture()
        callback, args, kwargs = replacer.replace(future, args, kwargs)
        if callback is not None:
            future.add_done_callback(
                functools.partial(_auth_future_to_callback, callback))

        def handle_exception(typ, value, tb):
            if future.done():
                return False
            else:
                future.set_exc_info((typ, value, tb))
                return True
        with ExceptionStackContext(handle_exception):
            f(*args, **kwargs)
        return future
    return wrapper


class OpenIdMixin(object):
    """Abstract implementation of OpenID and Attribute Exchange.

    Class attributes:

    * ``_OPENID_ENDPOINT``: the identity provider's URI.
    """
    @return_future
    def authenticate_redirect(self, callback_uri=None,
                              ax_attrs=["name", "email", "language", "username"],
                              callback=None):
        """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:: 3.1
           Returns a `.Future` and takes an optional callback.  These are
           not strictly necessary as this method is synchronous,
           but they are supplied for consistency with
           `OAuthMixin.authorize_redirect`.
        """
        callback_uri = callback_uri or self.request.uri
        args = self._openid_args(callback_uri, ax_attrs=ax_attrs)
        self.redirect(self._OPENID_ENDPOINT + "?" + urllib_parse.urlencode(args))
        callback()

    @_auth_return_future
    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.
        """
        # 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()
        http_client.fetch(url, functools.partial(
            self._on_authentication_verified, callback),
            method="POST", body=urllib_parse.urlencode(args))

    def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):
        url = urlparse.urljoin(self.request.full_url(), callback_uri)
        args = {
            "openid.ns": "http://specs.openid.net/auth/2.0",
            "openid.claimed_id":
            "http://specs.openid.net/auth/2.0/identifier_select",
            "openid.identity":
            "http://specs.openid.net/auth/2.0/identifier_select",
            "openid.return_to": url,
            "openid.realm": urlparse.urljoin(url, '/'),
            "openid.mode": "checkid_setup",
        }
        if ax_attrs:
            args.update({
                "openid.ns.ax": "http://openid.net/srv/ax/1.0",
                "openid.ax.mode": "fetch_request",
            })
            ax_attrs = set(ax_attrs)
            required = []
            if "name" in ax_attrs:
                ax_attrs -= set(["name", "firstname", "fullname", "lastname"])
                required += ["firstname", "fullname", "lastname"]
                args.update({
                    "openid.ax.type.firstname":
                    "http://axschema.org/namePerson/first",
                    "openid.ax.type.fullname":
                    "http://axschema.org/namePerson",
                    "openid.ax.type.lastname":
                    "http://axschema.org/namePerson/last",
                })
            known_attrs = {
                "email": "http://axschema.org/contact/email",
                "language": "http://axschema.org/pref/language",
                "username": "http://axschema.org/namePerson/friendly",
            }
            for name in ax_attrs:
                args["openid.ax.type." + name] = known_attrs[name]
                required.append(name)
            args["openid.ax.required"] = ",".join(required)
        if oauth_scope:
            args.update({
                "openid.ns.oauth":
                "http://specs.openid.net/extensions/oauth/1.0",
                "openid.oauth.consumer": self.request.host.split(":")[0],
                "openid.oauth.scope": oauth_scope,
            })
        return args

    def _on_authentication_verified(self, future, response):
        if response.error or b"is_valid:true" not in response.body:
            future.set_exception(AuthError(
                "Invalid OpenID response: %s" % (response.error or
                                                 response.body)))
            return

        # Make sure we got back at least an email from attribute exchange
        ax_ns = None
        for name in self.request.arguments:
            if name.startswith("openid.ns.") and \
                    self.get_argument(name) == u("http://openid.net/srv/ax/1.0"):
                ax_ns = name[10:]
                break

        def get_ax_arg(uri):
            if not ax_ns:
                return u("")
            prefix = "openid." + ax_ns + ".type."
            ax_name = None
            for name in self.request.arguments.keys():
                if self.get_argument(name) == uri and name.startswith(prefix):
                    part = name[len(prefix):]
                    ax_name = "openid." + ax_ns + ".value." + part
                    break
            if not ax_name:
                return u("")
            return self.get_argument(ax_name, u(""))

        email = get_ax_arg("http://axschema.org/contact/email")
        name = get_ax_arg("http://axschema.org/namePerson")
        first_name = get_ax_arg("http://axschema.org/namePerson/first")
        last_name = get_ax_arg("http://axschema.org/namePerson/last")
        username = get_ax_arg("http://axschema.org/namePerson/friendly")
        locale = get_ax_arg("http://axschema.org/pref/language").lower()
        user = dict()
        name_parts = []
        if first_name:
            user["first_name"] = first_name
            name_parts.append(first_name)
        if last_name:
            user["last_name"] = last_name
            name_parts.append(last_name)
        if name:
            user["name"] = name
        elif name_parts:
            user["name"] = u(" ").join(name_parts)
        elif email:
            user["name"] = email.split("@")[0]
        if email:
            user["email"] = email
        if locale:
            user["locale"] = locale
        if username:
            user["username"] = username
        claimed_id = self.get_argument("openid.claimed_id", None)
        if claimed_id:
            user["claimed_id"] = claimed_id
        future.set_result(user)

    def get_auth_http_client(self):
        """Returns the `.AsyncHTTPClient` instance to be used for auth requests.

        May be overridden by subclasses to use an HTTP client other than
        the default.
        """
        return httpclient.AsyncHTTPClient()


class OAuthMixin(object):
    """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.
    """
    @return_future
    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 (including Friendfeed), 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.

        Note that this method is asynchronous, although it calls
        `.RequestHandler.finish` for you so it may not be necessary
        to pass a callback or use the `.Future` it returns.  However,
        if this method is called from a function decorated with
        `.gen.coroutine`, you must call it with ``yield`` to keep the
        response from being closed prematurely.

        .. versionchanged:: 3.1
           Now returns a `.Future` and takes an optional callback, for
           compatibility with `.gen.coroutine`.
        """
        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":
            http_client.fetch(
                self._oauth_request_token_url(callback_uri=callback_uri,
                                              extra_params=extra_params),
                functools.partial(
                    self._on_request_token,
                    self._OAUTH_AUTHORIZE_URL,
                    callback_uri,
                    callback))
        else:
            http_client.fetch(
                self._oauth_request_token_url(),
                functools.partial(
                    self._on_request_token, self._OAUTH_AUTHORIZE_URL,
                    callback_uri,
                    callback))

    @_auth_return_future
    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.
        """
        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()
        http_client.fetch(self._oauth_access_token_url(token),
                          functools.partial(self._on_access_token, callback))

    def _oauth_request_token_url(self, callback_uri=None, extra_params=None):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_REQUEST_TOKEN_URL
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            if callback_uri == "oob":
                args["oauth_callback"] = "oob"
            elif callback_uri:
                args["oauth_callback"] = urlparse.urljoin(
                    self.request.full_url(), callback_uri)
            if extra_params:
                args.update(extra_params)
            signature = _oauth10a_signature(consumer_token, "GET", url, args)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args)

        args["oauth_signature"] = signature
        return url + "?" + urllib_parse.urlencode(args)

    def _on_request_token(self, authorize_url, callback_uri, callback,
                          response):
        if response.error:
            raise Exception("Could not get request token: %s" % response.error)
        request_token = _oauth_parse_response(response.body)
        data = (base64.b64encode(escape.utf8(request_token["key"])) + b"|" +
                base64.b64encode(escape.utf8(request_token["secret"])))
        self.set_cookie("_oauth_request_token", data)
        args = dict(oauth_token=request_token["key"])
        if callback_uri == "oob":
            self.finish(authorize_url + "?" + urllib_parse.urlencode(args))
            callback()
            return
        elif callback_uri:
            args["oauth_callback"] = urlparse.urljoin(
                self.request.full_url(), callback_uri)
        self.redirect(authorize_url + "?" + urllib_parse.urlencode(args))
        callback()

    def _oauth_access_token_url(self, request_token):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_ACCESS_TOKEN_URL
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_token=escape.to_basestring(request_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if "verifier" in request_token:
            args["oauth_verifier"] = request_token["verifier"]

        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(consumer_token, "GET", url, args,
                                            request_token)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args,
                                         request_token)

        args["oauth_signature"] = signature
        return url + "?" + urllib_parse.urlencode(args)

    def _on_access_token(self, future, response):
        if response.error:
            future.set_exception(AuthError("Could not fetch access token"))
            return

        access_token = _oauth_parse_response(response.body)
        self._oauth_get_user_future(access_token).add_done_callback(
            functools.partial(self._on_oauth_get_user, access_token, future))

    def _oauth_consumer_token(self):
        """Subclasses must override this to return their OAuth consumer keys.

        The return value should be a `dict` with keys ``key`` and ``secret``.
        """
        raise NotImplementedError()

    @return_future
    def _oauth_get_user_future(self, access_token, callback):
        """Subclasses must override this to get basic information about the
        user.

        Should return a `.Future` 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`.

        For backwards compatibility, the callback-based ``_oauth_get_user``
        method is also supported.
        """
        # By default, call the old-style _oauth_get_user, but new code
        # should override this method instead.
        self._oauth_get_user(access_token, callback)

    def _oauth_get_user(self, access_token, callback):
        raise NotImplementedError()

    def _on_oauth_get_user(self, access_token, future, user_future):
        if user_future.exception() is not None:
            future.set_exception(user_future.exception())
            return
        user = user_future.result()
        if not user:
            future.set_exception(AuthError("Error getting user"))
            return
        user["access_token"] = access_token
        future.set_result(user)

    def _oauth_request_parameters(self, url, access_token, parameters={},
                                  method="GET"):
        """Returns 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.
        """
        consumer_token = self._oauth_consumer_token()
        base_args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_token=escape.to_basestring(access_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        args = {}
        args.update(base_args)
        args.update(parameters)
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(consumer_token, method, url, args,
                                            access_token)
        else:
            signature = _oauth_signature(consumer_token, method, url, args,
                                         access_token)
        base_args["oauth_signature"] = escape.to_basestring(signature)
        return base_args

    def get_auth_http_client(self):
        """Returns the `.AsyncHTTPClient` instance to be used for auth requests.

        May be overridden by subclasses to use an HTTP client other than
        the default.
        """
        return httpclient.AsyncHTTPClient()


class OAuth2Mixin(object):
    """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.
    """
    @return_future
    def authorize_redirect(self, redirect_uri=None, client_id=None,
                           client_secret=None, extra_params=None,
                           callback=None, scope=None, response_type="code"):
        """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:: 3.1
           Returns a `.Future` and takes an optional callback.  These are
           not strictly necessary as this method is synchronous,
           but they are supplied for consistency with
           `OAuthMixin.authorize_redirect`.
        """
        args = {
            "redirect_uri": redirect_uri,
            "client_id": client_id,
            "response_type": response_type
        }
        if extra_params:
            args.update(extra_params)
        if scope:
            args['scope'] = ' '.join(scope)
        self.redirect(
            url_concat(self._OAUTH_AUTHORIZE_URL, args))
        callback()

    def _oauth_request_token_url(self, redirect_uri=None, client_id=None,
                                 client_secret=None, code=None,
                                 extra_params=None):
        url = self._OAUTH_ACCESS_TOKEN_URL
        args = dict(
            redirect_uri=redirect_uri,
            code=code,
            client_id=client_id,
            client_secret=client_secret,
        )
        if extra_params:
            args.update(extra_params)
        return url_concat(url, args)

    @_auth_return_future
    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
                @tornado.gen.coroutine
                def get(self):
                    new_entry = yield 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?
                        yield self.authorize_redirect()
                        return
                    self.finish("Posted a message!")

        .. testoutput::
           :hide:

        .. versionadded:: 4.3
        """
        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 = functools.partial(self._on_oauth2_request, callback)
        http = self.get_auth_http_client()
        if post_args is not None:
            http.fetch(url, method="POST", body=urllib_parse.urlencode(post_args),
                       callback=callback)
        else:
            http.fetch(url, callback=callback)

    def _on_oauth2_request(self, future, response):
        if response.error:
            future.set_exception(AuthError("Error response %s fetching %s" %
                                           (response.error, response.request.url)))
            return

        future.set_result(escape.json_decode(response.body))

    def get_auth_http_client(self):
        """Returns 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
        """
        return httpclient.AsyncHTTPClient()


class TwitterMixin(OAuthMixin):
    """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):
            @tornado.gen.coroutine
            def get(self):
                if self.get_argument("oauth_token", None):
                    user = yield self.get_authenticated_user()
                    # Save the user using e.g. set_secure_cookie()
                else:
                    yield self.authorize_redirect()

    .. testoutput::
       :hide:

    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
    """
    _OAUTH_REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
    _OAUTH_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"
    _OAUTH_AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize"
    _OAUTH_AUTHENTICATE_URL = "https://api.twitter.com/oauth/authenticate"
    _OAUTH_NO_CALLBACKS = False
    _TWITTER_BASE_URL = "https://api.twitter.com/1.1"

    @return_future
    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`.
        """
        http = self.get_auth_http_client()
        http.fetch(self._oauth_request_token_url(callback_uri=callback_uri),
                   functools.partial(
                       self._on_request_token, self._OAUTH_AUTHENTICATE_URL,
                       None, callback))

    @_auth_return_future
    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
                @tornado.gen.coroutine
                def get(self):
                    new_entry = yield 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:

        """
        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 = functools.partial(self._on_twitter_request, callback)
        if post_args is not None:
            http.fetch(url, method="POST", body=urllib_parse.urlencode(post_args),
                       callback=http_callback)
        else:
            http.fetch(url, callback=http_callback)

    def _on_twitter_request(self, future, response):
        if response.error:
            future.set_exception(AuthError(
                "Error response %s fetching %s" % (response.error,
                                                   response.request.url)))
            return
        future.set_result(escape.json_decode(response.body))

    def _oauth_consumer_token(self):
        self.require_setting("twitter_consumer_key", "Twitter OAuth")
        self.require_setting("twitter_consumer_secret", "Twitter OAuth")
        return dict(
            key=self.settings["twitter_consumer_key"],
            secret=self.settings["twitter_consumer_secret"])

    @gen.coroutine
    def _oauth_get_user_future(self, access_token):
        user = yield self.twitter_request(
            "/account/verify_credentials",
            access_token=access_token)
        if user:
            user["username"] = user["screen_name"]
        raise gen.Return(user)


class GoogleOAuth2Mixin(OAuth2Mixin):
    """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.
    * In the sidebar on the left, select APIs & Auth.
    * In the list of APIs, find the Google+ API service and set it to ON.
    * In the sidebar on the left, select Credentials.
    * In the OAuth section of the page, select Create New Client ID.
    * Set the Redirect URI to point to your auth handler
    * Copy the "Client secret" and "Client ID" to the application settings as
      {"google_oauth": {"key": CLIENT_ID, "secret": CLIENT_SECRET}}

    .. versionadded:: 3.2
    """
    _OAUTH_AUTHORIZE_URL = "https://accounts.google.com/o/oauth2/auth"
    _OAUTH_ACCESS_TOKEN_URL = "https://accounts.google.com/o/oauth2/token"
    _OAUTH_USERINFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo"
    _OAUTH_NO_CALLBACKS = False
    _OAUTH_SETTINGS_KEY = 'google_oauth'

    @_auth_return_future
    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):
                @tornado.gen.coroutine
                def get(self):
                    if self.get_argument('code', False):
                        access = yield self.get_authenticated_user(
                            redirect_uri='http://your.site.com/auth/google',
                            code=self.get_argument('code'))
                        user = yield 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:
                        yield 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:

        """
        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",
        })

        http.fetch(self._OAUTH_ACCESS_TOKEN_URL,
                   functools.partial(self._on_access_token, callback),
                   method="POST", headers={'Content-Type': 'application/x-www-form-urlencoded'}, body=body)

    def _on_access_token(self, future, response):
        """Callback function for the exchange to the access token."""
        if response.error:
            future.set_exception(AuthError('Google auth error: %s' % str(response)))
            return

        args = escape.json_decode(response.body)
        future.set_result(args)


class FacebookGraphMixin(OAuth2Mixin):
    """Facebook authentication using the new Graph API and OAuth2."""
    _OAUTH_ACCESS_TOKEN_URL = "https://graph.facebook.com/oauth/access_token?"
    _OAUTH_AUTHORIZE_URL = "https://www.facebook.com/dialog/oauth?"
    _OAUTH_NO_CALLBACKS = False
    _FACEBOOK_BASE_URL = "https://graph.facebook.com"

    @_auth_return_future
    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):
              @tornado.gen.coroutine
              def get(self):
                  if self.get_argument("code", False):
                      user = yield 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:
                      yield self.authorize_redirect(
                          redirect_uri='/auth/facebookgraph/',
                          client_id=self.settings["facebook_api_key"],
                          extra_params={"scope": "read_stream,offline_access"})

        .. testoutput::
           :hide:

        """
        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)

        http.fetch(self._oauth_request_token_url(**args),
                   functools.partial(self._on_access_token, redirect_uri, client_id,
                                     client_secret, callback, fields))

    def _on_access_token(self, redirect_uri, client_id, client_secret,
                         future, fields, response):
        if response.error:
            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))
            return

        args = escape.parse_qs_bytes(escape.native_str(response.body))
        session = {
            "access_token": args["access_token"][-1],
            "expires": args.get("expires")
        }

        self.facebook_request(
            path="/me",
            callback=functools.partial(
                self._on_get_user_info, future, session, fields),
            access_token=session["access_token"],
            fields=",".join(fields)
        )

    def _on_get_user_info(self, future, session, fields, user):
        if user is None:
            future.set_result(None)
            return

        fieldmap = {}
        for field in fields:
            fieldmap[field] = user.get(field)

        fieldmap.update({"access_token": session["access_token"], "session_expires": session.get("expires")})
        future.set_result(fieldmap)

    @_auth_return_future
    def facebook_request(self, path, callback, access_token=None,
                         post_args=None, **args):
        """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
                @tornado.gen.coroutine
                def get(self):
                    new_entry = yield 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?
                        yield self.authorize_redirect()
                        return
                    self.finish("Posted a message!")

        .. testoutput::
           :hide:

        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``.
        """
        url = self._FACEBOOK_BASE_URL + path
        return self.oauth2_request(url, callback, access_token,
                                   post_args, **args)


def _oauth_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth signature for the given request.

    See http://oauth.net/core/1.0/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))
    base_string = "&".join(_oauth_escape(e) for e in base_elems)

    key_elems = [escape.utf8(consumer_token["secret"])]
    key_elems.append(escape.utf8(token["secret"] if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1]


def _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.

    See http://oauth.net/core/1.0a/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))

    base_string = "&".join(_oauth_escape(e) for e in base_elems)
    key_elems = [escape.utf8(urllib_parse.quote(consumer_token["secret"], safe='~'))]
    key_elems.append(escape.utf8(urllib_parse.quote(token["secret"], safe='~') if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1]


def _oauth_escape(val):
    if isinstance(val, unicode_type):
        val = val.encode("utf-8")
    return urllib_parse.quote(val, safe="~")


def _oauth_parse_response(body):
    # I can't find an officially-defined encoding for oauth responses and
    # have never seen anyone use non-ascii.  Leave the response in a byte
    # string for python 2, and use utf8 on python 3.
    body = escape.native_str(body)
    p = urlparse.parse_qs(body, keep_blank_values=False)
    token = dict(key=p["oauth_token"][0], secret=p["oauth_token_secret"][0])

    # Add the extra parameters the Provider included to the token
    special = ("oauth_token", "oauth_token_secret")
    token.update((k, p[k][0]) for k in p if k not in special)
    return token

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** Facebook login request hangs and results in timeout

**Description:**
When attempting to authenticate via Facebook, the login request does not complete and eventually times out. This issue occurs when access tokens are returned as bytes, causing the user objects to be non-JSON-encodable and disrupting the authentication flow.

**Example Code:**
```python
response = fetch('/facebook/client/login', follow_redirects=False)
if response.code == 302:
    response = fetch('/facebook/client/login?code=1234', follow_redirects=False)
    # The operation times out here
```

**Expected Behavior:**
After initiating the Facebook login with a valid authentication code, the server should process the request successfully and respond with a status code of 200, completing the user authentication.

**Actual Behavior:**
The authentication request hangs and times out after 5 seconds without completing, preventing the user from being authenticated.
[/ISSUE]
{
    "AuthTest.test_facebook_login": "PASSED",
    "AuthTest.test_oauth10_get_user": "PASSED",
    "AuthTest.test_oauth10_redirect": "PASSED",
    "AuthTest.test_oauth10_request_parameters": "PASSED",
    "AuthTest.test_oauth10a_get_user": "PASSED",
    "AuthTest.test_oauth10a_get_user_coroutine_exception": "PASSED",
    "AuthTest.test_oauth10a_redirect": "PASSED",
    "AuthTest.test_oauth10a_request_parameters": "PASSED",
    "AuthTest.test_oauth2_redirect": "PASSED",
    "AuthTest.test_openid_get_user": "PASSED",
    "AuthTest.test_openid_redirect": "PASSED",
    "AuthTest.test_twitter_get_user": "PASSED",
    "AuthTest.test_twitter_redirect": "PASSED",
    "AuthTest.test_twitter_redirect_gen_coroutine": "PASSED",
    "AuthTest.test_twitter_redirect_gen_engine": "PASSED",
    "AuthTest.test_twitter_show_user": "PASSED",
    "AuthTest.test_twitter_show_user_error": "PASSED",
    "AuthTest.test_twitter_show_user_future": "PASSED",
    "AuthTest.test_twitter_show_user_future_error": "PASSED",
    "GoogleOAuth2Test.test_google_login": "PASSED"
}
diff --git a/tornado/auth.py b/tornado/auth.py
index 32d0e226..ff7172aa 100644
--- a/tornado/auth.py
+++ b/tornado/auth.py
@@ -75,7 +75,7 @@ import hmac
 import time
 import uuid
 
-from tornado.concurrent import TracebackFuture, return_future
+from tornado.concurrent import TracebackFuture, return_future, chain_future
 from tornado import gen
 from tornado import httpclient
 from tornado import escape
@@ -985,7 +985,7 @@ class FacebookGraphMixin(OAuth2Mixin):
             future.set_exception(AuthError('Facebook auth error: %s' % str(response)))
             return
 
-        args = escape.parse_qs_bytes(escape.native_str(response.body))
+        args = urlparse.parse_qs(escape.native_str(response.body))
         session = {
             "access_token": args["access_token"][-1],
             "expires": args.get("expires")
@@ -1062,8 +1062,13 @@ class FacebookGraphMixin(OAuth2Mixin):
            Added the ability to override ``self._FACEBOOK_BASE_URL``.
         """
         url = self._FACEBOOK_BASE_URL + path
-        return self.oauth2_request(url, callback, access_token,
-                                   post_args, **args)
+        # Thanks to the _auth_return_future decorator, our "callback"
+        # argument is a Future, which we cannot pass as a callback to
+        # oauth2_request. Instead, have oauth2_request return a
+        # future and chain them together.
+        oauth_future = self.oauth2_request(url, access_token=access_token,
+                                           post_args=post_args, **args)
+        chain_future(oauth_future, callback)
 
 
 def _oauth_signature(consumer_token, method, url, parameters={}, token=None):

{"tornado/auth.py": "#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"This module contains implementations of various third-party\nauthentication schemes.\n\nAll the classes in this file are class mixins designed to be used with\nthe `tornado.web.RequestHandler` class.  They are used in two ways:\n\n* On a login handler, use methods such as ``authenticate_redirect()``,\n  ``authorize_redirect()``, and ``get_authenticated_user()`` to\n  establish the user's identity and store authentication tokens to your\n  database and/or cookies.\n* In non-login handlers, use methods such as ``facebook_request()``\n  or ``twitter_request()`` to use the authentication tokens to make\n  requests to the respective services.\n\nThey all take slightly different arguments due to the fact all these\nservices implement authentication and authorization slightly differently.\nSee the individual service classes below for complete documentation.\n\nExample usage for Google OAuth:\n\n.. testcode::\n\n    class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n                                   tornado.auth.GoogleOAuth2Mixin):\n        @tornado.gen.coroutine\n        def get(self):\n            if self.get_argument('code', False):\n                user = yield self.get_authenticated_user(\n                    redirect_uri='http://your.site.com/auth/google',\n                    code=self.get_argument('code'))\n                # Save the user with e.g. set_secure_cookie\n            else:\n                yield self.authorize_redirect(\n                    redirect_uri='http://your.site.com/auth/google',\n                    client_id=self.settings['google_oauth']['key'],\n                    scope=['profile', 'email'],\n                    response_type='code',\n                    extra_params={'approval_prompt': 'auto'})\n\n.. testoutput::\n   :hide:\n\n\n.. versionchanged:: 4.0\n   All of the callback interfaces in this module are now guaranteed\n   to run their callback with an argument of ``None`` on error.\n   Previously some functions would do this while others would simply\n   terminate the request on their own.  This change also ensures that\n   errors are more consistently reported through the ``Future`` interfaces.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport base64\nimport binascii\nimport functools\nimport hashlib\nimport hmac\nimport time\nimport uuid\n\nfrom tornado.concurrent import TracebackFuture, return_future\nfrom tornado import gen\nfrom tornado import httpclient\nfrom tornado import escape\nfrom tornado.httputil import url_concat\nfrom tornado.log import gen_log\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.util import u, unicode_type, ArgReplacer\n\ntry:\n    import urlparse  # py2\nexcept ImportError:\n    import urllib.parse as urlparse  # py3\n\ntry:\n    import urllib.parse as urllib_parse  # py3\nexcept ImportError:\n    import urllib as urllib_parse  # py2\n\ntry:\n    long  # py2\nexcept NameError:\n    long = int  # py3\n\n\nclass AuthError(Exception):\n    pass\n\n\ndef _auth_future_to_callback(callback, future):\n    try:\n        result = future.result()\n    except AuthError as e:\n        gen_log.warning(str(e))\n        result = None\n    callback(result)\n\n\ndef _auth_return_future(f):\n    \"\"\"Similar to tornado.concurrent.return_future, but uses the auth\n    module's legacy callback interface.\n\n    Note that when using this decorator the ``callback`` parameter\n    inside the function will actually be a future.\n    \"\"\"\n    replacer = ArgReplacer(f, 'callback')\n\n    @functools.wraps(f)\n    def wrapper(*args, **kwargs):\n        future = TracebackFuture()\n        callback, args, kwargs = replacer.replace(future, args, kwargs)\n        if callback is not None:\n            future.add_done_callback(\n                functools.partial(_auth_future_to_callback, callback))\n\n        def handle_exception(typ, value, tb):\n            if future.done():\n                return False\n            else:\n                future.set_exc_info((typ, value, tb))\n                return True\n        with ExceptionStackContext(handle_exception):\n            f(*args, **kwargs)\n        return future\n    return wrapper\n\n\nclass OpenIdMixin(object):\n    \"\"\"Abstract implementation of OpenID and Attribute Exchange.\n\n    Class attributes:\n\n    * ``_OPENID_ENDPOINT``: the identity provider's URI.\n    \"\"\"\n    @return_future\n    def authenticate_redirect(self, callback_uri=None,\n                              ax_attrs=[\"name\", \"email\", \"language\", \"username\"],\n                              callback=None):\n        \"\"\"Redirects to the authentication URL for this service.\n\n        After authentication, the service will redirect back to the given\n        callback URI with additional parameters including ``openid.mode``.\n\n        We request the given attributes for the authenticated user by\n        default (name, email, language, and username). If you don't need\n        all those attributes for your app, you can request fewer with\n        the ax_attrs keyword argument.\n\n        .. versionchanged:: 3.1\n           Returns a `.Future` and takes an optional callback.  These are\n           not strictly necessary as this method is synchronous,\n           but they are supplied for consistency with\n           `OAuthMixin.authorize_redirect`.\n        \"\"\"\n        callback_uri = callback_uri or self.request.uri\n        args = self._openid_args(callback_uri, ax_attrs=ax_attrs)\n        self.redirect(self._OPENID_ENDPOINT + \"?\" + urllib_parse.urlencode(args))\n        callback()\n\n    @_auth_return_future\n    def get_authenticated_user(self, callback, http_client=None):\n        \"\"\"Fetches the authenticated user data upon redirect.\n\n        This method should be called by the handler that receives the\n        redirect from the `authenticate_redirect()` method (which is\n        often the same as the one that calls it; in that case you would\n        call `get_authenticated_user` if the ``openid.mode`` parameter\n        is present and `authenticate_redirect` if it is not).\n\n        The result of this method will generally be used to set a cookie.\n        \"\"\"\n        # Verify the OpenID response via direct request to the OP\n        args = dict((k, v[-1]) for k, v in self.request.arguments.items())\n        args[\"openid.mode\"] = u(\"check_authentication\")\n        url = self._OPENID_ENDPOINT\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        http_client.fetch(url, functools.partial(\n            self._on_authentication_verified, callback),\n            method=\"POST\", body=urllib_parse.urlencode(args))\n\n    def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):\n        url = urlparse.urljoin(self.request.full_url(), callback_uri)\n        args = {\n            \"openid.ns\": \"http://specs.openid.net/auth/2.0\",\n            \"openid.claimed_id\":\n            \"http://specs.openid.net/auth/2.0/identifier_select\",\n            \"openid.identity\":\n            \"http://specs.openid.net/auth/2.0/identifier_select\",\n            \"openid.return_to\": url,\n            \"openid.realm\": urlparse.urljoin(url, '/'),\n            \"openid.mode\": \"checkid_setup\",\n        }\n        if ax_attrs:\n            args.update({\n                \"openid.ns.ax\": \"http://openid.net/srv/ax/1.0\",\n                \"openid.ax.mode\": \"fetch_request\",\n            })\n            ax_attrs = set(ax_attrs)\n            required = []\n            if \"name\" in ax_attrs:\n                ax_attrs -= set([\"name\", \"firstname\", \"fullname\", \"lastname\"])\n                required += [\"firstname\", \"fullname\", \"lastname\"]\n                args.update({\n                    \"openid.ax.type.firstname\":\n                    \"http://axschema.org/namePerson/first\",\n                    \"openid.ax.type.fullname\":\n                    \"http://axschema.org/namePerson\",\n                    \"openid.ax.type.lastname\":\n                    \"http://axschema.org/namePerson/last\",\n                })\n            known_attrs = {\n                \"email\": \"http://axschema.org/contact/email\",\n                \"language\": \"http://axschema.org/pref/language\",\n                \"username\": \"http://axschema.org/namePerson/friendly\",\n            }\n            for name in ax_attrs:\n                args[\"openid.ax.type.\" + name] = known_attrs[name]\n                required.append(name)\n            args[\"openid.ax.required\"] = \",\".join(required)\n        if oauth_scope:\n            args.update({\n                \"openid.ns.oauth\":\n                \"http://specs.openid.net/extensions/oauth/1.0\",\n                \"openid.oauth.consumer\": self.request.host.split(\":\")[0],\n                \"openid.oauth.scope\": oauth_scope,\n            })\n        return args\n\n    def _on_authentication_verified(self, future, response):\n        if response.error or b\"is_valid:true\" not in response.body:\n            future.set_exception(AuthError(\n                \"Invalid OpenID response: %s\" % (response.error or\n                                                 response.body)))\n            return\n\n        # Make sure we got back at least an email from attribute exchange\n        ax_ns = None\n        for name in self.request.arguments:\n            if name.startswith(\"openid.ns.\") and \\\n                    self.get_argument(name) == u(\"http://openid.net/srv/ax/1.0\"):\n                ax_ns = name[10:]\n                break\n\n        def get_ax_arg(uri):\n            if not ax_ns:\n                return u(\"\")\n            prefix = \"openid.\" + ax_ns + \".type.\"\n            ax_name = None\n            for name in self.request.arguments.keys():\n                if self.get_argument(name) == uri and name.startswith(prefix):\n                    part = name[len(prefix):]\n                    ax_name = \"openid.\" + ax_ns + \".value.\" + part\n                    break\n            if not ax_name:\n                return u(\"\")\n            return self.get_argument(ax_name, u(\"\"))\n\n        email = get_ax_arg(\"http://axschema.org/contact/email\")\n        name = get_ax_arg(\"http://axschema.org/namePerson\")\n        first_name = get_ax_arg(\"http://axschema.org/namePerson/first\")\n        last_name = get_ax_arg(\"http://axschema.org/namePerson/last\")\n        username = get_ax_arg(\"http://axschema.org/namePerson/friendly\")\n        locale = get_ax_arg(\"http://axschema.org/pref/language\").lower()\n        user = dict()\n        name_parts = []\n        if first_name:\n            user[\"first_name\"] = first_name\n            name_parts.append(first_name)\n        if last_name:\n            user[\"last_name\"] = last_name\n            name_parts.append(last_name)\n        if name:\n            user[\"name\"] = name\n        elif name_parts:\n            user[\"name\"] = u(\" \").join(name_parts)\n        elif email:\n            user[\"name\"] = email.split(\"@\")[0]\n        if email:\n            user[\"email\"] = email\n        if locale:\n            user[\"locale\"] = locale\n        if username:\n            user[\"username\"] = username\n        claimed_id = self.get_argument(\"openid.claimed_id\", None)\n        if claimed_id:\n            user[\"claimed_id\"] = claimed_id\n        future.set_result(user)\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass OAuthMixin(object):\n    \"\"\"Abstract implementation of OAuth 1.0 and 1.0a.\n\n    See `TwitterMixin` below for an example implementation.\n\n    Class attributes:\n\n    * ``_OAUTH_AUTHORIZE_URL``: The service's OAuth authorization url.\n    * ``_OAUTH_ACCESS_TOKEN_URL``: The service's OAuth access token url.\n    * ``_OAUTH_VERSION``: May be either \"1.0\" or \"1.0a\".\n    * ``_OAUTH_NO_CALLBACKS``: Set this to True if the service requires\n      advance registration of callbacks.\n\n    Subclasses must also override the `_oauth_get_user_future` and\n    `_oauth_consumer_token` methods.\n    \"\"\"\n    @return_future\n    def authorize_redirect(self, callback_uri=None, extra_params=None,\n                           http_client=None, callback=None):\n        \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n        The ``callback_uri`` may be omitted if you have previously\n        registered a callback URI with the third-party service.  For\n        some services (including Friendfeed), you must use a\n        previously-registered callback URI and cannot specify a\n        callback via this method.\n\n        This method sets a cookie called ``_oauth_request_token`` which is\n        subsequently used (and cleared) in `get_authenticated_user` for\n        security purposes.\n\n        Note that this method is asynchronous, although it calls\n        `.RequestHandler.finish` for you so it may not be necessary\n        to pass a callback or use the `.Future` it returns.  However,\n        if this method is called from a function decorated with\n        `.gen.coroutine`, you must call it with ``yield`` to keep the\n        response from being closed prematurely.\n\n        .. versionchanged:: 3.1\n           Now returns a `.Future` and takes an optional callback, for\n           compatibility with `.gen.coroutine`.\n        \"\"\"\n        if callback_uri and getattr(self, \"_OAUTH_NO_CALLBACKS\", False):\n            raise Exception(\"This service does not support oauth_callback\")\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            http_client.fetch(\n                self._oauth_request_token_url(callback_uri=callback_uri,\n                                              extra_params=extra_params),\n                functools.partial(\n                    self._on_request_token,\n                    self._OAUTH_AUTHORIZE_URL,\n                    callback_uri,\n                    callback))\n        else:\n            http_client.fetch(\n                self._oauth_request_token_url(),\n                functools.partial(\n                    self._on_request_token, self._OAUTH_AUTHORIZE_URL,\n                    callback_uri,\n                    callback))\n\n    @_auth_return_future\n    def get_authenticated_user(self, callback, http_client=None):\n        \"\"\"Gets the OAuth authorized user and access token.\n\n        This method should be called from the handler for your\n        OAuth callback URL to complete the registration process. We run the\n        callback with the authenticated user dictionary.  This dictionary\n        will contain an ``access_key`` which can be used to make authorized\n        requests to this service on behalf of the user.  The dictionary will\n        also contain other fields such as ``name``, depending on the service\n        used.\n        \"\"\"\n        future = callback\n        request_key = escape.utf8(self.get_argument(\"oauth_token\"))\n        oauth_verifier = self.get_argument(\"oauth_verifier\", None)\n        request_cookie = self.get_cookie(\"_oauth_request_token\")\n        if not request_cookie:\n            future.set_exception(AuthError(\n                \"Missing OAuth request token cookie\"))\n            return\n        self.clear_cookie(\"_oauth_request_token\")\n        cookie_key, cookie_secret = [base64.b64decode(escape.utf8(i)) for i in request_cookie.split(\"|\")]\n        if cookie_key != request_key:\n            future.set_exception(AuthError(\n                \"Request token does not match cookie\"))\n            return\n        token = dict(key=cookie_key, secret=cookie_secret)\n        if oauth_verifier:\n            token[\"verifier\"] = oauth_verifier\n        if http_client is None:\n            http_client = self.get_auth_http_client()\n        http_client.fetch(self._oauth_access_token_url(token),\n                          functools.partial(self._on_access_token, callback))\n\n    def _oauth_request_token_url(self, callback_uri=None, extra_params=None):\n        consumer_token = self._oauth_consumer_token()\n        url = self._OAUTH_REQUEST_TOKEN_URL\n        args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            if callback_uri == \"oob\":\n                args[\"oauth_callback\"] = \"oob\"\n            elif callback_uri:\n                args[\"oauth_callback\"] = urlparse.urljoin(\n                    self.request.full_url(), callback_uri)\n            if extra_params:\n                args.update(extra_params)\n            signature = _oauth10a_signature(consumer_token, \"GET\", url, args)\n        else:\n            signature = _oauth_signature(consumer_token, \"GET\", url, args)\n\n        args[\"oauth_signature\"] = signature\n        return url + \"?\" + urllib_parse.urlencode(args)\n\n    def _on_request_token(self, authorize_url, callback_uri, callback,\n                          response):\n        if response.error:\n            raise Exception(\"Could not get request token: %s\" % response.error)\n        request_token = _oauth_parse_response(response.body)\n        data = (base64.b64encode(escape.utf8(request_token[\"key\"])) + b\"|\" +\n                base64.b64encode(escape.utf8(request_token[\"secret\"])))\n        self.set_cookie(\"_oauth_request_token\", data)\n        args = dict(oauth_token=request_token[\"key\"])\n        if callback_uri == \"oob\":\n            self.finish(authorize_url + \"?\" + urllib_parse.urlencode(args))\n            callback()\n            return\n        elif callback_uri:\n            args[\"oauth_callback\"] = urlparse.urljoin(\n                self.request.full_url(), callback_uri)\n        self.redirect(authorize_url + \"?\" + urllib_parse.urlencode(args))\n        callback()\n\n    def _oauth_access_token_url(self, request_token):\n        consumer_token = self._oauth_consumer_token()\n        url = self._OAUTH_ACCESS_TOKEN_URL\n        args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_token=escape.to_basestring(request_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        if \"verifier\" in request_token:\n            args[\"oauth_verifier\"] = request_token[\"verifier\"]\n\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            signature = _oauth10a_signature(consumer_token, \"GET\", url, args,\n                                            request_token)\n        else:\n            signature = _oauth_signature(consumer_token, \"GET\", url, args,\n                                         request_token)\n\n        args[\"oauth_signature\"] = signature\n        return url + \"?\" + urllib_parse.urlencode(args)\n\n    def _on_access_token(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\"Could not fetch access token\"))\n            return\n\n        access_token = _oauth_parse_response(response.body)\n        self._oauth_get_user_future(access_token).add_done_callback(\n            functools.partial(self._on_oauth_get_user, access_token, future))\n\n    def _oauth_consumer_token(self):\n        \"\"\"Subclasses must override this to return their OAuth consumer keys.\n\n        The return value should be a `dict` with keys ``key`` and ``secret``.\n        \"\"\"\n        raise NotImplementedError()\n\n    @return_future\n    def _oauth_get_user_future(self, access_token, callback):\n        \"\"\"Subclasses must override this to get basic information about the\n        user.\n\n        Should return a `.Future` whose result is a dictionary\n        containing information about the user, which may have been\n        retrieved by using ``access_token`` to make a request to the\n        service.\n\n        The access token will be added to the returned dictionary to make\n        the result of `get_authenticated_user`.\n\n        For backwards compatibility, the callback-based ``_oauth_get_user``\n        method is also supported.\n        \"\"\"\n        # By default, call the old-style _oauth_get_user, but new code\n        # should override this method instead.\n        self._oauth_get_user(access_token, callback)\n\n    def _oauth_get_user(self, access_token, callback):\n        raise NotImplementedError()\n\n    def _on_oauth_get_user(self, access_token, future, user_future):\n        if user_future.exception() is not None:\n            future.set_exception(user_future.exception())\n            return\n        user = user_future.result()\n        if not user:\n            future.set_exception(AuthError(\"Error getting user\"))\n            return\n        user[\"access_token\"] = access_token\n        future.set_result(user)\n\n    def _oauth_request_parameters(self, url, access_token, parameters={},\n                                  method=\"GET\"):\n        \"\"\"Returns the OAuth parameters as a dict for the given request.\n\n        parameters should include all POST arguments and query string arguments\n        that will be sent with the request.\n        \"\"\"\n        consumer_token = self._oauth_consumer_token()\n        base_args = dict(\n            oauth_consumer_key=escape.to_basestring(consumer_token[\"key\"]),\n            oauth_token=escape.to_basestring(access_token[\"key\"]),\n            oauth_signature_method=\"HMAC-SHA1\",\n            oauth_timestamp=str(int(time.time())),\n            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),\n            oauth_version=\"1.0\",\n        )\n        args = {}\n        args.update(base_args)\n        args.update(parameters)\n        if getattr(self, \"_OAUTH_VERSION\", \"1.0a\") == \"1.0a\":\n            signature = _oauth10a_signature(consumer_token, method, url, args,\n                                            access_token)\n        else:\n            signature = _oauth_signature(consumer_token, method, url, args,\n                                         access_token)\n        base_args[\"oauth_signature\"] = escape.to_basestring(signature)\n        return base_args\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass OAuth2Mixin(object):\n    \"\"\"Abstract implementation of OAuth 2.0.\n\n    See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example\n    implementations.\n\n    Class attributes:\n\n    * ``_OAUTH_AUTHORIZE_URL``: The service's authorization url.\n    * ``_OAUTH_ACCESS_TOKEN_URL``:  The service's access token url.\n    \"\"\"\n    @return_future\n    def authorize_redirect(self, redirect_uri=None, client_id=None,\n                           client_secret=None, extra_params=None,\n                           callback=None, scope=None, response_type=\"code\"):\n        \"\"\"Redirects the user to obtain OAuth authorization for this service.\n\n        Some providers require that you register a redirect URL with\n        your application instead of passing one via this method. You\n        should call this method to log the user in, and then call\n        ``get_authenticated_user`` in the handler for your\n        redirect URL to complete the authorization process.\n\n        .. versionchanged:: 3.1\n           Returns a `.Future` and takes an optional callback.  These are\n           not strictly necessary as this method is synchronous,\n           but they are supplied for consistency with\n           `OAuthMixin.authorize_redirect`.\n        \"\"\"\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"client_id\": client_id,\n            \"response_type\": response_type\n        }\n        if extra_params:\n            args.update(extra_params)\n        if scope:\n            args['scope'] = ' '.join(scope)\n        self.redirect(\n            url_concat(self._OAUTH_AUTHORIZE_URL, args))\n        callback()\n\n    def _oauth_request_token_url(self, redirect_uri=None, client_id=None,\n                                 client_secret=None, code=None,\n                                 extra_params=None):\n        url = self._OAUTH_ACCESS_TOKEN_URL\n        args = dict(\n            redirect_uri=redirect_uri,\n            code=code,\n            client_id=client_id,\n            client_secret=client_secret,\n        )\n        if extra_params:\n            args.update(extra_params)\n        return url_concat(url, args)\n\n    @_auth_return_future\n    def oauth2_request(self, url, callback, access_token=None,\n                       post_args=None, **args):\n        \"\"\"Fetches the given URL auth an OAuth2 access token.\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.oauth2_request(\n                        \"https://graph.facebook.com/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        .. versionadded:: 4.3\n        \"\"\"\n        all_args = {}\n        if access_token:\n            all_args[\"access_token\"] = access_token\n            all_args.update(args)\n\n        if all_args:\n            url += \"?\" + urllib_parse.urlencode(all_args)\n        callback = functools.partial(self._on_oauth2_request, callback)\n        http = self.get_auth_http_client()\n        if post_args is not None:\n            http.fetch(url, method=\"POST\", body=urllib_parse.urlencode(post_args),\n                       callback=callback)\n        else:\n            http.fetch(url, callback=callback)\n\n    def _on_oauth2_request(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\"Error response %s fetching %s\" %\n                                           (response.error, response.request.url)))\n            return\n\n        future.set_result(escape.json_decode(response.body))\n\n    def get_auth_http_client(self):\n        \"\"\"Returns the `.AsyncHTTPClient` instance to be used for auth requests.\n\n        May be overridden by subclasses to use an HTTP client other than\n        the default.\n\n        .. versionadded:: 4.3\n        \"\"\"\n        return httpclient.AsyncHTTPClient()\n\n\nclass TwitterMixin(OAuthMixin):\n    \"\"\"Twitter OAuth authentication.\n\n    To authenticate with Twitter, register your application with\n    Twitter at http://twitter.com/apps. Then copy your Consumer Key\n    and Consumer Secret to the application\n    `~tornado.web.Application.settings` ``twitter_consumer_key`` and\n    ``twitter_consumer_secret``. Use this mixin on the handler for the\n    URL you registered as your application's callback URL.\n\n    When your application is set up, you can use this mixin like this\n    to authenticate the user with Twitter and get access to their stream:\n\n    .. testcode::\n\n        class TwitterLoginHandler(tornado.web.RequestHandler,\n                                  tornado.auth.TwitterMixin):\n            @tornado.gen.coroutine\n            def get(self):\n                if self.get_argument(\"oauth_token\", None):\n                    user = yield self.get_authenticated_user()\n                    # Save the user using e.g. set_secure_cookie()\n                else:\n                    yield self.authorize_redirect()\n\n    .. testoutput::\n       :hide:\n\n    The user object returned by `~OAuthMixin.get_authenticated_user`\n    includes the attributes ``username``, ``name``, ``access_token``,\n    and all of the custom Twitter user attributes described at\n    https://dev.twitter.com/docs/api/1.1/get/users/show\n    \"\"\"\n    _OAUTH_REQUEST_TOKEN_URL = \"https://api.twitter.com/oauth/request_token\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://api.twitter.com/oauth/access_token\"\n    _OAUTH_AUTHORIZE_URL = \"https://api.twitter.com/oauth/authorize\"\n    _OAUTH_AUTHENTICATE_URL = \"https://api.twitter.com/oauth/authenticate\"\n    _OAUTH_NO_CALLBACKS = False\n    _TWITTER_BASE_URL = \"https://api.twitter.com/1.1\"\n\n    @return_future\n    def authenticate_redirect(self, callback_uri=None, callback=None):\n        \"\"\"Just like `~OAuthMixin.authorize_redirect`, but\n        auto-redirects if authorized.\n\n        This is generally the right interface to use if you are using\n        Twitter for single-sign on.\n\n        .. versionchanged:: 3.1\n           Now returns a `.Future` and takes an optional callback, for\n           compatibility with `.gen.coroutine`.\n        \"\"\"\n        http = self.get_auth_http_client()\n        http.fetch(self._oauth_request_token_url(callback_uri=callback_uri),\n                   functools.partial(\n                       self._on_request_token, self._OAUTH_AUTHENTICATE_URL,\n                       None, callback))\n\n    @_auth_return_future\n    def twitter_request(self, path, callback=None, access_token=None,\n                        post_args=None, **args):\n        \"\"\"Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``\n\n        The path should not include the format or API version number.\n        (we automatically use JSON format and API version 1).\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        All the Twitter methods are documented at http://dev.twitter.com/\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuthMixin.authorize_redirect` and\n        `~OAuthMixin.get_authenticated_user`. The user returned through that\n        process includes an 'access_token' attribute that can be used\n        to make authenticated requests via this method. Example\n        usage:\n\n        .. testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.TwitterMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.twitter_request(\n                        \"/statuses/update\",\n                        post_args={\"status\": \"Testing Tornado Web Server\"},\n                        access_token=self.current_user[\"access_token\"])\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        if path.startswith('http:') or path.startswith('https:'):\n            # Raw urls are useful for e.g. search which doesn't follow the\n            # usual pattern: http://search.twitter.com/search.json\n            url = path\n        else:\n            url = self._TWITTER_BASE_URL + path + \".json\"\n        # Add the OAuth resource request signature if we have credentials\n        if access_token:\n            all_args = {}\n            all_args.update(args)\n            all_args.update(post_args or {})\n            method = \"POST\" if post_args is not None else \"GET\"\n            oauth = self._oauth_request_parameters(\n                url, access_token, all_args, method=method)\n            args.update(oauth)\n        if args:\n            url += \"?\" + urllib_parse.urlencode(args)\n        http = self.get_auth_http_client()\n        http_callback = functools.partial(self._on_twitter_request, callback)\n        if post_args is not None:\n            http.fetch(url, method=\"POST\", body=urllib_parse.urlencode(post_args),\n                       callback=http_callback)\n        else:\n            http.fetch(url, callback=http_callback)\n\n    def _on_twitter_request(self, future, response):\n        if response.error:\n            future.set_exception(AuthError(\n                \"Error response %s fetching %s\" % (response.error,\n                                                   response.request.url)))\n            return\n        future.set_result(escape.json_decode(response.body))\n\n    def _oauth_consumer_token(self):\n        self.require_setting(\"twitter_consumer_key\", \"Twitter OAuth\")\n        self.require_setting(\"twitter_consumer_secret\", \"Twitter OAuth\")\n        return dict(\n            key=self.settings[\"twitter_consumer_key\"],\n            secret=self.settings[\"twitter_consumer_secret\"])\n\n    @gen.coroutine\n    def _oauth_get_user_future(self, access_token):\n        user = yield self.twitter_request(\n            \"/account/verify_credentials\",\n            access_token=access_token)\n        if user:\n            user[\"username\"] = user[\"screen_name\"]\n        raise gen.Return(user)\n\n\nclass GoogleOAuth2Mixin(OAuth2Mixin):\n    \"\"\"Google authentication using OAuth2.\n\n    In order to use, register your application with Google and copy the\n    relevant parameters to your application settings.\n\n    * Go to the Google Dev Console at http://console.developers.google.com\n    * Select a project, or create a new one.\n    * In the sidebar on the left, select APIs & Auth.\n    * In the list of APIs, find the Google+ API service and set it to ON.\n    * In the sidebar on the left, select Credentials.\n    * In the OAuth section of the page, select Create New Client ID.\n    * Set the Redirect URI to point to your auth handler\n    * Copy the \"Client secret\" and \"Client ID\" to the application settings as\n      {\"google_oauth\": {\"key\": CLIENT_ID, \"secret\": CLIENT_SECRET}}\n\n    .. versionadded:: 3.2\n    \"\"\"\n    _OAUTH_AUTHORIZE_URL = \"https://accounts.google.com/o/oauth2/auth\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://accounts.google.com/o/oauth2/token\"\n    _OAUTH_USERINFO_URL = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n    _OAUTH_NO_CALLBACKS = False\n    _OAUTH_SETTINGS_KEY = 'google_oauth'\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, code, callback):\n        \"\"\"Handles the login for the Google user, returning an access token.\n\n        The result is a dictionary containing an ``access_token`` field\n        ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).\n        Unlike other ``get_authenticated_user`` methods in this package,\n        this method does not return any additional information about the user.\n        The returned access token can be used with `OAuth2Mixin.oauth2_request`\n        to request additional information (perhaps from\n        ``https://www.googleapis.com/oauth2/v2/userinfo``)\n\n        Example usage:\n\n        .. testcode::\n\n            class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,\n                                           tornado.auth.GoogleOAuth2Mixin):\n                @tornado.gen.coroutine\n                def get(self):\n                    if self.get_argument('code', False):\n                        access = yield self.get_authenticated_user(\n                            redirect_uri='http://your.site.com/auth/google',\n                            code=self.get_argument('code'))\n                        user = yield self.oauth2_request(\n                            \"https://www.googleapis.com/oauth2/v1/userinfo\",\n                            access_token=access[\"access_token\"])\n                        # Save the user and access token with\n                        # e.g. set_secure_cookie.\n                    else:\n                        yield self.authorize_redirect(\n                            redirect_uri='http://your.site.com/auth/google',\n                            client_id=self.settings['google_oauth']['key'],\n                            scope=['profile', 'email'],\n                            response_type='code',\n                            extra_params={'approval_prompt': 'auto'})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        body = urllib_parse.urlencode({\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": self.settings[self._OAUTH_SETTINGS_KEY]['key'],\n            \"client_secret\": self.settings[self._OAUTH_SETTINGS_KEY]['secret'],\n            \"grant_type\": \"authorization_code\",\n        })\n\n        http.fetch(self._OAUTH_ACCESS_TOKEN_URL,\n                   functools.partial(self._on_access_token, callback),\n                   method=\"POST\", headers={'Content-Type': 'application/x-www-form-urlencoded'}, body=body)\n\n    def _on_access_token(self, future, response):\n        \"\"\"Callback function for the exchange to the access token.\"\"\"\n        if response.error:\n            future.set_exception(AuthError('Google auth error: %s' % str(response)))\n            return\n\n        args = escape.json_decode(response.body)\n        future.set_result(args)\n\n\nclass FacebookGraphMixin(OAuth2Mixin):\n    \"\"\"Facebook authentication using the new Graph API and OAuth2.\"\"\"\n    _OAUTH_ACCESS_TOKEN_URL = \"https://graph.facebook.com/oauth/access_token?\"\n    _OAUTH_AUTHORIZE_URL = \"https://www.facebook.com/dialog/oauth?\"\n    _OAUTH_NO_CALLBACKS = False\n    _FACEBOOK_BASE_URL = \"https://graph.facebook.com\"\n\n    @_auth_return_future\n    def get_authenticated_user(self, redirect_uri, client_id, client_secret,\n                               code, callback, extra_fields=None):\n        \"\"\"Handles the login for the Facebook user, returning a user object.\n\n        Example usage:\n\n        .. testcode::\n\n            class FacebookGraphLoginHandler(tornado.web.RequestHandler,\n                                            tornado.auth.FacebookGraphMixin):\n              @tornado.gen.coroutine\n              def get(self):\n                  if self.get_argument(\"code\", False):\n                      user = yield self.get_authenticated_user(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          client_secret=self.settings[\"facebook_secret\"],\n                          code=self.get_argument(\"code\"))\n                      # Save the user with e.g. set_secure_cookie\n                  else:\n                      yield self.authorize_redirect(\n                          redirect_uri='/auth/facebookgraph/',\n                          client_id=self.settings[\"facebook_api_key\"],\n                          extra_params={\"scope\": \"read_stream,offline_access\"})\n\n        .. testoutput::\n           :hide:\n\n        \"\"\"\n        http = self.get_auth_http_client()\n        args = {\n            \"redirect_uri\": redirect_uri,\n            \"code\": code,\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n        }\n\n        fields = set(['id', 'name', 'first_name', 'last_name',\n                      'locale', 'picture', 'link'])\n        if extra_fields:\n            fields.update(extra_fields)\n\n        http.fetch(self._oauth_request_token_url(**args),\n                   functools.partial(self._on_access_token, redirect_uri, client_id,\n                                     client_secret, callback, fields))\n\n    def _on_access_token(self, redirect_uri, client_id, client_secret,\n                         future, fields, response):\n        if response.error:\n            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))\n            return\n\n        args = escape.parse_qs_bytes(escape.native_str(response.body))\n        session = {\n            \"access_token\": args[\"access_token\"][-1],\n            \"expires\": args.get(\"expires\")\n        }\n\n        self.facebook_request(\n            path=\"/me\",\n            callback=functools.partial(\n                self._on_get_user_info, future, session, fields),\n            access_token=session[\"access_token\"],\n            fields=\",\".join(fields)\n        )\n\n    def _on_get_user_info(self, future, session, fields, user):\n        if user is None:\n            future.set_result(None)\n            return\n\n        fieldmap = {}\n        for field in fields:\n            fieldmap[field] = user.get(field)\n\n        fieldmap.update({\"access_token\": session[\"access_token\"], \"session_expires\": session.get(\"expires\")})\n        future.set_result(fieldmap)\n\n    @_auth_return_future\n    def facebook_request(self, path, callback, access_token=None,\n                         post_args=None, **args):\n        \"\"\"Fetches the given relative API path, e.g., \"/btaylor/picture\"\n\n        If the request is a POST, ``post_args`` should be provided. Query\n        string arguments should be given as keyword arguments.\n\n        An introduction to the Facebook Graph API can be found at\n        http://developers.facebook.com/docs/api\n\n        Many methods require an OAuth access token which you can\n        obtain through `~OAuth2Mixin.authorize_redirect` and\n        `get_authenticated_user`. The user returned through that\n        process includes an ``access_token`` attribute that can be\n        used to make authenticated requests via this method.\n\n        Example usage:\n\n        ..testcode::\n\n            class MainHandler(tornado.web.RequestHandler,\n                              tornado.auth.FacebookGraphMixin):\n                @tornado.web.authenticated\n                @tornado.gen.coroutine\n                def get(self):\n                    new_entry = yield self.facebook_request(\n                        \"/me/feed\",\n                        post_args={\"message\": \"I am posting from my Tornado application!\"},\n                        access_token=self.current_user[\"access_token\"])\n\n                    if not new_entry:\n                        # Call failed; perhaps missing permission?\n                        yield self.authorize_redirect()\n                        return\n                    self.finish(\"Posted a message!\")\n\n        .. testoutput::\n           :hide:\n\n        The given path is relative to ``self._FACEBOOK_BASE_URL``,\n        by default \"https://graph.facebook.com\".\n\n        This method is a wrapper around `OAuth2Mixin.oauth2_request`;\n        the only difference is that this method takes a relative path,\n        while ``oauth2_request`` takes a complete url.\n\n        .. versionchanged:: 3.1\n           Added the ability to override ``self._FACEBOOK_BASE_URL``.\n        \"\"\"\n        url = self._FACEBOOK_BASE_URL + path\n        return self.oauth2_request(url, callback, access_token,\n                                   post_args, **args)\n\n\ndef _oauth_signature(consumer_token, method, url, parameters={}, token=None):\n    \"\"\"Calculates the HMAC-SHA1 OAuth signature for the given request.\n\n    See http://oauth.net/core/1.0/#signing_process\n    \"\"\"\n    parts = urlparse.urlparse(url)\n    scheme, netloc, path = parts[:3]\n    normalized_url = scheme.lower() + \"://\" + netloc.lower() + path\n\n    base_elems = []\n    base_elems.append(method.upper())\n    base_elems.append(normalized_url)\n    base_elems.append(\"&\".join(\"%s=%s\" % (k, _oauth_escape(str(v)))\n                               for k, v in sorted(parameters.items())))\n    base_string = \"&\".join(_oauth_escape(e) for e in base_elems)\n\n    key_elems = [escape.utf8(consumer_token[\"secret\"])]\n    key_elems.append(escape.utf8(token[\"secret\"] if token else \"\"))\n    key = b\"&\".join(key_elems)\n\n    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)\n    return binascii.b2a_base64(hash.digest())[:-1]\n\n\ndef _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):\n    \"\"\"Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.\n\n    See http://oauth.net/core/1.0a/#signing_process\n    \"\"\"\n    parts = urlparse.urlparse(url)\n    scheme, netloc, path = parts[:3]\n    normalized_url = scheme.lower() + \"://\" + netloc.lower() + path\n\n    base_elems = []\n    base_elems.append(method.upper())\n    base_elems.append(normalized_url)\n    base_elems.append(\"&\".join(\"%s=%s\" % (k, _oauth_escape(str(v)))\n                               for k, v in sorted(parameters.items())))\n\n    base_string = \"&\".join(_oauth_escape(e) for e in base_elems)\n    key_elems = [escape.utf8(urllib_parse.quote(consumer_token[\"secret\"], safe='~'))]\n    key_elems.append(escape.utf8(urllib_parse.quote(token[\"secret\"], safe='~') if token else \"\"))\n    key = b\"&\".join(key_elems)\n\n    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)\n    return binascii.b2a_base64(hash.digest())[:-1]\n\n\ndef _oauth_escape(val):\n    if isinstance(val, unicode_type):\n        val = val.encode(\"utf-8\")\n    return urllib_parse.quote(val, safe=\"~\")\n\n\ndef _oauth_parse_response(body):\n    # I can't find an officially-defined encoding for oauth responses and\n    # have never seen anyone use non-ascii.  Leave the response in a byte\n    # string for python 2, and use utf8 on python 3.\n    body = escape.native_str(body)\n    p = urlparse.parse_qs(body, keep_blank_values=False)\n    token = dict(key=p[\"oauth_token\"][0], secret=p[\"oauth_token_secret\"][0])\n\n    # Add the extra parameters the Provider included to the token\n    special = (\"oauth_token\", \"oauth_token_secret\")\n    token.update((k, p[k][0]) for k in p if k not in special)\n    return token\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Facebook login request hangs and results in timeout

**Description:**
When attempting to authenticate via Facebook, the login request does not complete and eventually times out. This issue occurs when access tokens are returned as bytes, causing the user objects to be non-JSON-encodable and disrupting the authentication flow.

**Example Code:**
```python
response = fetch('/facebook/client/login', follow_redirects=False)
if response.code == 302:
    response = fetch('/facebook/client/login?code=1234', follow_redirects=False)
    # The operation times out here
```

**Expected Behavior:**
After initiating the Facebook login with a valid authentication code, the server should process the request successfully and respond with a status code of 200, completing the user authentication.

**Actual Behavior:**
The authentication request hangs and times out after 5 seconds without completing, preventing the user from being authenticated.
[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/auth.py
#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""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:

.. testcode::

    class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
                                   tornado.auth.GoogleOAuth2Mixin):
        @tornado.gen.coroutine
        def get(self):
            if self.get_argument('code', False):
                user = yield self.get_authenticated_user(
                    redirect_uri='http://your.site.com/auth/google',
                    code=self.get_argument('code'))
                # Save the user with e.g. set_secure_cookie
            else:
                yield 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:


.. versionchanged:: 4.0
   All of the callback interfaces in this module are now guaranteed
   to run their callback with an argument of ``None`` on error.
   Previously some functions would do this while others would simply
   terminate the request on their own.  This change also ensures that
   errors are more consistently reported through the ``Future`` interfaces.
"""

from __future__ import absolute_import, division, print_function, with_statement

import base64
import binascii
import functools
import hashlib
import hmac
import time
import uuid

from tornado.concurrent import TracebackFuture, return_future
from tornado import gen
from tornado import httpclient
from tornado import escape
from tornado.httputil import url_concat
from tornado.log import gen_log
from tornado.stack_context import ExceptionStackContext
from tornado.util import u, unicode_type, ArgReplacer

try:
    import urlparse  # py2
except ImportError:
    import urllib.parse as urlparse  # py3

try:
    import urllib.parse as urllib_parse  # py3
except ImportError:
    import urllib as urllib_parse  # py2

try:
    long  # py2
except NameError:
    long = int  # py3


class AuthError(Exception):
    pass


def _auth_future_to_callback(callback, future):
    try:
        result = future.result()
    except AuthError as e:
        gen_log.warning(str(e))
        result = None
    callback(result)


def _auth_return_future(f):
    """Similar to tornado.concurrent.return_future, but uses the auth
    module's legacy callback interface.

    Note that when using this decorator the ``callback`` parameter
    inside the function will actually be a future.
    """
    replacer = ArgReplacer(f, 'callback')

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        future = TracebackFuture()
        callback, args, kwargs = replacer.replace(future, args, kwargs)
        if callback is not None:
            future.add_done_callback(
                functools.partial(_auth_future_to_callback, callback))

        def handle_exception(typ, value, tb):
            if future.done():
                return False
            else:
                future.set_exc_info((typ, value, tb))
                return True
        with ExceptionStackContext(handle_exception):
            f(*args, **kwargs)
        return future
    return wrapper


class OpenIdMixin(object):
    """Abstract implementation of OpenID and Attribute Exchange.

    Class attributes:

    * ``_OPENID_ENDPOINT``: the identity provider's URI.
    """
    @return_future
    def authenticate_redirect(self, callback_uri=None,
                              ax_attrs=["name", "email", "language", "username"],
                              callback=None):
        """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:: 3.1
           Returns a `.Future` and takes an optional callback.  These are
           not strictly necessary as this method is synchronous,
           but they are supplied for consistency with
           `OAuthMixin.authorize_redirect`.
        """
        callback_uri = callback_uri or self.request.uri
        args = self._openid_args(callback_uri, ax_attrs=ax_attrs)
        self.redirect(self._OPENID_ENDPOINT + "?" + urllib_parse.urlencode(args))
        callback()

    @_auth_return_future
    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.
        """
        # 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()
        http_client.fetch(url, functools.partial(
            self._on_authentication_verified, callback),
            method="POST", body=urllib_parse.urlencode(args))

    def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):
        url = urlparse.urljoin(self.request.full_url(), callback_uri)
        args = {
            "openid.ns": "http://specs.openid.net/auth/2.0",
            "openid.claimed_id":
            "http://specs.openid.net/auth/2.0/identifier_select",
            "openid.identity":
            "http://specs.openid.net/auth/2.0/identifier_select",
            "openid.return_to": url,
            "openid.realm": urlparse.urljoin(url, '/'),
            "openid.mode": "checkid_setup",
        }
        if ax_attrs:
            args.update({
                "openid.ns.ax": "http://openid.net/srv/ax/1.0",
                "openid.ax.mode": "fetch_request",
            })
            ax_attrs = set(ax_attrs)
            required = []
            if "name" in ax_attrs:
                ax_attrs -= set(["name", "firstname", "fullname", "lastname"])
                required += ["firstname", "fullname", "lastname"]
                args.update({
                    "openid.ax.type.firstname":
                    "http://axschema.org/namePerson/first",
                    "openid.ax.type.fullname":
                    "http://axschema.org/namePerson",
                    "openid.ax.type.lastname":
                    "http://axschema.org/namePerson/last",
                })
            known_attrs = {
                "email": "http://axschema.org/contact/email",
                "language": "http://axschema.org/pref/language",
                "username": "http://axschema.org/namePerson/friendly",
            }
            for name in ax_attrs:
                args["openid.ax.type." + name] = known_attrs[name]
                required.append(name)
            args["openid.ax.required"] = ",".join(required)
        if oauth_scope:
            args.update({
                "openid.ns.oauth":
                "http://specs.openid.net/extensions/oauth/1.0",
                "openid.oauth.consumer": self.request.host.split(":")[0],
                "openid.oauth.scope": oauth_scope,
            })
        return args

    def _on_authentication_verified(self, future, response):
        if response.error or b"is_valid:true" not in response.body:
            future.set_exception(AuthError(
                "Invalid OpenID response: %s" % (response.error or
                                                 response.body)))
            return

        # Make sure we got back at least an email from attribute exchange
        ax_ns = None
        for name in self.request.arguments:
            if name.startswith("openid.ns.") and \
                    self.get_argument(name) == u("http://openid.net/srv/ax/1.0"):
                ax_ns = name[10:]
                break

        def get_ax_arg(uri):
            if not ax_ns:
                return u("")
            prefix = "openid." + ax_ns + ".type."
            ax_name = None
            for name in self.request.arguments.keys():
                if self.get_argument(name) == uri and name.startswith(prefix):
                    part = name[len(prefix):]
                    ax_name = "openid." + ax_ns + ".value." + part
                    break
            if not ax_name:
                return u("")
            return self.get_argument(ax_name, u(""))

        email = get_ax_arg("http://axschema.org/contact/email")
        name = get_ax_arg("http://axschema.org/namePerson")
        first_name = get_ax_arg("http://axschema.org/namePerson/first")
        last_name = get_ax_arg("http://axschema.org/namePerson/last")
        username = get_ax_arg("http://axschema.org/namePerson/friendly")
        locale = get_ax_arg("http://axschema.org/pref/language").lower()
        user = dict()
        name_parts = []
        if first_name:
            user["first_name"] = first_name
            name_parts.append(first_name)
        if last_name:
            user["last_name"] = last_name
            name_parts.append(last_name)
        if name:
            user["name"] = name
        elif name_parts:
            user["name"] = u(" ").join(name_parts)
        elif email:
            user["name"] = email.split("@")[0]
        if email:
            user["email"] = email
        if locale:
            user["locale"] = locale
        if username:
            user["username"] = username
        claimed_id = self.get_argument("openid.claimed_id", None)
        if claimed_id:
            user["claimed_id"] = claimed_id
        future.set_result(user)

    def get_auth_http_client(self):
        """Returns the `.AsyncHTTPClient` instance to be used for auth requests.

        May be overridden by subclasses to use an HTTP client other than
        the default.
        """
        return httpclient.AsyncHTTPClient()


class OAuthMixin(object):
    """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.
    """
    @return_future
    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 (including Friendfeed), 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.

        Note that this method is asynchronous, although it calls
        `.RequestHandler.finish` for you so it may not be necessary
        to pass a callback or use the `.Future` it returns.  However,
        if this method is called from a function decorated with
        `.gen.coroutine`, you must call it with ``yield`` to keep the
        response from being closed prematurely.

        .. versionchanged:: 3.1
           Now returns a `.Future` and takes an optional callback, for
           compatibility with `.gen.coroutine`.
        """
        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":
            http_client.fetch(
                self._oauth_request_token_url(callback_uri=callback_uri,
                                              extra_params=extra_params),
                functools.partial(
                    self._on_request_token,
                    self._OAUTH_AUTHORIZE_URL,
                    callback_uri,
                    callback))
        else:
            http_client.fetch(
                self._oauth_request_token_url(),
                functools.partial(
                    self._on_request_token, self._OAUTH_AUTHORIZE_URL,
                    callback_uri,
                    callback))

    @_auth_return_future
    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.
        """
        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()
        http_client.fetch(self._oauth_access_token_url(token),
                          functools.partial(self._on_access_token, callback))

    def _oauth_request_token_url(self, callback_uri=None, extra_params=None):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_REQUEST_TOKEN_URL
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            if callback_uri == "oob":
                args["oauth_callback"] = "oob"
            elif callback_uri:
                args["oauth_callback"] = urlparse.urljoin(
                    self.request.full_url(), callback_uri)
            if extra_params:
                args.update(extra_params)
            signature = _oauth10a_signature(consumer_token, "GET", url, args)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args)

        args["oauth_signature"] = signature
        return url + "?" + urllib_parse.urlencode(args)

    def _on_request_token(self, authorize_url, callback_uri, callback,
                          response):
        if response.error:
            raise Exception("Could not get request token: %s" % response.error)
        request_token = _oauth_parse_response(response.body)
        data = (base64.b64encode(escape.utf8(request_token["key"])) + b"|" +
                base64.b64encode(escape.utf8(request_token["secret"])))
        self.set_cookie("_oauth_request_token", data)
        args = dict(oauth_token=request_token["key"])
        if callback_uri == "oob":
            self.finish(authorize_url + "?" + urllib_parse.urlencode(args))
            callback()
            return
        elif callback_uri:
            args["oauth_callback"] = urlparse.urljoin(
                self.request.full_url(), callback_uri)
        self.redirect(authorize_url + "?" + urllib_parse.urlencode(args))
        callback()

    def _oauth_access_token_url(self, request_token):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_ACCESS_TOKEN_URL
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_token=escape.to_basestring(request_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if "verifier" in request_token:
            args["oauth_verifier"] = request_token["verifier"]

        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(consumer_token, "GET", url, args,
                                            request_token)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args,
                                         request_token)

        args["oauth_signature"] = signature
        return url + "?" + urllib_parse.urlencode(args)

    def _on_access_token(self, future, response):
        if response.error:
            future.set_exception(AuthError("Could not fetch access token"))
            return

        access_token = _oauth_parse_response(response.body)
        self._oauth_get_user_future(access_token).add_done_callback(
            functools.partial(self._on_oauth_get_user, access_token, future))

    def _oauth_consumer_token(self):
        """Subclasses must override this to return their OAuth consumer keys.

        The return value should be a `dict` with keys ``key`` and ``secret``.
        """
        raise NotImplementedError()

    @return_future
    def _oauth_get_user_future(self, access_token, callback):
        """Subclasses must override this to get basic information about the
        user.

        Should return a `.Future` 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`.

        For backwards compatibility, the callback-based ``_oauth_get_user``
        method is also supported.
        """
        # By default, call the old-style _oauth_get_user, but new code
        # should override this method instead.
        self._oauth_get_user(access_token, callback)

    def _oauth_get_user(self, access_token, callback):
        raise NotImplementedError()

    def _on_oauth_get_user(self, access_token, future, user_future):
        if user_future.exception() is not None:
            future.set_exception(user_future.exception())
            return
        user = user_future.result()
        if not user:
            future.set_exception(AuthError("Error getting user"))
            return
        user["access_token"] = access_token
        future.set_result(user)

    def _oauth_request_parameters(self, url, access_token, parameters={},
                                  method="GET"):
        """Returns 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.
        """
        consumer_token = self._oauth_consumer_token()
        base_args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_token=escape.to_basestring(access_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        args = {}
        args.update(base_args)
        args.update(parameters)
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(consumer_token, method, url, args,
                                            access_token)
        else:
            signature = _oauth_signature(consumer_token, method, url, args,
                                         access_token)
        base_args["oauth_signature"] = escape.to_basestring(signature)
        return base_args

    def get_auth_http_client(self):
        """Returns the `.AsyncHTTPClient` instance to be used for auth requests.

        May be overridden by subclasses to use an HTTP client other than
        the default.
        """
        return httpclient.AsyncHTTPClient()


class OAuth2Mixin(object):
    """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.
    """
    @return_future
    def authorize_redirect(self, redirect_uri=None, client_id=None,
                           client_secret=None, extra_params=None,
                           callback=None, scope=None, response_type="code"):
        """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:: 3.1
           Returns a `.Future` and takes an optional callback.  These are
           not strictly necessary as this method is synchronous,
           but they are supplied for consistency with
           `OAuthMixin.authorize_redirect`.
        """
        args = {
            "redirect_uri": redirect_uri,
            "client_id": client_id,
            "response_type": response_type
        }
        if extra_params:
            args.update(extra_params)
        if scope:
            args['scope'] = ' '.join(scope)
        self.redirect(
            url_concat(self._OAUTH_AUTHORIZE_URL, args))
        callback()

    def _oauth_request_token_url(self, redirect_uri=None, client_id=None,
                                 client_secret=None, code=None,
                                 extra_params=None):
        url = self._OAUTH_ACCESS_TOKEN_URL
        args = dict(
            redirect_uri=redirect_uri,
            code=code,
            client_id=client_id,
            client_secret=client_secret,
        )
        if extra_params:
            args.update(extra_params)
        return url_concat(url, args)

    @_auth_return_future
    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
                @tornado.gen.coroutine
                def get(self):
                    new_entry = yield 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?
                        yield self.authorize_redirect()
                        return
                    self.finish("Posted a message!")

        .. testoutput::
           :hide:

        .. versionadded:: 4.3
        """
        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 = functools.partial(self._on_oauth2_request, callback)
        http = self.get_auth_http_client()
        if post_args is not None:
            http.fetch(url, method="POST", body=urllib_parse.urlencode(post_args),
                       callback=callback)
        else:
            http.fetch(url, callback=callback)

    def _on_oauth2_request(self, future, response):
        if response.error:
            future.set_exception(AuthError("Error response %s fetching %s" %
                                           (response.error, response.request.url)))
            return

        future.set_result(escape.json_decode(response.body))

    def get_auth_http_client(self):
        """Returns 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
        """
        return httpclient.AsyncHTTPClient()


class TwitterMixin(OAuthMixin):
    """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):
            @tornado.gen.coroutine
            def get(self):
                if self.get_argument("oauth_token", None):
                    user = yield self.get_authenticated_user()
                    # Save the user using e.g. set_secure_cookie()
                else:
                    yield self.authorize_redirect()

    .. testoutput::
       :hide:

    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
    """
    _OAUTH_REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
    _OAUTH_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"
    _OAUTH_AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize"
    _OAUTH_AUTHENTICATE_URL = "https://api.twitter.com/oauth/authenticate"
    _OAUTH_NO_CALLBACKS = False
    _TWITTER_BASE_URL = "https://api.twitter.com/1.1"

    @return_future
    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`.
        """
        http = self.get_auth_http_client()
        http.fetch(self._oauth_request_token_url(callback_uri=callback_uri),
                   functools.partial(
                       self._on_request_token, self._OAUTH_AUTHENTICATE_URL,
                       None, callback))

    @_auth_return_future
    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
                @tornado.gen.coroutine
                def get(self):
                    new_entry = yield 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:

        """
        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 = functools.partial(self._on_twitter_request, callback)
        if post_args is not None:
            http.fetch(url, method="POST", body=urllib_parse.urlencode(post_args),
                       callback=http_callback)
        else:
            http.fetch(url, callback=http_callback)

    def _on_twitter_request(self, future, response):
        if response.error:
            future.set_exception(AuthError(
                "Error response %s fetching %s" % (response.error,
                                                   response.request.url)))
            return
        future.set_result(escape.json_decode(response.body))

    def _oauth_consumer_token(self):
        self.require_setting("twitter_consumer_key", "Twitter OAuth")
        self.require_setting("twitter_consumer_secret", "Twitter OAuth")
        return dict(
            key=self.settings["twitter_consumer_key"],
            secret=self.settings["twitter_consumer_secret"])

    @gen.coroutine
    def _oauth_get_user_future(self, access_token):
        user = yield self.twitter_request(
            "/account/verify_credentials",
            access_token=access_token)
        if user:
            user["username"] = user["screen_name"]
        raise gen.Return(user)


class GoogleOAuth2Mixin(OAuth2Mixin):
    """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.
    * In the sidebar on the left, select APIs & Auth.
    * In the list of APIs, find the Google+ API service and set it to ON.
    * In the sidebar on the left, select Credentials.
    * In the OAuth section of the page, select Create New Client ID.
    * Set the Redirect URI to point to your auth handler
    * Copy the "Client secret" and "Client ID" to the application settings as
      {"google_oauth": {"key": CLIENT_ID, "secret": CLIENT_SECRET}}

    .. versionadded:: 3.2
    """
    _OAUTH_AUTHORIZE_URL = "https://accounts.google.com/o/oauth2/auth"
    _OAUTH_ACCESS_TOKEN_URL = "https://accounts.google.com/o/oauth2/token"
    _OAUTH_USERINFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo"
    _OAUTH_NO_CALLBACKS = False
    _OAUTH_SETTINGS_KEY = 'google_oauth'

    @_auth_return_future
    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):
                @tornado.gen.coroutine
                def get(self):
                    if self.get_argument('code', False):
                        access = yield self.get_authenticated_user(
                            redirect_uri='http://your.site.com/auth/google',
                            code=self.get_argument('code'))
                        user = yield 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:
                        yield 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:

        """
        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",
        })

        http.fetch(self._OAUTH_ACCESS_TOKEN_URL,
                   functools.partial(self._on_access_token, callback),
                   method="POST", headers={'Content-Type': 'application/x-www-form-urlencoded'}, body=body)

    def _on_access_token(self, future, response):
        """Callback function for the exchange to the access token."""
        if response.error:
            future.set_exception(AuthError('Google auth error: %s' % str(response)))
            return

        args = escape.json_decode(response.body)
        future.set_result(args)


class FacebookGraphMixin(OAuth2Mixin):
    """Facebook authentication using the new Graph API and OAuth2."""
    _OAUTH_ACCESS_TOKEN_URL = "https://graph.facebook.com/oauth/access_token?"
    _OAUTH_AUTHORIZE_URL = "https://www.facebook.com/dialog/oauth?"
    _OAUTH_NO_CALLBACKS = False
    _FACEBOOK_BASE_URL = "https://graph.facebook.com"

    @_auth_return_future
    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):
              @tornado.gen.coroutine
              def get(self):
                  if self.get_argument("code", False):
                      user = yield 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:
                      yield self.authorize_redirect(
                          redirect_uri='/auth/facebookgraph/',
                          client_id=self.settings["facebook_api_key"],
                          extra_params={"scope": "read_stream,offline_access"})

        .. testoutput::
           :hide:

        """
        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)

        http.fetch(self._oauth_request_token_url(**args),
                   functools.partial(self._on_access_token, redirect_uri, client_id,
                                     client_secret, callback, fields))

    def _on_access_token(self, redirect_uri, client_id, client_secret,
                         future, fields, response):
        if response.error:
            future.set_exception(AuthError('Facebook auth error: %s' % str(response)))
            return

        args = escape.parse_qs_bytes(escape.native_str(response.body))
        session = {
            "access_token": args["access_token"][-1],
            "expires": args.get("expires")
        }

        self.facebook_request(
            path="/me",
            callback=functools.partial(
                self._on_get_user_info, future, session, fields),
            access_token=session["access_token"],
            fields=",".join(fields)
        )

    def _on_get_user_info(self, future, session, fields, user):
        if user is None:
            future.set_result(None)
            return

        fieldmap = {}
        for field in fields:
            fieldmap[field] = user.get(field)

        fieldmap.update({"access_token": session["access_token"], "session_expires": session.get("expires")})
        future.set_result(fieldmap)

    @_auth_return_future
    def facebook_request(self, path, callback, access_token=None,
                         post_args=None, **args):
        """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
                @tornado.gen.coroutine
                def get(self):
                    new_entry = yield 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?
                        yield self.authorize_redirect()
                        return
                    self.finish("Posted a message!")

        .. testoutput::
           :hide:

        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``.
        """
        url = self._FACEBOOK_BASE_URL + path
        return self.oauth2_request(url, callback, access_token,
                                   post_args, **args)


def _oauth_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth signature for the given request.

    See http://oauth.net/core/1.0/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))
    base_string = "&".join(_oauth_escape(e) for e in base_elems)

    key_elems = [escape.utf8(consumer_token["secret"])]
    key_elems.append(escape.utf8(token["secret"] if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1]


def _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.

    See http://oauth.net/core/1.0a/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))

    base_string = "&".join(_oauth_escape(e) for e in base_elems)
    key_elems = [escape.utf8(urllib_parse.quote(consumer_token["secret"], safe='~'))]
    key_elems.append(escape.utf8(urllib_parse.quote(token["secret"], safe='~') if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1]


def _oauth_escape(val):
    if isinstance(val, unicode_type):
        val = val.encode("utf-8")
    return urllib_parse.quote(val, safe="~")


def _oauth_parse_response(body):
    # I can't find an officially-defined encoding for oauth responses and
    # have never seen anyone use non-ascii.  Leave the response in a byte
    # string for python 2, and use utf8 on python 3.
    body = escape.native_str(body)
    p = urlparse.parse_qs(body, keep_blank_values=False)
    token = dict(key=p["oauth_token"][0], secret=p["oauth_token_secret"][0])

    # Add the extra parameters the Provider included to the token
    special = ("oauth_token", "oauth_token_secret")
    token.update((k, p[k][0]) for k in p if k not in special)
    return token

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user