Python oauth2.Consumer() Examples

The following are 30 code examples of oauth2.Consumer(). 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: common.py    From pylti with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def lookup_consumer(self, key):
        """
        Search through keys
        """
        if not self.consumers:
            log.critical(("No consumers defined in settings."
                          "Have you created a configuration file?"))
            return None

        consumer = self.consumers.get(key)
        if not consumer:
            log.info("Did not find consumer, using key: %s ", key)
            return None

        secret = consumer.get('secret', None)
        if not secret:
            log.critical(('Consumer %s, is missing secret'
                          'in settings file, and needs correction.'), key)
            return None
        return oauth2.Consumer(key, secret) 
Example #2
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 #3
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 #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: outcome_request.py    From ontask_b with MIT License 6 votes vote down vote up
def post_outcome_request(self):
        """
        POST an OAuth signed request to the Tool Consumer.
        """
        if not self.has_required_attributes():
            raise InvalidLTIConfigError(
                'OutcomeRequest does not have all required attributes')

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

        client = oauth2.Client(consumer)

        response, content = client.request(
            self.lis_outcome_service_url,
            'POST',
            body=self.generate_request_xml(),
            headers={'Content-Type': 'application/xml'})

        self.outcome_response = OutcomeResponse.from_post_response(response,
                                                                   content)
        return self.outcome_response 
Example #6
Source File: twitter_auth.py    From Python-Programming-Blueprints with MIT License 6 votes vote down vote up
def get_oauth_token(config):

    global consumer
    global client
    global req_token

    consumer = oauth.Consumer(config.consumer_key, config.consumer_secret)
    client = oauth.Client(consumer)

    resp, content = client.request(config.request_token_url, 'GET')

    if resp['status'] != '200':
        raise Exception("Invalid response {}".format(resp['status']))

    request_token = dict(parse_qsl(content.decode('utf-8')))

    req_token = RequestToken(**request_token) 
Example #7
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 #8
Source File: outcome_request.py    From ontask_b with MIT License 5 votes vote down vote up
def post_replace_result(self, score):
        """
        POSTs the given score to the Tool Consumer with a replaceResult.
        """
        self.operation = REPLACE_REQUEST
        self.score = score
        return self.post_outcome_request() 
Example #9
Source File: outcome_request.py    From ontask_b with MIT License 5 votes vote down vote up
def post_delete_result(self):
        """
        POSTs a deleteRequest to the Tool Consumer.
        """
        self.operation = DELETE_REQUEST
        return self.post_outcome_request() 
Example #10
Source File: outcome_request.py    From ontask_b with MIT License 5 votes vote down vote up
def post_read_result(self):
        """
        POSTS a readResult to the Tool Consumer.
        """
        self.operation = READ_REQUEST
        return self.post_outcome_request() 
Example #11
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 #12
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 #13
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 #14
Source File: oauth7digital.py    From MusicGenreClassification with MIT License 5 votes vote down vote up
def _consumer():
    return oauth.Consumer(api_settings.oauthkey, api_settings.secret) 
Example #15
Source File: oauth7digital.py    From MusicGenreClassification with MIT License 5 votes vote down vote up
def _consumer():
    return oauth.Consumer(api_settings.oauthkey, api_settings.secret) 
Example #16
Source File: oauth.py    From allura with Apache License 2.0 5 votes vote down vote up
def consumer(self):
        '''OAuth compatible consumer object'''
        return oauth.Consumer(self.api_key, self.secret_key) 
Example #17
Source File: oauth10a_account.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, g, client_id, client_secret, auth_url, token_url, access_token_url, socket_timeout=60):
        self.globals = g
        self.client_id = client_id
        self.client_secret = client_secret
        self.code = None
        self.request = current.request
        self.session = current.session
        self.auth_url = auth_url
        self.token_url = token_url
        self.access_token_url = access_token_url
        self.socket_timeout = socket_timeout

        # consumer init
        self.consumer = oauth.Consumer(self.client_id, self.client_secret) 
Example #18
Source File: common.py    From pylti with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def key(self):  # pylint: disable=no-self-use
        """
        OAuth Consumer Key
        :return: key
        """
        return self.session['oauth_consumer_key'] 
