Python requests_oauthlib 模块,OAuth2Session() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用requests_oauthlib.OAuth2Session()

项目:ELO-Darts    作者:pwgraham91    | 项目源码 | 文件源码
def get_google_auth(state=None, token=None):
    if token:
        return OAuth2Session(Auth.CLIENT_ID, token=token)
    if state:
        return OAuth2Session(
            Auth.CLIENT_ID,
            state=state,
            redirect_uri=Auth.REDIRECT_URI,
            scope=['email']
        )
    oauth = OAuth2Session(
        Auth.CLIENT_ID,
        redirect_uri=Auth.REDIRECT_URI,
        scope=['email']
    )
    return oauth
项目:ud-catalog    作者:aviaryan    | 项目源码 | 文件源码
def get_google_auth(state=None, token=None):
    """
    get_google_auth creates an oauth object for google oauth
    Thanks http://bitwiser.in/2015/09/09/add-google-login-in-flask.html
    """
    # if token from server is available, just use it
    # we can now fetch user info from google
    if token:
        return OAuth2Session(Auth.CLIENT_ID, token=token)
    # if state is set (& token is not), create an OAuth session to fetch token
    if state:
        return OAuth2Session(
            Auth.CLIENT_ID,
            state=state,
            redirect_uri=Auth.REDIRECT_URI)
    # neither token nor state is set
    # start a new oauth session
    oauth = OAuth2Session(
        Auth.CLIENT_ID,
        redirect_uri=Auth.REDIRECT_URI,
        scope=Auth.SCOPE)
    return oauth
项目:python-eduvpn-client    作者:eduvpn    | 项目源码 | 文件源码
def oauth_from_token(meta):
    """
    Recreate a oauth2 object from a token

    args:
        token (dict): a oauth2 token object
        token_updater (func): a function that is triggered upon a token update

    returns:
        OAuth2Session: an auth2 session

    """
    def inner(new_token):
        meta.update_token(new_token)

    return OAuth2Session(token=meta.token, auto_refresh_url=meta.token_endpoint, scope=scope, token_updater=inner,
                         client_id=client_id)
