def GetAccessTokenForApiQuery(api_query):
  """Attempts to retrieve a valid access token for an API Query.

  First retrieves the stored access token for the owner of the API Query, if
  available. Checks if token has expired and refreshes token if required (and
  saves it) before returning the token.

  Args:
    api_query: The API Query for which to retrieve an access token.

  Returns:
    A valid access token if available or None.
  """
  user_settings = users_helper.GetGaSuperProxyUser(api_query.user.key().name())
  if user_settings.ga_refresh_token and user_settings.ga_access_token:

    access_token = user_settings.ga_access_token

    # Check for expired access_token
    if datetime.utcnow() > user_settings.ga_token_expiry:
      response = FetchAccessToken(user_settings.ga_refresh_token)
      if (response.get('status_code') == 200 and response.get('content')
          and response.get('content').get('access_token')):
        access_token = response.get('content').get('access_token')
        expires_in = int(response.get('content').get('expires_in', 0))

        users_helper.SetUserCredentials(api_query.user.key().name(),
                                        user_settings.ga_refresh_token,
                                        access_token,
                                        expires_in)
    return access_token
  return None
dataset/ETHPy150Open googleanalytics/google-analytics-super-proxy/src/controllers/util/analytics_auth_helper.py/GetAccessTokenForApiQuery/original