Python oauth2.Token() Examples

The following are 23 code examples of oauth2.Token(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oauth2 , or try the search function .
Example #1
Source File: instapaper.py    From pyinstapaper with MIT License 6 votes vote down vote up
def login(self, username, password):
        '''Authenticate using XAuth variant of OAuth.

        :param str username: Username or email address for the relevant account
        :param str password: Password for the account
        '''
        response = self.request(
            ACCESS_TOKEN,
            {
                'x_auth_mode': 'client_auth',
                'x_auth_username': username,
                'x_auth_password': password
            },
            returns_json=False
        )
        token = dict(parse_qsl(response['data'].decode()))
        self.token = oauth.Token(
            token['oauth_token'], token['oauth_token_secret'])
        self.oauth_client = oauth.Client(self.consumer, self.token) 
Example #2
Source File: trading.py    From trump2cash with MIT License 6 votes vote down vote up
def make_request(self, url, method="GET", body="", headers=None):
        """Makes a request to the TradeKing API."""

        consumer = Consumer(key=TRADEKING_CONSUMER_KEY,
                            secret=TRADEKING_CONSUMER_SECRET)
        token = Token(key=TRADEKING_ACCESS_TOKEN,
                      secret=TRADEKING_ACCESS_TOKEN_SECRET)
        client = Client(consumer, token)

        body_bytes = body.encode("utf-8")
        self.logs.debug("TradeKing request: %s %s %s %s" %
                        (url, method, body_bytes, headers))
        response, content = client.request(url, method=method,
                                           body=body_bytes,
                                           headers=headers)
        self.logs.debug("TradeKing response: %s %s" % (response, content))

        try:
            return loads(content)
        except ValueError:
            self.logs.error("Failed to decode JSON response: %s" % content)
            return None 
Example #3
Source File: cartodb.py    From qgis-cartodb with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, key, secret, email, password, cartodb_domain, host='carto.com', protocol='https', proxy_info=None, *args, **kwargs):
        super(CartoDBOAuth, self).__init__(cartodb_domain, host, protocol, *args, **kwargs)

        self.consumer_key = key
        self.consumer_secret = secret
        consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)

        client = oauth.Client(consumer, proxy_info=proxy_info)
        client.set_signature_method = oauth.SignatureMethod_HMAC_SHA1()

        params = {}
        params["x_auth_username"] = email
        params["x_auth_password"] = password
        params["x_auth_mode"] = 'client_auth'

        # Get Access Token
        access_token_url = ACCESS_TOKEN_URL % {'user': cartodb_domain, 'domain': host, 'protocol': protocol}
        resp, token = client.request(access_token_url, method="POST", body=urllib.urlencode(params))
        access_token = dict(urlparse.parse_qsl(token))
        token = oauth.Token(access_token['oauth_token'], access_token['oauth_token_secret'])

        # prepare client
        self.client = oauth.Client(consumer, token) 
Example #4
Source File: imapclient.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
def oauth_login(self, url, oauth_token, oauth_token_secret,
                    consumer_key='anonymous', consumer_secret='anonymous'):
        """Authenticate using the OAUTH method.

        This only works with IMAP servers that support OAUTH (e.g. Gmail).
        """
        if oauth_module:
            token = oauth_module.Token(oauth_token, oauth_token_secret)
            consumer = oauth_module.Consumer(consumer_key, consumer_secret)
            xoauth_callable = lambda x: oauth_module.build_xoauth_string(url,
                                                                         consumer,
                                                                         token)
            return self._command_and_check('authenticate', 'XOAUTH',
                                           xoauth_callable, unpack=True)
        else:
            raise self.Error(
                'The optional oauth2 package is needed for OAUTH authentication') 
Example #5
Source File: twitter_auth.py    From Python-Programming-Blueprints with MIT License 6 votes vote down vote up
def callback():

    global req_token
    global consumer

    config = read_config()

    oauth_verifier = request.args.get('oauth_verifier', '')

    token = oauth.Token(req_token.oauth_token,
                        req_token.oauth_token_secret)

    token.set_verifier(oauth_verifier)

    client = oauth.Client(consumer, token)

    resp, content = client.request(config.access_token_url, 'POST')
    access_token = dict(parse_qsl(content.decode('utf-8')))

    with open('.twitterauth', 'w') as req_auth:
        file_content = yaml.dump(access_token, default_flow_style=False)
        req_auth.write(file_content)

    return 'All set! You can close the browser window and stop the server.' 