项目:rt_api    作者:NickMolloy    | 项目源码 | 文件源码
def _get_token(self):
        """Get an API token.

        Raises:
            AuthenticationError: if getting token fails.

        """
        client = BackendApplicationClient(client_id=CLIENT_ID)
        oauth = OAuth2Session(client=client)
        # Retry auth if error (to get around intermittent failures)
        latest_exception = None
        for i in range(3):
            try:
                token = oauth.fetch_token(
                    token_url=AUTH_URL, client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
                self.__token = token["access_token"]
                self.__session = oauth
                self._me = None
                return
            except (AccessDeniedError, InvalidClientError, MissingTokenError) as e:
                latest_exception = e
                continue
        raise AuthenticationError("Failed to get authentication token: {0}".format(latest_exception))
项目:cloudstrype    作者:btimby    | 项目源码 | 文件源码
def __init__(self, client_id, client_secret, user=None, storage=None,
                 redirect_uri=None, token=None, token_callback=None, **kwargs):
        self.client_id = client_id
        self.client_secret = client_secret
        self.user = user
        self.storage = storage
        self.token = token or {}
        self.token_callback = token_callback
        if self.token:
            # We already have a token, pass it along.
            self.oauthsession = OAuth2Session(
                token=self.token, **kwargs)
        else:
            # We have yet to obtain a token, so we have only the client ID etc.
            # needed to call `authorization_url()` and get a token.
            self.oauthsession = OAuth2Session(
                self.client_id, redirect_uri=redirect_uri,
                scope=self.SCOPES, **kwargs)
项目:cloudstrype    作者:btimby    | 项目源码 | 文件源码
def __init__(self, client_id, client_secret, user=None, storage=None,
                 redirect_uri=None, token=None, token_callback=None, **kwargs):
        self.client_id = client_id
        self.client_secret = client_secret
        self.user = user
        self.storage = storage
        self.token = token or {}
        self.token_callback = token_callback
        if self.token:
            # We already have a token, pass it along.
            self.oauthsession = OAuth2Session(
                token=self.token, **kwargs)
        else:
            # We have yet to obtain a token, so we have only the client ID etc.
            # needed to call `authorization_url()` and get a token.
            self.oauthsession = OAuth2Session(
                self.client_id, redirect_uri=redirect_uri,
                scope=self.SCOPES, **kwargs)
项目:cloudstrype    作者:btimby    | 项目源码 | 文件源码
def __init__(self, client_id, client_secret, user=None, storage=None,
                 redirect_uri=None, token=None, token_callback=None, **kwargs):
        self.client_id = client_id
        self.client_secret = client_secret
        self.user = user
        self.storage = storage
        self.token = token or {}
        self.token_callback = token_callback
        if self.token:
            # We already have a token, pass it along.
            self.oauthsession = OAuth2Session(
                token=self.token, **kwargs)
        else:
            # We have yet to obtain a token, so we have only the client ID etc.
            # needed to call `authorization_url()` and get a token.
            self.oauthsession = OAuth2Session(
                self.client_id, redirect_uri=redirect_uri,
                scope=self.SCOPES, **kwargs)
项目:MMM-fitbit    作者:SVendittelli    | 项目源码 | 文件源码
def __init__(self, client_id, client_secret,
                 access_token=None, refresh_token=None,
                 *args, **kwargs):
        """
        Create a FitbitOauth2Client object. Specify the first 7 parameters if
        you have them to access user data. Specify just the first 2 parameters
        to start the setup for user authorization (as an example see gather_key_oauth2.py)
            - client_id, client_secret are in the app configuration page
            https://dev.fitbit.com/apps
            - access_token, refresh_token are obtained after the user grants permission
        """

        self.session = requests.Session()
        self.client_id = client_id
        self.client_secret = client_secret
        self.token = {
            'access_token': access_token,
            'refresh_token': refresh_token
        }
        self.oauth = OAuth2Session(client_id)
项目:pymonzo    作者:pawelad    | 项目源码 | 文件源码
def _get_oauth_token(self):
        """
        Get Monzo access token via OAuth2 `authorization code` grant type.

        Official docs:
            https://monzo.com/docs/#acquire-an-access-token

        :returns: OAuth 2 access token
        :rtype: dict
        """
        url = urljoin(self.api_url, '/oauth2/token')

        oauth = OAuth2Session(
            client_id=self._client_id,
            redirect_uri=config.PYMONZO_REDIRECT_URI,
        )

        token = oauth.fetch_token(
            token_url=url,
            code=self._auth_code,
            client_secret=self._client_secret,
        )

        return token
项目:adarnauth-esi    作者:Adarnof    | 项目源码 | 文件源码
def refresh(self, session=None, auth=None):
        """
        Refreshes the token.
        :param session: :class:`requests_oauthlib.OAuth2Session` for refreshing token with.
        :param auth: :class:`requests.auth.HTTPBasicAuth`
        """
        if self.can_refresh:
            if not session:
                session = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID)
            if not auth:
                auth = HTTPBasicAuth(app_settings.ESI_SSO_CLIENT_ID, app_settings.ESI_SSO_CLIENT_SECRET)
            try:
                self.access_token = \
                    session.refresh_token(app_settings.ESI_TOKEN_URL, refresh_token=self.refresh_token, auth=auth)[
                        'access_token']
                self.created = timezone.now()
                self.save()
            except (InvalidGrantError, MissingTokenError):
                raise TokenInvalidError()
            except InvalidClientError:
                raise ImproperlyConfigured('Verify ESI_SSO_CLIENT_ID and ESI_SSO_CLIENT_SECRET settings.')
        else:
            raise NotRefreshableTokenError()
项目:Fitbit    作者:jaromirsalamon    | 项目源码 | 文件源码
def __init__(self, client_id, client_secret,
                 access_token=None, refresh_token=None,
                 *args, **kwargs):
        """
        Create a FitbitOauth2Client object. Specify the first 7 parameters if
        you have them to access user data. Specify just the first 2 parameters
        to start the setup for user authorization (as an example see gather_key_oauth2.py)
            - client_id, client_secret are in the app configuration page
            https://dev.fitbit.com/apps
            - access_token, refresh_token are obtained after the user grants permission
        """

        self.session = requests.Session()
        self.client_id = client_id
        self.client_secret = client_secret
        self.token = {
            'access_token': access_token,
            'refresh_token': refresh_token
        }
        self.oauth = OAuth2Session(client_id)
项目:python-mautic    作者:divio    | 项目源码 | 文件源码
def callback():
    """ Step 3: Retrieving an access token.

    The user has been redirected back from the provider to your registered
    callback URL. With this redirection comes an authorization code included
    in the redirect URL. We will use that to obtain an access token.
    """

    mautic = OAuth2Session(client_id, redirect_uri=redirect_uri,
                           state=session['oauth_state'])
    token = mautic.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url)

    # We use the session as a simple DB for this example.
    session['oauth_token'] = token
    update_token_tempfile(token)  # store token in /tmp/mautic_creds.json

    return redirect(url_for('.menu'))