Example #19
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 #20
Source File: oauth.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def step1_get_authorize_url(self, oauth_callback='oob'):
    """Returns a URI to redirect to the provider.

    oauth_callback - Either the string 'oob' for a non-web-based application,
                     or a URI that handles the callback from the authorization
                     server.

    If oauth_callback is 'oob' then pass in the
    generated verification code to step2_exchange,
    otherwise pass in the query parameters received
    at the callback uri to step2_exchange.
    """
    consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
    client = oauth.Client(consumer)

    headers = {
        'user-agent': self.user_agent,
        'content-type': 'application/x-www-form-urlencoded'
    }
    body = urllib.urlencode({'oauth_callback': oauth_callback})
    uri = _oauth_uri('request', self.discovery, self.params)

    resp, content = client.request(uri, 'POST', headers=headers,
                                   body=body)
    if resp['status'] != '200':
      logging.error('Failed to retrieve temporary authorization: %s', content)
      raise RequestError('Invalid response %s.' % resp['status'])

    self.request_token = dict(parse_qsl(content))

    auth_params = copy.copy(self.params)
    auth_params['oauth_token'] = self.request_token['oauth_token']

    return _oauth_uri('authorize', self.discovery, auth_params) 
Example #21
Source File: oauth.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def __init__(self, consumer_key, consumer_secret, user_agent):
    """
    Args:
      consumer_key: string, An OAuth 1.0 consumer key
      consumer_secret: string, An OAuth 1.0 consumer secret
      user_agent: string, The HTTP User-Agent to provide for this application.
    """
    self.consumer = oauth.Consumer(consumer_key, consumer_secret)
    self.user_agent = user_agent
    self.store = None

    # email address of the user to act on the behalf of.
    self._requestor = None 
Example #22
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 #23
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 #24
Source File: oauth_providers.py    From kansha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, key, secret, scopes=(), timeout=None):
        self.consumer = oauth.Consumer(key, secret)
        self.timeout = timeout
        self.scopes = scopes
        self.token = None 
Example #25
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 #26
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 #27
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 #28
Source File: demo2_get_request_token.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def get_request_token(with_callback=True):
    consumer = oauth.Consumer(key='9fdce0e111a1489eb5a42eab7a84306b', secret='liqutXmqJpKmetfs')
    if with_callback:
        callback = CALLBACK_URL
    else:
        callback = 'oob'
    oauth_request = oauth.Request.from_consumer_and_token(consumer, http_url=REQUEST_TOKEN_URL, parameters={'oauth_callback': callback})
    oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None)

    response = requests.get(REQUEST_TOKEN_URL, headers=oauth_request.to_header())
    request_token = dict(urllib.parse.parse_qsl(response.content.decode('utf8')))
    return request_token 
Example #29
Source File: instapaper.py    From pyinstapaper with MIT License 5 votes vote down vote up
def __init__(self, oauth_key, oauth_secret):
        self.consumer = oauth.Consumer(oauth_key, oauth_secret)
        self.oauth_client = oauth.Client(self.consumer)
        self.token = None 
Example #30
Source File: common.py    From pylti with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def _post_patched_request(consumers, lti_key, body,
                          url, method, content_type):
    """
    Authorization header needs to be capitalized for some LTI clients
    this function ensures that header is capitalized

    :param body: body of the call
    :param client: OAuth Client
    :param url: outcome url
    :return: response
    """
    # pylint: disable=too-many-locals, too-many-arguments
    oauth_server = LTIOAuthServer(consumers)
    oauth_server.add_signature_method(SignatureMethod_HMAC_SHA1_Unicode())
    lti_consumer = oauth_server.lookup_consumer(lti_key)
    lti_cert = oauth_server.lookup_cert(lti_key)
    secret = lti_consumer.secret

    consumer = oauth2.Consumer(key=lti_key, secret=secret)
    client = oauth2.Client(consumer)

    if lti_cert:
        client.add_certificate(key=lti_cert, cert=lti_cert, domain='')
        log.debug("cert %s", lti_cert)

    import httplib2

    http = httplib2.Http
    # pylint: disable=protected-access
    normalize = http._normalize_headers

    def my_normalize(self, headers):
        """ This function patches Authorization header """
        ret = normalize(self, headers)
        if 'authorization' in ret:
            ret['Authorization'] = ret.pop('authorization')
        log.debug("headers")
        log.debug(headers)
        return ret

    http._normalize_headers = my_normalize
    monkey_patch_function = normalize
    response, content = client.request(
        url,
        method,
        body=body.encode('utf-8'),
        headers={'Content-Type': content_type})

    http = httplib2.Http
    # pylint: disable=protected-access
    http._normalize_headers = monkey_patch_function

    log.debug("key %s", lti_key)
    log.debug("secret %s", secret)
    log.debug("url %s", url)
    log.debug("response %s", response)
    log.debug("content %s", format(content))

    return response, content