Example #6
Source File: test_auth.py    From allura with Apache License 2.0 5 votes vote down vote up
def test_generate_revoke_access_token(self):
        # generate
        self.app.get('/').follow()  # establish session
        r = self.app.post('/auth/oauth/register',
                          params={'application_name': 'oautstapp', 'application_description': 'Oauth rulez',
                                  '_session_id': self.app.cookies['_session_id'],
                                  }, status=302)
        r = self.app.get('/auth/oauth/')
        assert_equal(r.forms[1].action, 'generate_access_token')
        r = r.forms[1].submit(extra_environ={'username': str('test-user')})  # not the right user
        assert_in("Invalid app ID", self.webflash(r))                   # gets an error
        r = self.app.get('/auth/oauth/')                                # do it again
        r = r.forms[1].submit()                                         # as correct user
        assert_equal('', self.webflash(r))

        r = self.app.get('/auth/oauth/')
        assert 'Bearer Token:' in r
        assert_not_equal(
            M.OAuthAccessToken.for_user(M.User.by_username('test-admin')), [])
        # revoke
        assert_equal(r.forms[0].action, 'revoke_access_token')
        r.forms[0].submit()
        r = self.app.get('/auth/oauth/')
        assert_not_equal(r.forms[0].action, 'revoke_access_token')
        assert_equal(
            M.OAuthAccessToken.for_user(M.User.by_username('test-admin')), []) 
Example #7
Source File: oauth.py    From allura with Apache License 2.0 5 votes vote down vote up
def as_token(self):
        return oauth.Token(self.api_key, self.secret_key) 
Example #8
Source File: oauth.py    From allura with Apache License 2.0 5 votes vote down vote up
def to_string(self):
        return oauth.Token(self.api_key, self.secret_key).to_string() 
Example #9
Source File: imap.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def authenticate(self, url, consumer, token):
        if consumer is not None and not isinstance(consumer, oauth2.Consumer):
            raise ValueError("Invalid consumer.")

        if token is not None and not isinstance(token, oauth2.Token):
            raise ValueError("Invalid token.")

        imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH',
            lambda x: oauth2.build_xoauth_string(url, consumer, token)) 
Example #10
Source File: smtp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def authenticate(self, url, consumer, token):
        if consumer is not None and not isinstance(consumer, oauth2.Consumer):
            raise ValueError("Invalid consumer.")

        if token is not None and not isinstance(token, oauth2.Token):
            raise ValueError("Invalid token.")

        self.docmd('AUTH', 'XOAUTH %s' % \
            base64.b64encode(oauth2.build_xoauth_string(url, consumer, token))) 
Example #11
Source File: views.py    From CLAtoolkit with GNU General Public License v3.0 5 votes vote down vote up
def lrs_oauth_callback(request):
    import os
    import urlparse

    user_id = request.user.id
    user = User.objects.get(id=user_id)

    status = request.GET.get('status')
    if status is not None and status == 'fail':
        return HttpResponseServerError('Could not get access token.')

    request_token = OAuthTempRequestToken.objects.get(user_id=user)
    verifier = request.GET.get('oauth_verifier')

    token = oauth.Token(request_token.token, request_token.secret)
    request_token.delete() #delete temp token
    token.set_verifier(verifier)

    # Get Consumer info #Todo: change (most definitely) (IMPORTANT!!)
    # consumer_key, consumer_secret = get_consumer_key_and_secret()
    app = ClientApp.objects.get(id = request_token.clientapp.id)
    client = oauth.Client(oauth.Consumer(app.get_key(), app.get_secret()), token)

    # Exchange request_token for authed and verified access_token
    resp,content = client.request(app.get_access_token_url(), "POST")
    access_token = dict(urlparse.parse_qsl(content))

    if access_token['oauth_token']:
        UserAccessToken_LRS(user=user, access_token=access_token['oauth_token'],
                            access_token_secret=access_token['oauth_token_secret'],
                            clientapp = app).save()
        from django.shortcuts import render_to_response
        return render_to_response('xapi/get_access_token_successful.html') 
Example #12
Source File: authentication.py    From baobab with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, consumer_key, consumer_secret, token_key, token_secret):
        consumer = Consumer(key=consumer_key, secret=consumer_secret)
        token = Token(key=token_key, secret=token_secret)

        proxy_info = None
        if hasattr(settings, 'PROXY_HOST') and \
                hasattr(settings, 'PROXY_PORT'):
            proxy_info = ProxyInfo(
                proxy_type=PROXY_TYPE_HTTP,
                proxy_host=settings.PROXY_HOST,
                proxy_port=settings.PROXY_PORT)
        self.client = Client(
            consumer=consumer,
            token=token,
            proxy_info=proxy_info) 