项目:QuestradeAPI_PythonWrapper    作者:pcinat    | 项目源码 | 文件源码
def refresh():
    token = __get_session_token__()
    refresh_token_arg = request.args.get('refresh_token')

    if refresh_token_arg != None:
        refresh_token = refresh_token_arg
    else:
        try:
            refresh_token = token['refresh_token']
        except KeyError:
            refresh_token = ''

    questradeAPI = OAuth2Session(client_id, token=token)
    token = questradeAPI.refresh_token(token_url, refresh_token=refresh_token)

    __set_session_token__(token)

    return redirect(url_for('.token'))
项目:Epsilon    作者:Capuno    | 项目源码 | 文件源码
def cmd_info(message, parameters, recursion=0):
    await client.send_typing(message.channel)
    async for msg in client.logs_from(message.channel, limit=25):
        try:
            if msg.attachments:
                img = msg.attachments[0]['url']
                while not tokenAvailable:
                    asyncio.get_event_loop().create_task(tokenTimedOut())
                    await asyncio.sleep(1)
                api = OAuth2Session(aestheticsApiClientID, token=aesthToken)
                params = {'url': img, 'num_keywords': 10}
                keywords = api.get('https://api.everypixel.com/v1/keywords', params=params).json()
                quality = api.get('https://api.everypixel.com/v1/quality', params=params).json()
                if 'error' in params.keys() or 'error' in quality.keys():
                    await client.send_message(message.channel, "**Error:** API limit, you'll either have to wait like 5 mins so I get more requests or manually upload the image to https://everypixel.com/aesthetics")
                    return
                e = discord.Embed(colour=0x4DB15A)
                tags = [ tag['keyword'] for tag in keywords['keywords'] ]
                e.description = "```fix\nScore = {}% Awesome Image!```\n```md\n#{}```".format('{0:.1f}'.format(float(quality['quality']['score'])*100.0), "\n#".join(tags))
                await client.send_message(message.channel, embed=e)
                return
        except Exception as e:
            raise e
项目:flask-template    作者:pwgraham91    | 项目源码 | 文件源码
def get_google_auth(state=None, token=None):
    if token:
        return OAuth2Session(Auth.CLIENT_ID, token=token)
    if state:
        return OAuth2Session(
            Auth.CLIENT_ID,
            state=state,
            redirect_uri=Auth.REDIRECT_URI,
            scope=['email']
        )
    oauth = OAuth2Session(
        Auth.CLIENT_ID,
        redirect_uri=Auth.REDIRECT_URI,
        scope=['email']
    )
    return oauth
项目:google-auth-library-python-oauthlib    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def session_from_client_secrets_file(client_secrets_file, scopes, **kwargs):
    """Creates a :class:`requests_oauthlib.OAuth2Session` instance from a
    Google-format client secrets file.

    Args:
        client_secrets_file (str): The path to the `client secrets`_ .json
            file.
        scopes (Sequence[str]): The list of scopes to request during the
            flow.
        kwargs: Any additional parameters passed to
            :class:`requests_oauthlib.OAuth2Session`

    Returns:
        Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]: The new
            oauthlib session and the validated client configuration.

    .. _client secrets:
        https://developers.google.com/api-client-library/python/guide
        /aaa_client_secrets
    """
    with open(client_secrets_file, 'r') as json_file:
        client_config = json.load(json_file)

    return session_from_client_config(client_config, scopes, **kwargs)
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
def get_redirect_url(self, *args, **kwargs):
        client = OAuth2Session(
            client_id=settings.OAUTH['client_id'],
            redirect_uri=settings.OAUTH['redirect_domain'] + reverse('oauth_return_view'),
            scope=['view_profile'],
        )

        # extract next url
        next_url = self.request.GET.get('next', None)

        # save it to the session
        if next_url and is_safe_url(next_url):
            self.request.session['login_next_url'] = next_url

        # the user is then redirected to the auth provider with the right parameters
        url, state = client.authorization_url(settings.OAUTH['authorization_url'])

        # the nonce is saved inside the session
        self.request.session['oauth2_nonce'] = state
        return url
项目:pysnow    作者:rbw0    | 项目源码 | 文件源码
def __init__(self, client_id=None, client_secret=None, token_updater=None, **kwargs):

        if not (client_secret and client_id):
            raise InvalidUsage('You must supply a client_id and client_secret')

        if kwargs.get('session') or kwargs.get('user'):
            warnings.warn('pysnow.OAuthClient manages sessions internally, '
                          'provided user / password credentials or sessions will be ignored.')

        # Forcibly set session, user and password
        kwargs['session'] = OAuth2Session(client=LegacyApplicationClient(client_id=client_id))
        kwargs['user'] = None
        kwargs['password'] = None

        super(OAuthClient, self).__init__(**kwargs)

        self.token_updater = token_updater
        self.client_id = client_id
        self.client_secret = client_secret

        self.token_url = "%s/oauth_token.do" % self.base_url
