Search code examples
pythonasync-awaittornado

Tornado - getting return value from await (multiple callbacks)


I am working on an application with OAuth2 authentication in tornado. Login class looks as follows:

class IDPLogin(tornado.web.RequestHandler, IDPLoginHandler):
    async def get(self):
        if self.get_argument('code', False):
            access = await self.get_authenticated_user(
                ...
            )
            print(type(access))
            #self.set_secure_cookie('user', self.get_argument('code'))
            #self.redirect('/')
        else:
            await self.authorize_redirect(
                ...
            )

With get_authenticated_user method looking as follows (two extra callbacks for getting all the details required for evaluating user):

class IDPHubLoginHandler(tornado.auth.OAuth2Mixin):
    def __init__(self):
        self._OAUTH_AUTHORIZE_URL = "..."
        self._OAUTH_ACCESS_TOKEN_URL = "..."
        self._USERINFO_ENDPOINT = "..."

    async def get_authenticated_user(self, redirect_uri, client_id, client_secret, code):
        http = self.get_auth_http_client()
        body = urllib_parse.urlencode({
            "redirect_uri": redirect_uri,
            "code": code,
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
        })
        fut = http.fetch(self._OAUTH_ACCESS_TOKEN_URL,
                         method="POST",
                         headers={'Content-Type': 'application/x-www-form-urlencoded'},
                         body=body)
        fut.add_done_callback(wrap(functools.partial(self._on_access_token)))

    def _on_access_token(self, future):
        """Callback function for the exchange to the access token."""
        try:
            response = future.result()
        except Exception as e:
            future.set_exception(AuthError('IDP auth error: %s' % str(e)))
            return

        args = escape.json_decode(response.body)
        # Fetch userinfo
        http = self.get_auth_http_client()
        fut = http.fetch(self._USERINFO_ENDPOINT,
                         method="GET",
                         headers={
                             'Authorization': 'Bearer ' + args['access_token'],
                             'accept': 'application/json'
                         }
        )
        fut.add_done_callback(wrap(functools.partial(self._on_userinfo)))

    def _on_userinfo(self, future):
        response = future.result()
        r_body = escape.json_decode(response.body)
        return r_body

I want to be able to access body returned in _on_userinfo callback, but access in Login class is 'NoneType' and I would like to evaluate the response in order to either deny access or present user with a cookie.

Presented code is successful in obtaining all the required input data, however I am struggling to understand how to return values from callback and reuse them in main login class (IDPLogin). I have looked through Tornado documentation and couldn't find an answer. Oauth2/OpenID examples are very short on details at best.

Trying to set_result on future results in asyncio.base_futures.InvalidStateError.


Solution

  • Found another way to do it. Not sure if it's the most canonical way to do but seems to get the job done.

    1. Implement Oauth2 Mixin as follows:

      class IDPLoginHandler(tornado.auth.OAuth2Mixin):
      ...
          async def get_authenticated_user(self, redirect_uri, client_id, client_secret, code):
              #do fetching and return future result
          async def get_user_info(self, access_token):
              #do fetching and return future result
      
    2. Call methods sequentially with await keyword from main Login Handler:

      class IDPLogin(tornado.web.RequestHandler, IDPLoginHandler):
          async def get(self):
              if self.get_argument('code', False):
                  response_token = await self.get_authenticated_user(
                      ...
                  )
                  token = escape.json_decode(response_token.body)['access_token']
                  response_userinfo = await self.get_user_info(token)