Example #13
Source File: oauth.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def step2_exchange(self, verifier):
    """Exhanges an authorized request token
    for OAuthCredentials.

    Args:
      verifier: string, dict - either the verifier token, or a dictionary
        of the query parameters to the callback, which contains
        the oauth_verifier.
    Returns:
       The Credentials object.
    """

    if not (isinstance(verifier, str) or isinstance(verifier, unicode)):
      verifier = verifier['oauth_verifier']

    token = oauth.Token(
        self.request_token['oauth_token'],
        self.request_token['oauth_token_secret'])
    token.set_verifier(verifier)
    consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
    client = oauth.Client(consumer, token)

    headers = {
        'user-agent': self.user_agent,
        'content-type': 'application/x-www-form-urlencoded'
    }

    uri = _oauth_uri('access', self.discovery, self.params)
    resp, content = client.request(uri, 'POST', headers=headers)
    if resp['status'] != '200':
      logging.error('Failed to retrieve access token: %s', content)
      raise RequestError('Invalid response %s.' % resp['status'])

    oauth_params = dict(parse_qsl(content))
    token = oauth.Token(
        oauth_params['oauth_token'],
        oauth_params['oauth_token_secret'])

    return OAuthCredentials(consumer, token, self.user_agent) 
Example #14
Source File: oauth.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def __init__(self, consumer, token, user_agent):
    """
    consumer   - An instance of oauth.Consumer.
    token      - An instance of oauth.Token constructed with
                 the access token and secret.
    user_agent - The HTTP User-Agent to provide for this application.
    """
    self.consumer = consumer
    self.token = token
    self.user_agent = user_agent
    self.store = None

    # True if the credentials have been revoked
    self._invalid = False 
Example #15
Source File: request.py    From Python-Programming-Blueprints with MIT License 5 votes vote down vote up
def prepare_request(url, url_params):
    reqconfig = read_reqauth()
    config = read_config()

    token = oauth.Token(
        key=reqconfig.oauth_token,
        secret=reqconfig.oauth_token_secret)

    consumer = oauth.Consumer(
        key=config.consumer_key,
        secret=config.consumer_secret)

    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_timestamp': str(int(time.time()))
    }

    params['oauth_token'] = token.key
    params['oauth_consumer_key'] = consumer.key

    params.update(url_params)

    req = oauth.Request(method="GET", url=url, parameters=params)

    signature_method = oauth.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, token)

    return req.to_url() 
Example #16
Source File: imap.py    From qgis-cartodb with GNU General Public License v2.0 5 votes vote down vote up
def authenticate(self, url, consumer, token):
        if consumer is not None and not isinstance(consumer, oauth2.Consumer):
            raise ValueError("Invalid consumer.")

        if token is not None and not isinstance(token, oauth2.Token):
            raise ValueError("Invalid token.")

        imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH',
            lambda x: oauth2.build_xoauth_string(url, consumer, token)) 
Example #17
Source File: smtp.py    From qgis-cartodb with GNU General Public License v2.0 5 votes vote down vote up
def authenticate(self, url, consumer, token):
        if consumer is not None and not isinstance(consumer, oauth2.Consumer):
            raise ValueError("Invalid consumer.")

        if token is not None and not isinstance(token, oauth2.Token):
            raise ValueError("Invalid token.")

        self.docmd('AUTH', 'XOAUTH %s' % \
            base64.b64encode(oauth2.build_xoauth_string(url, consumer, token))) 
Example #18
Source File: demo3_get_access_token.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def get_access_token(oauth_token, oauth_secret, oauth_verifier):
    consumer = oauth.Consumer(key='9fdce0e111a1489eb5a42eab7a84306b', secret='liqutXmqJpKmetfs')
    token = oauth.Token(oauth_token, oauth_secret)
    token.set_verifier(oauth_verifier)
    oauth_request = oauth.Request.from_consumer_and_token(consumer, token, http_url=ACCESS_TOKEN_URL)
    oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token)
    response = requests.get(ACCESS_TOKEN_URL, headers=oauth_request.to_header())
    access_token = dict(urllib.parse.parse_qsl(response.content.decode('utf8')))

    return access_token 