项目:pysnow    作者:rbw0    | 项目源码 | 文件源码
def _get_oauth_session(self):
        """Creates a new OAuth session

        :return:
            - OAuth2Session object
        """

        return self._get_session(
            OAuth2Session(
                client_id=self.client_id,
                token=self.token,
                token_updater=self.token_updater,
                auto_refresh_url=self.token_url,
                auto_refresh_kwargs={
                    "client_id": self.client_id,
                    "client_secret": self.client_secret
                }
            )
        )
项目:stethoscope    作者:Netflix    | 项目源码 | 文件源码
def login(self, **kwargs):
    try:
      oauth2_session = requests_oauthlib.OAuth2Session(client_id=self.get_config_value('CLIENT_ID'),
          redirect_uri=self.callback_url(**kwargs),
          scope=self.get_config_value('SCOPES'),
          state=flask.session[self.state_session_key])
      token = oauth2_session.fetch_token(self.get_config_value('TOKEN_URL'),
          code=flask.request.args['code'], client_secret=self.get_config_value('CLIENT_SECRET'))
    except Exception as exc:
      flask.current_app.logger.exception("exception while retrieving token")
      self.login_failure_func(exc)

    try:
      profile = self.get_profile(oauth2_session)
    except Exception as exc:
      flask.current_app.logger.exception("exception while retrieving profile")
      self.login_failure_func(exc)
    # flask.current_app.logger.debug("profile: {!s}".format(pprint.pformat(profile)))

    return self.login_success_func(token, profile, **kwargs)
项目:github-buildservice-boilerplate    作者:m-vdb    | 项目源码 | 文件源码
def callback(request):
    """
    Step 2 of OAuth: fetch the token.
    """
    try:
        oauth_state = request.session['oauth_state']
    except KeyError:
        return HttpResponseBadRequest('Missing oauth state.')

    github = OAuth2Session(settings.GITHUB_CLIENT_ID, state=oauth_state)
    token = github.fetch_token(
        settings.GITHUB_TOKEN_URL,
        client_secret=settings.GITHUB_CLIENT_SECRET,
        authorization_response=request.build_absolute_uri()
    )

    try:
        OAuthToken.objects.create(user=request.user, value=token['access_token'])
    except (KeyError, TypeError):
        return HttpResponseBadRequest('Cannot read access_token.')

    Repository.add_user_to_known_repositories(request.user)
    return redirect("home")
项目:fitbit-fetch    作者:tomh05    | 项目源码 | 文件源码
def __init__(self, client_id , client_secret,
                access_token=None, refresh_token=None,
                *args, **kwargs):
        """
        Create a FitbitOauth2Client object. Specify the first 7 parameters if
        you have them to access user data. Specify just the first 2 parameters
        to start the setup for user authorization (as an example see gather_key_oauth2.py)
            - client_id, client_secret are in the app configuration page
            https://dev.fitbit.com/apps
            - access_token, refresh_token are obtained after the user grants permission
        """

        self.session = requests.Session()
        self.client_id = client_id
        self.client_secret = client_secret
        self.token = {'access_token' : access_token,
                      'refresh_token': refresh_token}
        self.oauth = OAuth2Session(client_id)
项目:fitbit-fetch    作者:tomh05    | 项目源码 | 文件源码
def test_auto_refresh_token_exception(self):
        # test of auto_refresh with tokenExpired exception
        # 1. first call to _request causes a TokenExpired
        # 2. the token_refresh call is faked
        # 3. the second call to _request returns a valid value
        kwargs = self.client_kwargs
        kwargs['access_token'] = 'fake_access_token'
        kwargs['refresh_token'] = 'fake_refresh_token'

        fb = Fitbit(**kwargs)
        with mock.patch.object(FitbitOauth2Client, '_request') as r:
            r.side_effect = [TokenExpiredError, fake_response(200,'correct_response')]
            with mock.patch.object(OAuth2Session, 'refresh_token') as rt:
                rt.return_value = {
                    'access_token': 'fake_return_access_token',
                    'refresh_token': 'fake_return_refresh_token'
                }
                retval = fb.client.make_request(Fitbit.API_ENDPOINT + '/1/user/-/profile.json')
        self.assertEqual("correct_response", retval.text)
        self.assertEqual("fake_return_access_token", fb.client.token['access_token'])
        self.assertEqual("fake_return_refresh_token", fb.client.token['refresh_token'])
        self.assertEqual(1, rt.call_count)
        self.assertEqual(2, r.call_count)
