# Buggy code
def create_session(self):
    """Create OAuth session for user

    This configures the OAuth session based on the :py:class:`SocialToken`
    attributes. If there is an ``expires_at``, treat the session as an auto
    renewing token. Some providers expire tokens after as little as 2
    hours.
    """
    token = self.account.socialtoken_set.first()
    if token is None:
        return None

    token_config = {
        "access_token": str(token.token),
        "token_type": "bearer",
    }
    if token.expires_at is not None:
        token_expires = (token.expires_at - datetime.now()).total_seconds()
        token_config.update(
            {
                "refresh_token": str(token.token_secret),
                "expires_in": token_expires,
            }
        )

    self.session = OAuth2Session(
        client_id=token.app.client_id,
        token=token_config,
        auto_refresh_kwargs={
            "client_id": token.app.client_id,
            "client_secret": token.app.secret,
        },
        auto_refresh_url=self.get_adapter().access_token_url,
        token_updater=self.token_updater(token),
    )

    return self.session or None


# Traceback (InvalidClientIdError)
[05/Jul/2017 14:44:13] celery.worker.job:282[33151]: ERROR Task readthedocs.oauth.tasks.SyncRemoteRepositories[86bd1cbd-0c99-44a6-b5d7-9beadb917a7b] raised unexpected: InvalidClientIdError(u'(invalid_request) (invalid_request) Invalid
refresh_token',)
Traceback (most recent call last):
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/anthony/dev/readthedocs.org/readthedocs/core/utils/tasks/public.py", line 71, in run
result = self.run_public(*args, **kwargs)
File "/Users/anthony/dev/readthedocs.org/readthedocs/oauth/tasks.py", line 22, in run_public
service.sync()
File "/Users/anthony/dev/readthedocs.org/readthedocs/oauth/services/bitbucket.py", line 38, in sync
self.sync_repositories()
File "/Users/anthony/dev/readthedocs.org/readthedocs/oauth/services/bitbucket.py", line 46, in sync_repositories
'https://bitbucket.org/api/2.0/repositories/?role=member')
File "/Users/anthony/dev/readthedocs.org/readthedocs/oauth/services/bitbucket.py", line 172, in paginate
resp = self.get_session().get(url)
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/requests/sessions.py", line 468, in get
return self.request('GET', url, **kwargs)
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/requests_oauthlib/oauth2_session.py", line 343, in request
self.auto_refresh_url, auth=auth, **kwargs
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/requests_oauthlib/oauth2_session.py", line 309, in refresh_token
self.token = self._client.parse_request_body_response(r.text, scope=self.scope)
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 409, in parse_request_body_response
self.token = parse_token_response(body, scope=scope)
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 376, in parse_token_response
validate_token_parameters(params)
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 383, in validate_token_parameters
raise_from_error(params.get('error'), params)
File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/errors.py", line 325, in raise_from_error
raise cls(**kwargs)
InvalidClientIdError: (invalid_request) (invalid_request) Invalid refresh_token

# Fixed code
def create_session(self):
    """Create OAuth session for user

    This configures the OAuth session based on the :py:class:`SocialToken`
    attributes. If there is an ``expires_at``, treat the session as an auto
    renewing token. Some providers expire tokens after as little as 2
    hours.
    """
    token = self.account.socialtoken_set.first()
    if token is None:
        return None

    token_config = {
        "access_token": token.token,
        "token_type": "bearer",
    }
    if token.expires_at is not None:
        token_expires = (token.expires_at - datetime.now()).total_seconds()
        token_config.update(
            {
                "refresh_token": token.token_secret,
                "expires_in": token_expires,
            }
        )

    self.session = OAuth2Session(
        client_id=token.app.client_id,
        token=token_config,
        auto_refresh_kwargs={
            "client_id": token.app.client_id,
            "client_secret": token.app.secret,
        },
        auto_refresh_url=self.get_adapter().access_token_url,
        token_updater=self.token_updater(token),
    )

    return self.session or None