Example #19
Source File: demo4_use_access_token.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def use_access_token(oauth_token, oauth_secret):
    consumer = oauth.Consumer(key='9fdce0e111a1489eb5a42eab7a84306b', secret='liqutXmqJpKmetfs')
    token = oauth.Token(oauth_token, oauth_secret)
    oauth_request = oauth.Request.from_consumer_and_token(consumer, http_url=RESOURCE_URL)
    oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token)

    # get the resource
    response = requests.get(RESOURCE_URL, headers=oauth_request.to_header())
    return response.text 
Example #20
Source File: test_auth.py    From allura with Apache License 2.0 4 votes vote down vote up
def test_interactive(self):
        with mock.patch('allura.controllers.rest.oauth.Server') as Server, \
                mock.patch('allura.controllers.rest.oauth.Request') as Request:   # these are the oauth2 libs
            user = M.User.by_username('test-admin')
            M.OAuthConsumerToken(
                api_key='api_key',
                user_id=user._id,
                description='ctok_desc',
            )
            ThreadLocalORMSession.flush_all()
            Request.from_request.return_value = {
                'oauth_consumer_key': 'api_key',
                'oauth_callback': 'http://my.domain.com/callback',
            }
            r = self.app.post('/rest/oauth/request_token', params={})
            rtok = parse_qs(r.text)['oauth_token'][0]
            r = self.app.post('/rest/oauth/authorize',
                              params={'oauth_token': rtok})
            r = r.forms[0].submit('yes')
            assert r.location.startswith('http://my.domain.com/callback')
            pin = parse_qs(urlparse(r.location).query)['oauth_verifier'][0]
            Request.from_request.return_value = {
                'oauth_consumer_key': 'api_key',
                'oauth_token': rtok,
                'oauth_verifier': pin,
            }
            r = self.app.get('/rest/oauth/access_token')
            atok = parse_qs(r.text)
            assert_equal(len(atok['oauth_token']), 1)
            assert_equal(len(atok['oauth_token_secret']), 1)

        # now use the tokens & secrets to make a full OAuth request:
        oauth_secret = atok['oauth_token_secret'][0]
        oauth_token = atok['oauth_token'][0]
        consumer = oauth2.Consumer('api_key', oauth_secret)
        M.OAuthConsumerToken.consumer = consumer
        access_token = oauth2.Token(oauth_token, oauth_secret)
        oauth_client = oauth2.Client(consumer, access_token)
        # use the oauth2 lib, but intercept the request and then send it to self.app.get
        with mock.patch('oauth2.httplib2.Http.request', name='hl2req') as oa2_req:
            oauth_client.request('http://localhost/rest/p/test/', 'GET')
            oa2url = oa2_req.call_args[0][1]
            oa2url = oa2url.replace('http://localhost', '')
            print(oa2url)
            oa2kwargs = oa2_req.call_args[1]
        self.app.get(oa2url, headers=oa2kwargs['headers'], status=200)
        self.app.get(oa2url.replace('oauth_signature=', 'removed='), headers=oa2kwargs['headers'], status=401) 
Example #21
Source File: wiki-copy.py    From allura with Apache License 2.0 4 votes vote down vote up
def make_oauth_client(base_url):
    """
    Build an oauth.Client with which callers can query Allura.
    """
    config_file = os.path.join(os.environ['HOME'], '.allurarc')
    cp = ConfigParser()
    cp.read(config_file)

    REQUEST_TOKEN_URL = base_url + '/rest/oauth/request_token'
    AUTHORIZE_URL = base_url + '/rest/oauth/authorize'
    ACCESS_TOKEN_URL = base_url + '/rest/oauth/access_token'
    oauth_key = option(cp, base_url, 'oauth_key',
                       'Forge API OAuth Key (%s/auth/oauth/): ' % base_url)
    oauth_secret = option(cp, base_url, 'oauth_secret',
                          'Forge API Oauth Secret: ')
    consumer = oauth.Consumer(oauth_key, oauth_secret)

    try:
        oauth_token = cp.get(base_url, 'oauth_token')
        oauth_token_secret = cp.get(base_url, 'oauth_token_secret')
    except NoOptionError:
        client = oauth.Client(consumer)
        resp, content = client.request(REQUEST_TOKEN_URL, 'GET')
        assert resp['status'] == '200', resp

        request_token = dict(six.moves.urllib.parse.parse_qsl(content))
        pin_url = "%s?oauth_token=%s" % (
            AUTHORIZE_URL, request_token['oauth_token'])
        if getattr(webbrowser.get(), 'name', '') == 'links':
            # sandboxes
            print(("Go to %s" % pin_url))
        else:
            webbrowser.open(pin_url)
        oauth_verifier = input('What is the PIN? ')

        token = oauth.Token(
            request_token['oauth_token'], request_token['oauth_token_secret'])
        token.set_verifier(oauth_verifier)
        client = oauth.Client(consumer, token)
        resp, content = client.request(ACCESS_TOKEN_URL, "GET")
        access_token = dict(six.moves.urllib.parse.parse_qsl(content))
        oauth_token = access_token['oauth_token']
        oauth_token_secret = access_token['oauth_token_secret']

        cp.set(base_url, 'oauth_token', oauth_token)
        cp.set(base_url, 'oauth_token_secret', oauth_token_secret)

    # save oauth token for later use
    cp.write(open(config_file, 'w'))
    print('Saving oauth tokens in {} for later re-use'.format(config_file))
    print()

    access_token = oauth.Token(oauth_token, oauth_token_secret)
    oauth_client = oauth.Client(consumer, access_token)
    return oauth_client 