项目:xqz.es    作者:arahayrabedian    | 项目源码 | 文件源码
def callback():
    """ Step 3: Retrieving an access token.
    The user has been redirected back from the provider to your registered
    callback URL. With this redirection comes an authorization code included
    in the redirect URL. We will use that to obtain an access token.

    NOTE: your server name must be correctly configured in order for this to
    work, do this by adding the headers at your http layer, in particular:
    X_FORWARDED_HOST, X_FORWARDED_PROTO so that bottle can render the correct
    url and links for you.
    """
    oauth2session = OAuth2Session(settings.SLACK_OAUTH['client_id'],
                                  state=request.GET['state'])

    #PII - update privacy policy if oauth2 token is stored.
    token = oauth2session.fetch_token(
        settings.SLACK_OAUTH['token_url'],
        client_secret=settings.SLACK_OAUTH['client_secret'],
        authorization_response=request.url
    )

    # we don't need the token, we just need the user to have installed the app
    # in the future, if we need tokens, we'll get them.

    redirect('/?added_to_slack=true')
项目:DeviantArt-Extractor    作者:volfegan    | 项目源码 | 文件源码
def createDAsession():
    '''Create a DeviantArt session using The Client Credentials access by Backend Application Flow from oauthlib.oauth2 and OAuth2Session from Requests-OAuthlib '''
    global client_id, client_secret, deviantart_client, deviantart_session, token
    deviantart_session = OAuth2Session(client = deviantart_client)
    token=get_token()
    deviantart_session = OAuth2Session(client_id, token=token)
项目:DeviantArt-Extractor    作者:volfegan    | 项目源码 | 文件源码
def createDAsession():
    '''Create a DeviantArt session using The Client Credentials access by Backend Application Flow and OAuth2Session from oauthlib.oauth2 / Requests-OAuthlib '''
    global deviantart_client, deviantart_session, token
    deviantart_session = OAuth2Session(client = deviantart_client)
    token=get_token()
    deviantart_session = OAuth2Session(client_id, token=token)
项目:DeviantArt-Extractor    作者:volfegan    | 项目源码 | 文件源码
def createDAsession():
    '''Create a DeviantArt session using The Client Credentials access by Backend Application Flow and OAuth2Session from oauthlib.oauth2 / Requests-OAuthlib '''
    global deviantart_client, deviantart_session, token
    deviantart_session = OAuth2Session(client = deviantart_client)
    token=get_token()
    deviantart_session = OAuth2Session(client_id, token=token)
项目:DeviantArt-Extractor    作者:volfegan    | 项目源码 | 文件源码
def createDAsession():
    '''Create a DeviantArt session using The Client Credentials access by Backend Application Flow and OAuth2Session from oauthlib.oauth2 / Requests-OAuthlib '''
    global deviantart_client, deviantart_session, token
    deviantart_session = OAuth2Session(client = deviantart_client)
    token=get_token()
    deviantart_session = OAuth2Session(client_id, token=token)
项目:QOpenScienceFramework    作者:dschreij    | 项目源码 | 文件源码
def create_session():
    """ Creates/resets and OAuth 2 session, with the specified data. """
    global session
    global settings

    try:
        client_id = settings['client_id']
        redirect_uri = settings['redirect_uri']
    except KeyError as e:
        raise KeyError("The OAuth2 settings dictionary is missing the {} entry. "
            "Please add it to the QOpenScienceFramework.connection.settings "
            "dicationary before trying to create a new session".format(e))

    # Set up requests_oauthlib object
    mobile_app_client = MobileApplicationClient(client_id)

    # Create an OAuth2 session for the OSF
    session = requests_oauthlib.OAuth2Session(
        client_id,
        mobile_app_client,
        scope=scope,
        redirect_uri=redirect_uri,
    )
    return session

# Generate correct URLs
项目:QOpenScienceFramework    作者:dschreij    | 项目源码 | 文件源码
def is_authorized():
    """ Convenience function simply returning OAuth2Session.authorized. 

    Returns
    -------
    bool
        True is the user is authorized, False if not
    """
    check_for_active_session()
    return session.authorized
项目:python-eduvpn-client    作者:eduvpn    | 项目源码 | 文件源码
def create_oauth_session(port, auto_refresh_url):
    """
    Create a oauth2 callback webserver

    args:
        port (int): the port where to listen to
    returns:
        OAuth2Session: a oauth2 session object
    """
    logger.info("Creating an oauth session, temporarily starting webserver on port {} for auth callback".format(port))
    redirect_uri = 'http://127.0.0.1:%s/callback' % port
    oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, auto_refresh_url=auto_refresh_url, scope=scope)
    return oauth
项目:st2-auth-backend-oauth2    作者:pidah    | 项目源码 | 文件源码
def authenticate(self, username, password):

        if username in self._exclude_list:
            htpasswd_file = HtpasswdFile(path=self._file_path)
            result = htpasswd_file.check_password(username, password)

            if result is None:
                LOG.info('User "%s" doesn\'t exist' % (username))
            elif result is False:
                LOG.info('Invalid password for user "%s"' % (username))
            elif result is True:
                LOG.info(
                    'Authentication for user "%s" successful' %
                    (username))

            return bool(result)

        os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
        oauth = OAuth2Session(
            client=LegacyApplicationClient(
                client_id=self._client_id))

        try:
            token = oauth.fetch_token(
                token_url=self._token_url,
                username=username,
                password=password,
                client_id=self._client_id,
                client_secret=self._client_secret,
                verify=False)
        except Exception as e:
            LOG.info(
                'Authentication for user "{}" failed: {}'.format(
                    username, str(e)))
            return False
        if token is not None:
            LOG.info('Authentication for user "{}" successful'.format(username))
            return True

        return False
项目:django-authlib    作者:matthiask    | 项目源码 | 文件源码
def __init__(self, request):
        self._request = request
        self._session = OAuth2Session(
            self.client_id,
            scope=self.scope,
            redirect_uri=request.build_absolute_uri('.'),
        )
项目:django-authlib    作者:matthiask    | 项目源码 | 文件源码
def __init__(self, request):
        self._request = request
        self._session = OAuth2Session(
            self.client_id,
            scope=self.scope,
            redirect_uri=request.build_absolute_uri('.'),
        )
项目:MMM-fitbit    作者:SVendittelli    | 项目源码 | 文件源码
def fetch_access_token(self, code, redirect_uri):

        """Step 2: Given the code from fitbit from step 1, call
        fitbit again and returns an access token object. Extract the needed
        information from that and save it to use in future API calls.
        the token is internally saved
        """
        auth = OAuth2Session(self.client_id, redirect_uri=redirect_uri)
        self.token = auth.fetch_token(
            self.access_token_url,
            username=self.client_id,
            password=self.client_secret,
            code=code)

        return self.token
项目:doorman    作者:mwielgoszewski    | 项目源码 | 文件源码
def get_authorize_url(self):
        provider = OAuth2Session(self.client_id,
                                 scope=self.scope,
                                 redirect_uri=self.redirect_uri)

        authorization_url, state = provider.authorization_url(
            self.base_url,
            access_type='online',
            approval_prompt='force',
        )

        session['_oauth_state'] = state

        return authorization_url
项目:pymonzo    作者:pawelad    | 项目源码 | 文件源码
def _get_response(self, method, endpoint, params=None):
        """
        Helper method to handle HTTP requests and catch API errors

        :param method: valid HTTP method
        :type method: str
        :param endpoint: API endpoint
        :type endpoint: str
        :param params: extra parameters passed with the request
        :type params: dict
        :returns: API response
        :rtype: Response
        """
        url = urljoin(self.api_url, endpoint)

        try:
            response = getattr(self._session, method)(url, params=params)

            # Check if Monzo API returned HTTP 401, which could mean that the
            # token is expired
            if response.status_code == 401:
                raise TokenExpiredError

        except TokenExpiredError:
            # For some reason 'requests-oauthlib' automatic token refreshing
            # doesn't work so we do it here semi-manually
            self._refresh_oath_token()

            self._session = OAuth2Session(
                client_id=self._client_id,
                token=self._token,
            )

            response = getattr(self._session, method)(url, params=params)

        if response.status_code != requests.codes.ok:
            raise MonzoAPIError(
                "Something went wrong: {}".format(response.json())
            )

        return response
项目:django-discord-bind    作者:mrogaski    | 项目源码 | 文件源码
def oauth_session(request, state=None, token=None):
    """ Constructs the OAuth2 session object. """
    if settings.DISCORD_REDIRECT_URI is not None:
        redirect_uri = settings.DISCORD_REDIRECT_URI
    else:
        redirect_uri = request.build_absolute_uri(
            reverse('discord_bind_callback'))
    scope = (['email', 'guilds.join'] if settings.DISCORD_EMAIL_SCOPE
             else ['identity', 'guilds.join'])
    return OAuth2Session(settings.DISCORD_CLIENT_ID,
                         redirect_uri=redirect_uri,
                         scope=scope,
                         token=token,
                         state=state)