Example #22
Source File: tests.py    From coursys with GNU General Public License v3.0 4 votes vote down vote up
def test_oauth_workflow(self):
        request_token_url = 'http://testserver' + reverse('api:oauth_request_token')
        authorize_token_url = 'http://testserver' + reverse('api:oauth_user_authorization')

        # create consumer for tests
        c = Client()
        c.login_user('ggbaker')
        c.logout()
        consumer = Consumer(name='Test Consumer', description='Consumer to do some tests with', status=ACCEPTED,
                     user=User.objects.get(username='ggbaker'), xauth_allowed=False)
        consumer.generate_random_codes()
        consumer.save()
        ci = ConsumerInfo(consumer=consumer)
        ci.admin_contact = 'the_developer@example.com'
        ci.permissions = ['courses', 'grades']
        ci.save()

        # generate request token
        oauth_request = oauth.Request.from_consumer_and_token(consumer, http_url=request_token_url,
                                                              parameters={'oauth_callback': 'oob'})
        oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None)

        resp = c.get(request_token_url, **oauth_request.to_header())
        self.assertEqual(resp.status_code, 200)
        request_token = dict(urllib.parse.parse_qsl(resp.content.decode('utf8')))

        # get auth verifier
        c.login_user('ggbaker')
        resp = c.get(authorize_token_url, {'oauth_token': request_token['oauth_token']})
        self.assertEqual(resp.status_code, 200)
        resp = c.post(authorize_token_url, {'oauth_token': request_token['oauth_token'], 'authorize_access': 'on'})
        self.assertEqual(resp.status_code, 200)
        parser = etree.HTMLParser()
        root = etree.fromstring(resp.content, parser=parser)
        verifier_elt = root.xpath('//*[@id="verifier"]')[0]
        oauth_verifier = verifier_elt.text.strip()
        c.logout()

        # get access token
        token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
        token.set_verifier(oauth_verifier)
        oauth_request = oauth.Request.from_consumer_and_token(consumer, token, http_url=authorize_token_url)
        oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token)

        resp = c.get(authorize_token_url, **oauth_request.to_header())
        # TODO: this is failing for some reason, but succeeds in the demo scripts
        #self.assertEqual(resp.status_code, 200)
        #access_token = dict(urllib.parse.parse_qsl(response.content.decode('utf8'))) 
Example #23
Source File: tests.py    From coursys with GNU General Public License v3.0 4 votes vote down vote up
def setUp(self):
        self.faketime = 525942870
        self.client = Client()

        # create a Consumer (and associated stuff)
        try:
            u = User.objects.get(username='ggbaker')
        except User.DoesNotExist:
            u = User(username='ggbaker')
            u.save()

        try:
            c = Consumer.objects.get(name='Test Consumer')
        except Consumer.DoesNotExist:
            c = Consumer(name='Test Consumer')

        c.description = 'Consumer to do some tests with'
        c.status = ACCEPTED
        c.user = u
        c.xauth_allowed = False
        c.generate_random_codes()
        c.save()
        self.consumer = c

        i = ConsumerInfo(consumer=c)
        i.admin_contact = 'the_developer@example.com'
        i.permissions = ['courses']
        i.timestamp = self.faketime - 10 # make sure the ConsumerInfo was there "before" the Token was created
        i.save()
        self.consumerinfo = i

        # create an access token so we can jump in to requests
        try:
            t = Token.objects.get(token_type=Token.ACCESS, consumer=c, user=u)
        except Token.DoesNotExist:
            t = Token(token_type=Token.ACCESS, consumer=c, user=u, timestamp=self.faketime)
       
        t.is_approved = True
        t.generate_random_codes()
        t.verifier = VERIFIER
        t.save()
        self.token = t