项目:adarnauth-esi    作者:Adarnof    | 项目源码 | 文件源码
def bulk_refresh(self):
        """
        Refreshes all refreshable tokens in the queryset.
        Deletes any tokens which fail to refresh.
        Deletes any tokens which are expired and cannot refresh.
        """
        session = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID)
        auth = requests.auth.HTTPBasicAuth(app_settings.ESI_SSO_CLIENT_ID, app_settings.ESI_SSO_CLIENT_SECRET)
        for model in self.filter(refresh_token__isnull=False):
            try:
                model.refresh(session=session, auth=auth)
            except TokenError:
                model.delete()
        self.filter(refresh_token__isnull=True).get_expired().delete()
项目:adarnauth-esi    作者:Adarnof    | 项目源码 | 文件源码
def sso_redirect(request, scopes=list([]), return_to=None):
    """
    Generates a :model:`esi.CallbackRedirect` for the specified request.
    Redirects to EVE for login.
    Accepts a view or URL name as a redirect after SSO.
    """
    if isinstance(scopes, string_types):
        scopes = list([scopes])

    # ensure only one callback redirect model per session
    CallbackRedirect.objects.filter(session_key=request.session.session_key).delete()

    # ensure session installed in database
    if not request.session.exists(request.session.session_key):
        request.session.create()

    if return_to:
        url = reverse(return_to)
    else:
        url = request.get_full_path()

    oauth = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID, redirect_uri=app_settings.ESI_SSO_CALLBACK_URL, scope=scopes)
    redirect_url, state = oauth.authorization_url(app_settings.ESI_OAUTH_LOGIN_URL)

    CallbackRedirect.objects.create(session_key=request.session.session_key, state=state, url=url)

    return redirect(redirect_url)
项目:adarnauth-esi    作者:Adarnof    | 项目源码 | 文件源码
def get_token_data(cls, access_token):
        session = OAuth2Session(app_settings.ESI_SSO_CLIENT_ID, token={'access_token': access_token})
        return session.request('get', app_settings.ESI_TOKEN_VERIFY_URL).json()
项目:Fitbit    作者:jaromirsalamon    | 项目源码 | 文件源码
def fetch_access_token(self, code, redirect_uri):

        """Step 2: Given the code from fitbit from step 1, call
        fitbit again and returns an access token object. Extract the needed
        information from that and save it to use in future API calls.
        the token is internally saved
        """
        auth = OAuth2Session(self.client_id, redirect_uri=redirect_uri)
        self.token = auth.fetch_token(
            self.access_token_url,
            username=self.client_id,
            password=self.client_secret,
            code=code)

        return self.token
项目:python-mautic    作者:divio    | 项目源码 | 文件源码
def __init__(
        self,
        base_url,
        client_id,
        client_secret=None,
        scope=None,
        token=None,
        token_updater=None
    ):
        """
        :param base_url: str Base URL for Mautic API E.g. `https://<your-domain>.mautic.net`
        :param client_id: str Mautic API Public Key
        :param client_secret: str Mautic API Secret Key - needed to autorefresh token
        :param scope: list|str
        :param token: dict with access token data
        :param token_updater: function used for token autorefresh.
        """
        if scope and not isinstance(scope, (list, tuple)):
            scope = scope.split(',')
        self.base_url = base_url.strip(' /')

        self.access_token_url = base_url + '/oauth/v2/token'
        self.authorization_base_url = base_url + '/oauth/v2/authorize'

        if token_updater is not None and client_secret is not None:
            kwargs = {
                'auto_refresh_url': self.access_token_url,
                'auto_refresh_kwargs': {
                    'client_id': client_id,
                    'client_secret': client_secret
                },
                'token_updater': token_updater
            }
        else:
            kwargs = {}

        self.session = OAuth2Session(
            client_id, scope=scope, token=token, **kwargs
        )
项目:python-mautic    作者:divio    | 项目源码 | 文件源码
def index():
    """Step 1: User Authorization.

    Redirect the user/resource owner to the OAuth provider using an URL with a few key OAuth parameters.
    """
    mautic = OAuth2Session(client_id, redirect_uri=redirect_uri)
    authorization_url, state = mautic.authorization_url(authorization_base_url, grant_type='authorization_code')

    session['oauth_state'] = state
    return redirect(authorization_url)


# Step 2: User authorization, this happens on the provider.
项目:NZ-ORCID-Hub    作者:Royal-Society-of-New-Zealand    | 项目源码 | 文件源码
def make_fake_response(text, *args, **kwargs):
    """Mock out the response object returned by requests_oauthlib.OAuth2Session.get(...)."""
    mm = MagicMock(name="response")
    mm.text = text
    if "json" in kwargs:
        mm.json.return_value = kwargs["json"]
    else:
        mm.json.return_value = json.loads(text)
    if "status_code" in kwargs:
        mm.status_code = kwargs["status_code"]
    return mm
项目:NZ-ORCID-Hub    作者:Royal-Society-of-New-Zealand    | 项目源码 | 文件源码
def profile():
    """Fetch a protected resource using an OAuth 2 token."""
    user = current_user
    app.logger.info(f"For {user} trying to display profile by getting ORCID token")
    try:
        orcid_token = OrcidToken.get(user_id=user.id, org=user.organisation)
    except OrcidToken.DoesNotExist:
        app.logger.info(f"For {user} we dont have ocrditoken so redirecting back to link page")
        return redirect(url_for("link"))

    except Exception as ex:
        # TODO: need to handle this
        app.logger.exception("Failed to retrieve ORCID token form DB.")
        flash("Unhandled Exception occured: %s" % ex, "danger")
        return redirect(url_for("login"))
    else:
        client = OAuth2Session(
            user.organisation.orcid_client_id, token={
                "access_token": orcid_token.access_token
            })
        base_url = ORCID_API_BASE + user.orcid
        # TODO: utilize asyncio/aiohttp to run it concurrently
        resp_person = client.get(base_url + "/person", headers=HEADERS)
        app.logger.info("For %r logging response code %r, While fetching profile info", user,
                        resp_person.status_code)
        if resp_person.status_code == 401:
            orcid_token.delete_instance()
            app.logger.info("%r has removed his organisation from trusted list", user)
            return redirect(url_for("link"))
        else:
            users = User.select().where(User.orcid == user.orcid)
            users_orcid = OrcidToken.select().where(OrcidToken.user.in_(users))
            app.logger.info("For %r everything is fine, So displaying profile page", user)
            return render_template(
                "profile.html", user=user, users_orcid=users_orcid, profile_url=ORCID_BASE_URL)
项目:bluebutton-web-server    作者:CMSgov    | 项目源码 | 文件源码
def callback(request):

    response = OrderedDict()

    oas = OAuth2Session(request.session['client_id'],
                        redirect_uri=request.session['redirect_uri'])

    host = settings.HOSTNAME_URL

    if not(host.startswith("http://") or host.startswith("https://")):
        host = "https://%s" % (host)
    auth_uri = host + request.get_full_path()
    token = oas.fetch_token(request.session['token_uri'],
                            client_secret=request.session['client_secret'],
                            authorization_response=auth_uri)
    request.session['token'] = token
    response['token_response'] = OrderedDict()

    for k, v in token.items():
        if k != "scope":
            response['token_response'][k] = v
        else:
            response['token_response'][k] = ' '.join(v)

    userinfo = oas.get(request.session['userinfo_uri']).json()
    response[request.session['userinfo_uri']] = userinfo
    request.session['patient'] = userinfo['patient']

    response['oidc_discovery_uri'] = host + \
        reverse('openid-configuration')

    response['fhir_metadata_uri'] = host + \
        reverse('fhir_conformance_metadata')

    response['test_page'] = host + reverse('test_links')

    return JsonResponse(response)
项目:bluebutton-web-server    作者:CMSgov    | 项目源码 | 文件源码
def test_userinfo(request):
    oas = OAuth2Session(
        request.session['client_id'], token=request.session['token'])
    userinfo_uri = "%s/connect/userinfo" % (request.session['resource_uri'])
    userinfo = oas.get(userinfo_uri).json()
    return JsonResponse(userinfo)
项目:bluebutton-web-server    作者:CMSgov    | 项目源码 | 文件源码
def test_coverage(request):
    oas = OAuth2Session(
        request.session['client_id'], token=request.session['token'])
    coverage_uri = "%s/protected/bluebutton/fhir/v1/Coverage/?_format=json" % (
        request.session['resource_uri'])

    coverage = oas.get(coverage_uri).json()
    return JsonResponse(coverage, safe=False)
项目:bluebutton-web-server    作者:CMSgov    | 项目源码 | 文件源码
def test_patient(request):
    oas = OAuth2Session(
        request.session['client_id'], token=request.session['token'])
    patient_uri = "%s/protected/bluebutton/fhir/v1/Patient/%s?_format=json" % (
        request.session['resource_uri'], request.session['patient'])
    patient = oas.get(patient_uri).json()
    return JsonResponse(patient)