Exemple #1
0
    def test_create_access_token_expires_at(self):
        verifier = uuid.uuid4().hex
        consumer_key = uuid.uuid4().hex
        consumer_secret = uuid.uuid4().hex
        request_key = uuid.uuid4().hex
        request_secret = uuid.uuid4().hex

        t = self._new_oauth_token_with_expires_at()
        access_key, access_secret, expires_at, resp_ref = t

        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        self.stub_url('POST', [self.path_prefix, 'access_token'],
                      status_code=201,
                      text=resp_ref,
                      headers=headers)

        # Assert that the manager creates an access token object
        access_token = self.manager.create(consumer_key, consumer_secret,
                                           request_key, request_secret,
                                           verifier)
        self.assertIsInstance(access_token, self.model)
        self.assertEqual(access_key, access_token.key)
        self.assertEqual(access_secret, access_token.secret)
        self.assertEqual(expires_at, access_token.expires)

        req_headers = self.requests_mock.last_request.headers
        oauth_client = oauth1.Client(consumer_key,
                                     client_secret=consumer_secret,
                                     resource_owner_key=request_key,
                                     resource_owner_secret=request_secret,
                                     signature_method=oauth1.SIGNATURE_HMAC,
                                     verifier=verifier)

        self._validate_oauth_headers(req_headers['Authorization'],
                                     oauth_client)
Exemple #2
0
async def fetch_from_twitter(
    credentials,
    path,
    params: List[Tuple[str, str]],
    since_id: Optional[int],
    per_page: int,
    n_pages: int,
) -> List[Dict[str, Any]]:
    oauth_client = oauth1.Client(
        client_key=credentials["consumer_key"],
        client_secret=credentials["consumer_secret"],
        resource_owner_key=credentials["resource_owner_key"],
        resource_owner_secret=credentials["resource_owner_secret"],
    )

    page_dataframes = [create_empty_table()]

    max_id = None
    async with aiohttp.ClientSession() as session:  # aiohttp timeout of 5min
        for page in range(n_pages):
            # Assume {path} contains '?' already
            page_params = [
                *params,
                ("tweet_mode", "extended"),
                ("count", str(per_page)),
            ]
            if since_id:
                page_params.append(("since_id", str(since_id)))
            if max_id:
                page_params.append(("max_id", str(max_id)))

            page_url = f"https://api.twitter.com/1.1/{path}?{urlencode(page_params)}"

            page_url, headers, body = oauth_client.sign(
                page_url, headers={"Accept": "application/json"})

            # aiohttp internally performs URL canonization before sending
            # request. DISABLE THIS: it rewrites the signed URL!
            #
            # https://github.com/aio-libs/aiohttp/issues/3424
            page_url = yarl.URL(page_url, encoded=True)  # disable magic

            response = await session.get(page_url, headers=headers)
            response.raise_for_status()
            page_statuses = await response.json()

            if isinstance(page_statuses, dict) and "statuses" in page_statuses:
                # /search wraps result in {}
                page_statuses = page_statuses["statuses"]

            if not page_statuses:
                break

            # Parse one page at a time, instead of parsing all at the end.
            # Should save a bit of memory and make a smaller CPU-blip in our
            # event loop.
            page_dataframes.append(statuses_to_dataframe(page_statuses))
            max_id = page_statuses[-1]["id"] - 1

    return pd.concat(page_dataframes, ignore_index=True, sort=False)
    def test_create_request_token(self):
        project_id = uuid.uuid4().hex
        consumer_key = uuid.uuid4().hex
        consumer_secret = uuid.uuid4().hex

        request_key, request_secret, resp_ref = self._new_oauth_token()

        # NOTE(stevemar) The server expects the body to be JSON. Even though
        # the resp_ref is a string it is not a JSON string.
        self.stub_url(httpretty.POST, [self.path_prefix, 'request_token'],
                      status=201,
                      body=jsonutils.dumps(resp_ref),
                      content_type='application/x-www-form-urlencoded')

        # Assert the manager is returning request token object
        request_token = self.manager.create(consumer_key, consumer_secret,
                                            project_id)
        self.assertIsInstance(request_token, self.model)
        self.assertEqual(request_key, request_token.key)
        self.assertEqual(request_secret, request_token.secret)

        # Assert that the project id is in the header
        self.assertRequestHeaderEqual('requested_project_id', project_id)
        req_headers = httpretty.last_request().headers

        oauth_client = oauth1.Client(consumer_key,
                                     client_secret=consumer_secret,
                                     signature_method=oauth1.SIGNATURE_HMAC,
                                     callback_uri="oob")
        self._validate_oauth_headers(req_headers['Authorization'],
                                     oauth_client)
Exemple #4
0
def sign_parameters(passport, lti_parameters, url):
    """

    Args:
        passport: The LTIPassport to use to sign the oauth request
        lti_parameters: A dictionnary of parameters to sign
        url: The LTI launch URL

    Returns:
        dict: The signed parameters
    """

    signed_parameters = lti_parameters.copy()
    oauth_client = oauth1.Client(client_key=passport.oauth_consumer_key,
                                 client_secret=passport.shared_secret)
    # Compute Authorization header which looks like:
    # Authorization: OAuth oauth_nonce="80966668944732164491378916897",
    # oauth_timestamp="1378916897", oauth_version="1.0", oauth_signature_method="HMAC-SHA1",
    # oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"
    _uri, headers, _body = oauth_client.sign(
        url,
        http_method="POST",
        body=lti_parameters,
        headers={"Content-Type": CONTENT_TYPE},
    )

    # Parse headers to pass to template as part of context:
    oauth_dict = dict(param.strip().replace('"', "").split("=")
                      for param in headers["Authorization"].split(","))

    signature = oauth_dict["oauth_signature"]
    oauth_dict["oauth_signature"] = unquote(signature)
    oauth_dict["oauth_nonce"] = oauth_dict.pop("OAuth oauth_nonce")
    signed_parameters.update(oauth_dict)
    return signed_parameters
Exemple #5
0
def log_authorization_header(request, client_key, client_secret):
    """
    Helper function that logs proper HTTP Authorization header for a given request

    Used only in debug situations, this logs the correct Authorization header based on
    the request header and body according to OAuth 1 Body signing

    Arguments:
        request (xblock.django.request.DjangoWebobRequest):  Request object to log Authorization header for

    Returns:
        nothing
    """
    sha1 = hashlib.sha1()
    sha1.update(request.body)
    oauth_body_hash = unicode(base64.b64encode(sha1.digest()))  # pylint: disable=too-many-function-args
    log.debug("[LTI] oauth_body_hash = %s", oauth_body_hash)
    client = oauth1.Client(client_key, client_secret)
    params = client.get_oauth_params(request)
    params.append((u'oauth_body_hash', oauth_body_hash))
    mock_request = SignedRequest(
        uri=unicode(urllib.unquote(request.url)),
        headers=request.headers,
        body=u"",
        decoded_body=u"",
        oauth_params=params,
        http_method=unicode(request.method),
    )
    sig = client.get_oauth_signature(mock_request)
    mock_request.oauth_params.append((u'oauth_signature', sig))

    __, headers, _ = client._render(mock_request)  # pylint: disable=protected-access
    log.debug(
        "\n\n#### COPY AND PASTE AUTHORIZATION HEADER ####\n%s\n####################################\n\n",
        headers['Authorization'])
Exemple #6
0
def get_oauth_request_signature(key, secret, url, headers, body):
    """
    Returns Authorization header for a signed oauth request.

    Arguments:
        key (str): LTI provider key
        secret (str): LTI provider secret
        url (str): URL for the signed request
        header (str): HTTP headers for the signed request
        body (str): Body of the signed request

    Returns:
        str: Authorization header for the OAuth signed request
    """
    client = oauth1.Client(client_key=unicode(key),
                           client_secret=unicode(secret))
    try:
        # Add Authorization header which looks like:
        # Authorization: OAuth oauth_nonce="80966668944732164491378916897",
        # oauth_timestamp="1378916897", oauth_version="1.0", oauth_signature_method="HMAC-SHA1",
        # oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"
        __, headers, __ = client.sign(unicode(url.strip()),
                                      http_method=u'POST',
                                      body=body,
                                      headers=headers)
    except ValueError:  # Scheme not in url.
        raise LtiError("Failed to sign oauth request")

    return headers['Authorization']
Exemple #7
0
def oauth_headers(url,
                  consumer_key,
                  token_key,
                  token_secret,
                  consumer_secret,
                  timestamp=None):
    try:
        import oauthlib.oauth1 as oauth1
    except ImportError as e:
        raise NotImplementedError("oauth support is not available") from e

    if timestamp:
        timestamp = str(timestamp)
    else:
        timestamp = None

    client = oauth1.Client(
        consumer_key,
        client_secret=consumer_secret,
        resource_owner_key=token_key,
        resource_owner_secret=token_secret,
        signature_method=oauth1.SIGNATURE_PLAINTEXT,
        timestamp=timestamp,
    )
    _uri, signed_headers, _body = client.sign(url)
    return signed_headers
Exemple #8
0
 def _get_oauth_token(self, consumer, token):
     client = oauth1.Client(consumer['key'],
                            client_secret=consumer['secret'],
                            resource_owner_key=token.key,
                            resource_owner_secret=token.secret,
                            signature_method=oauth1.SIGNATURE_HMAC)
     endpoint = 'http://10.239.48.152:35357/v3/auth/tokens'
     url, headers, body = client.sign(endpoint, http_method='POST')
     # This will cause the headers for 't' is upper case, which will not pass
     # (Pdb) p request.headers, so it will defaults to be 'application/x-www-form-urlencoded'?
     # (Pdb) p request.content_type
     # 'application/x-www-form-urlencoded'
     # change the key to be 'Content_type' will fix
     # the issue.
     #headers.update({'Content-Type': 'application/json'})
     ref = {'auth': {'identity': {'oauth1': {}, 'methods': ['oauth1']}}}
     data = json.dumps(ref)
     request = urllib2.Request(endpoint, data)
     request.headers = headers
     # This will cause the headers for 't' is lower case
     # (Pdb) p request.headers
     # {'Content-type': 'application/json'...
     # add header will call capitalize('key') so that it will convert the key to 'Content-type' but
     # the method mentioned above will not, so the header will ignored by the urllib2.
     request.add_header('Content-Type', 'application/json')
     request.get_method = lambda: 'POST'
     response = urllib2.urlopen(request)
     return response
    def send(self, data, config=None, session_state=None):
        headers = {}
        if self.oauth_creds:
            client = oauth1.Client(
                client_key=self.oauth_creds['consumer_key'],
                client_secret=self.oauth_creds['consumer_secret'],
                resource_owner_key=self.oauth_creds['token_key'],
                resource_owner_secret=self.oauth_creds['token_secret'],
                signature_method=oauth1.SIGNATURE_HMAC,
                realm='Checkbox',
            )
            # The uri is unchanged from self.url, it's the headers we're
            # interested in.
            uri, headers, body = client.sign(self.url, 'POST')
        form_payload = dict(data=data)
        form_data = dict(uploader_email=self.uploader_email)
        try:
            response = requests.post(self.url,
                                     files=form_payload,
                                     data=form_data,
                                     headers=headers)
        except requests.exceptions.Timeout as exc:
            raise TransportError('Request to timed out: {}'.format(exc))
        except requests.exceptions.InvalidSchema as exc:
            raise TransportError('Invalid destination URL: {0}'.format(exc))
        except requests.exceptions.ConnectionError as exc:
            raise TransportError('Unable to connect: {0}'.format(exc))
        if response is not None:
            try:
                # This will raise HTTPError for status != 20x
                response.raise_for_status()
            except requests.exceptions.RequestException as exc:
                raise TransportError(str(exc))

        return dict(message='Upload successful.', status=response.status_code)
Exemple #10
0
 def sign(self, method, url):
     if not self.access:
         return url, {}, ''
     cl = oauth1.Client(self.access.key,
                        client_secret=self.access.secret,
                        signature_method=self.signature_method)
     return cl.sign(url, http_method=method)
Exemple #11
0
    def run(self, path=None):
        path = self.kwargs.get('path', path)
        if not path and self.request.method == 'GET':
            yield self.login()
            raise tornado.gen.Return()

        args = {key: val[0] for key, val in self.args.items()}
        params = AttrDict(self.kwargs)
        params['access_key'] = self.get_token('access_key',
                                              self.get_from_token)
        params['access_secret'] = self.get_token('access_secret',
                                                 self.get_from_token)

        client = oauth1.Client(client_key=params['key'],
                               client_secret=params['secret'],
                               resource_owner_key=params['access_key'],
                               resource_owner_secret=params['access_secret'])
        endpoint = params.get('endpoint', 'https://api.twitter.com/1.1/')
        path = params.get('path', path)
        uri, headers, body = client.sign(url_concat(endpoint + path, args))
        http = self.get_auth_http_client()
        response = yield http.fetch(uri, headers=headers, raise_error=False)
        result = yield self.social_response(response)
        self.set_header('Content-Type', 'application/json; charset=UTF-8')
        self.write(result)
Exemple #12
0
    def test_create_request_token(self):
        project_id = uuid.uuid4().hex
        consumer_key = uuid.uuid4().hex
        consumer_secret = uuid.uuid4().hex

        request_key, request_secret, resp_ref = self._new_oauth_token()

        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        self.stub_url('POST', [self.path_prefix, 'request_token'],
                      status_code=201,
                      text=resp_ref,
                      headers=headers)

        # Assert the manager is returning request token object
        request_token = self.manager.create(consumer_key, consumer_secret,
                                            project_id)
        self.assertIsInstance(request_token, self.model)
        self.assertEqual(request_key, request_token.key)
        self.assertEqual(request_secret, request_token.secret)

        # Assert that the project id is in the header
        self.assertRequestHeaderEqual('requested-project-id', project_id)
        req_headers = self.requests_mock.last_request.headers

        oauth_client = oauth1.Client(consumer_key,
                                     client_secret=consumer_secret,
                                     signature_method=oauth1.SIGNATURE_HMAC,
                                     callback_uri="oob")
        self._validate_oauth_headers(req_headers['Authorization'],
                                     oauth_client)
Exemple #13
0
 def pay(self, request, pk=None, provider=None):
     """
         Task Payment Provider Endpoint
         ---
         omit_serializer: true
         omit_parameters:
             - query
         """
     task = self.get_object()
     callback = '%s://%s/task/%s/rate/' % (request.scheme, request.get_host(), pk)
     next_url = callback
     if task and task.has_object_write_permission(request) and bitcoin_utils.is_valid_btc_address(task.btc_address):
         if provider == TASK_PAYMENT_METHOD_BITONIC:
             client = oauth1.Client(
                 BITONIC_CONSUMER_KEY, BITONIC_CONSUMER_SECRET, BITONIC_ACCESS_TOKEN, BITONIC_TOKEN_SECRET,
                 callback_uri=callback, signature_type=SIGNATURE_TYPE_QUERY
             )
             amount = task.pay
             increase_factor = 1 + (Decimal(BITONIC_PAYMENT_COST_PERCENTAGE)*Decimal(0.01))
             q_string = urlencode({
                 'ext_data': task.summary.encode('utf-8'),
                 'bitcoinaddress': task.btc_address,
                 'ordertype': 'buy',
                 'euros': amount * increase_factor
             })
             req_data = client.sign('%s/?%s' % (BITONIC_URL, q_string), http_method='GET')
             next_url = req_data[0]
     return redirect(next_url)
Exemple #14
0
    def _make_request(self, method, uri, body_parameters=None):
        headers = {}
        body = None
        if body_parameters is not None:
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
            body = urlencode(body_parameters)
        client = oauth1.Client(self._consumer_key,
                               client_secret=self._consumer_secret,
                               resource_owner_key=self._token_key,
                               resource_owner_secret=self._token_secret,
                               encoding='utf-8',
                               decoding='utf-8')
        uri, headers, body = client.sign(uri,
                                         http_method=method,
                                         headers=headers,
                                         body=body)
        headers = Headers(dict((k, [v]) for k, v in headers.items()))

        body_producer = None
        if body is not None:
            body_producer = FileBodyProducer(StringIO(body))

        d = self._agent.request(method, uri, headers, body_producer)
        return d.addCallback(self._handle_error)
Exemple #15
0
def generate_passport_and_signed_lti_parameters(url,
                                                lti_parameters,
                                                passport_attributes=None):
    """Generate signed LTI parameters."""
    url = urlparse(url)
    if passport_attributes is None:
        passport_attributes = {}
    passport = ConsumerSiteLTIPassportFactory(
        consumer_site__domain=url.hostname, **passport_attributes)
    client = oauth1.Client(client_key=passport.oauth_consumer_key,
                           client_secret=passport.shared_secret)
    # Compute Authorization header which looks like:
    # Authorization: OAuth oauth_nonce="80966668944732164491378916897",
    # oauth_timestamp="1378916897", oauth_version="1.0", oauth_signature_method="HMAC-SHA1",
    # oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"
    _uri, headers, _body = client.sign(
        url.geturl(),
        http_method="POST",
        body=lti_parameters,
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )

    oauth_dict = dict(param.strip().replace('"', "").split("=")
                      for param in headers["Authorization"].split(","))

    signature = oauth_dict["oauth_signature"]
    oauth_dict["oauth_signature"] = unquote(signature)
    oauth_dict["oauth_nonce"] = oauth_dict.pop("OAuth oauth_nonce")

    lti_parameters.update(oauth_dict)
    return lti_parameters, passport
Exemple #16
0
def generate_signed_request(partner_id, hotel_id, private_key, connect_url,
                            method):
    # At this moment we don't accept multiple query sting parameters,
    # so a dict can be used.
    params = {
        'partner_id':
        partner_id,  # partner_id must be identical to oauth_consumer_key
        'oauth_token': hotel_id,

        # These 4 mandatory parameters are generated by the oauth1.Client during the signing
        # process already, so they will be automatically added.
        # They are only left here, as an example, if using another library instead of oauthlib.
        # 'oauth_consumer_key': partner_id,
        # 'oauth_timestamp': int(time.time()),
        # 'oauth_nonce': ''.join(random.choice(string.letters) for _ in range(15)),
        # 'oauth_signature_method': 'RSA-SHA1',
    }

    client = oauth1.Client(
        client_key=
        partner_id,  # this will be the value of 'oauth_consumer_key' in the signed url
        signature_method=oauth1.SIGNATURE_RSA,
        rsa_key=private_key,
        signature_type=oauth1.SIGNATURE_TYPE_QUERY)

    unsigned_url = connect_url + '?' + urlencode(params)

    url, headers, body = client.sign(unsigned_url, http_method=method)

    return url
Exemple #17
0
async def fetch_from_twitter(access_token, path, params: List[Tuple[str, str]],
                             since_id: Optional[int], per_page: int,
                             n_pages: int) -> List[Dict[str, Any]]:
    service = oauth.OAuthService.lookup_or_none('twitter')
    if not service:
        raise Exception('Twitter connection misconfigured')

    oauth_client = oauth1.Client(
        client_key=service.consumer_key,
        client_secret=service.consumer_secret,
        resource_owner_key=access_token['oauth_token'],
        resource_owner_secret=access_token['oauth_token_secret'])

    page_dataframes = [create_empty_table()]

    max_id = None
    async with aiohttp.ClientSession() as session:  # aiohttp timeout of 5min
        for page in range(n_pages):
            # Assume {path} contains '?' already
            page_params = [
                *params,
                ('tweet_mode', 'extended'),
                ('count', str(per_page)),
            ]
            if since_id:
                page_params.append(('since_id', str(since_id)))
            if max_id:
                page_params.append(('max_id', str(max_id)))

            page_url = (
                f'https://api.twitter.com/1.1/{path}?{urlencode(page_params)}')

            page_url, headers, body = oauth_client.sign(
                page_url, headers={'Accept': 'application/json'})

            # aiohttp internally performs URL canonization before sending
            # request. DISABLE THIS: it rewrites the signed URL!
            #
            # https://github.com/aio-libs/aiohttp/issues/3424
            page_url = yarl.URL(page_url, encoded=True)  # disable magic

            response = await session.get(page_url, headers=headers)
            response.raise_for_status()
            page_statuses = await response.json()

            if isinstance(page_statuses, dict) and 'statuses' in page_statuses:
                # /search wraps result in {}
                page_statuses = page_statuses['statuses']

            if not page_statuses:
                break

            # Parse one page at a time, instead of parsing all at the end.
            # Should save a bit of memory and make a smaller CPU-blip in our
            # event loop.
            page_dataframes.append(statuses_to_dataframe(page_statuses))
            max_id = page_statuses[-1]['id'] - 1

    return pd.concat(page_dataframes, ignore_index=True, sort=False)
Exemple #18
0
    def __init__(self, apikey):
        self.consumer_key, self.token_key, self.token_secret = apikey.split(':')
        self.consumer_secret = ""
        self.realm = "OAuth"

        self.oauth_client = oauth1.Client(self.consumer_key, self.consumer_secret,
            self.token_key, self.token_secret, signature_method=oauth1.SIGNATURE_PLAINTEXT,
            realm=self.realm)
Exemple #19
0
 def regen(self):
     client = oauth1.Client(
         self.consumer_key,
         client_secret=self.consumer_secret,
         resource_owner_key=self.resource_owner_key,
         resource_owner_secret=self.resource_owner_secret,
         signature_method=sig)
     return client
Exemple #20
0
async def _fetch_paginated(
    endpoint: Literal["1.1/lists/statuses.json",
                      "1.1/statuses/user_timeline.json",
                      "1.1/search/tweets.json", ],
    params: Dict[str, Any],
    *,
    credentials: Dict[str, str],
) -> List[ResultPart]:
    """Fetch pages of results from Twitter API.

    Return empty list if there are no tweets.

    Return a single "API-ERROR.lz4" result if Twitter responds negatively
    to any request.

    Return a single "NETWORK-ERROR.json.lz4" result if we fail to receive a
    Twitter response to any request.

    Otherwise, return tweets ordered from newest to oldest.
    """
    oauth_client = oauth1.Client(
        client_key=credentials["consumer_key"],
        client_secret=credentials["consumer_secret"],
        resource_owner_key=credentials["resource_owner_key"],
        resource_owner_secret=credentials["resource_owner_secret"],
    )
    async with httpx.AsyncClient() as client:
        if endpoint == "1.1/search/tweets.json":
            return await _fetch_paginated_1_1(
                client,
                endpoint,
                params,
                oauth_client=oauth_client,
                tweets_per_request=100,
                max_n_requests=10,
            )
        elif endpoint == "1.1/statuses/user_timeline.json":
            return await _fetch_paginated_1_1(
                client,
                endpoint,
                params,
                oauth_client=oauth_client,
                tweets_per_request=200,
                max_n_requests=
                16,  # 3,200 tweets: [2020-11-26] Twitter's maximum
            )
        elif endpoint == "1.1/lists/statuses.json":
            return await _fetch_paginated_1_1(
                client,
                endpoint,
                params,
                oauth_client=oauth_client,
                tweets_per_request=200,
                max_n_requests=5,  # arbitrary => 1,000 tweets
            )
        else:
            raise NotImplementedError("Unknown endpoint '%s'" %
                                      endpoint)  # pragma: no cover
Exemple #21
0
def generate_oauth_header_2(url, conn_info):
    from oauthlib import oauth1

    client = oauth1.Client(
        conn_info.get_("here_client_key", ""),
        client_secret=conn_info.get_("here_client_secret", ""),
    )
    uri, headers, body = client.sign(url, "POST")
    return headers.get("Authorization", "").encode("utf-8")
def merchantLocApi(Lat, Lon, pageOffset, pageLength):
    response = ''
    # MASTERCARD PROD CLIENT KEY
    client_key = 'zwAwpIHtGsALRUt4xWUt44grXpu5Pn460JIz1zUX92b45ce3!644d5a70662b79354746773674725141557847354c413d3d'
    # PROD API ENDPOINT
    #url = "https://api.mastercard.com/merchants/v1/merchant"
    # Sandbox API ENDPOINT
    #url = "https://sandbox.api.mastercard.com/merchants/v1/merchant"
    url = "https://sandbox.api.mastercard.com/merchants/v1/country?Format=XML&Details=acceptance.paypass"

    # SET THE REQUEST PARAMETERS
    params = {
        'Format': "XML",
        'PageLength': pageLength,
        'PageOffset': pageOffset,
        'Country': "USA",
        'latitude': Lat,
        'longitude': Lon,
    }

    # PUT THE URL TOGETHER WITH THE PARAMS
    url_parts = list(urlparse.urlparse(url))
    query = dict(urlparse.parse_qsl(url_parts[4]))
    query.update(params)
    # ENCODE THE URL
    url_parts[4] = urllib.urlencode(query)

    # THIS IS THE FINAL URL W/PARAMS
    u = urlparse.urlunparse(url_parts)

    # BUILD THE REQUEST
    client = oauth1.Client(client_key,
                           signature_method=oauth1.SIGNATURE_RSA,
                           rsa_key=open('ss.key').read())

    # SIGN THE REQUEST
    uri, headers, body = client.sign(u)

    # PARSE THE AUTHORIZATION HEADER FOR USE BELOW
    for k, v in headers.iteritems():
        h = "%s" % (v)

    # BUILD THE REQUEST HANDLER & OPENER
    handler = urllib2.HTTPSHandler(debuglevel=debug)
    opener = urllib2.build_opener(handler)
    urllib2.install_opener(opener)

    # BUILD THE REQUEST
    request = urllib2.Request(u)
    # ADD THE AUTHORIZATION HEADER
    request.add_header('Authorization', h)
    # SEND THE REQUEST AND READ THE RESULT - ALSO CATCH ERRORS
    try:
        response = urllib2.urlopen(request).read()
    except urllib2.HTTPError, e:
        print('HTTPError = ' + str(e.code))
Exemple #23
0
    def test_lti_request_body(self):
        """Simulate an LTI launch request with oauth in the body.

        This test uses the oauthlib library to simulate an LTI launch request and make sure
        that our LTI verification works.
        """
        passport = ConsumerSiteLTIPassportFactory(
            consumer_site__domain="testserver")
        lti_parameters = {
            "resource_link_id": "df7",
            "context_id": "course-v1:ufr+mathematics+0001",
            "roles": "Instructor",
        }
        resource_id = uuid.uuid4()
        url = "http://testserver/lti/videos/{!s}".format(resource_id)
        client = oauth1.Client(client_key=passport.oauth_consumer_key,
                               client_secret=passport.shared_secret)
        # Compute Authorization header which looks like:
        # Authorization: OAuth oauth_nonce="80966668944732164491378916897",
        # oauth_timestamp="1378916897", oauth_version="1.0", oauth_signature_method="HMAC-SHA1",
        # oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"
        _uri, headers, _body = client.sign(
            url,
            http_method="POST",
            body=lti_parameters,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
        )

        # Parse headers to pass to template as part of context:
        oauth_dict = {
            k: v
            for k, v in [
                param.strip().replace('"', "").split("=")
                for param in headers["Authorization"].split(",")
            ]
        }
        signature = oauth_dict["oauth_signature"]
        oauth_dict["oauth_signature"] = unquote(signature)
        oauth_dict["oauth_nonce"] = oauth_dict.pop("OAuth oauth_nonce")

        lti_parameters.update(oauth_dict)
        request = self.factory.post(url,
                                    lti_parameters,
                                    HTTP_REFERER="https://testserver")
        lti = LTI(request, uuid.uuid4())
        self.assertTrue(lti.verify())
        self.assertEqual(lti.get_consumer_site(), passport.consumer_site)

        # If we alter the signature (e.g. add "a" to it), the verification should fail
        oauth_dict["oauth_signature"] = "{:s}a".format(signature)

        lti_parameters.update(oauth_dict)
        request = self.factory.post(url, lti_parameters)
        lti = LTI(request, resource_id)
        with self.assertRaises(LTIException):
            lti.verify()
Exemple #24
0
 def _get_oauth_headers(self, url):
     client = oauth1.Client(
         CONF.maas_oauth_consumer_key,
         client_secret=CONF.maas_oauth_consumer_secret,
         resource_owner_key=CONF.maas_oauth_token_key,
         resource_owner_secret=CONF.maas_oauth_token_secret,
         signature_method=oauth1.SIGNATURE_PLAINTEXT)
     realm = _Realm("")
     headers = client.sign(url, realm=realm)[1]
     return headers
Exemple #25
0
 def _get_oauth_request_header(self, url, method):
     """Get an oauth request header given the token and the url"""
     client = oauth1.Client(unicode(self.consumer_key),
                            client_secret=unicode(self.consumer_secret),
                            resource_owner_key=unicode(self.token),
                            resource_owner_secret=unicode(
                                self.token_secret))
     url, headers, body = client.sign(unicode(url),
                                      http_method=unicode(method))
     return [url, headers]
Exemple #26
0
 def sign(self, method, url):
     if not self.access:
         return url, {}, ''
     cl = oauth1.Client(self.access.key,
                        client_secret=self.access.secret,
                        signature_method=self.signature_method)
     url, headers, body = cl.sign(url, http_method=method)
     # We give cl.sign a str, but it gives us back a unicode, which cause
     # double-encoding problems later down the road with the django test
     # client. To fix that, ensure it's still an str after signing.
     return smart_str(url), headers, body
 def _get_oauth_headers(self, url):
     LOG.debug("Getting authorization headers for %s.", url)
     client = oauth1.Client(
         CONF.maas.oauth_consumer_key,
         client_secret=CONF.maas.oauth_consumer_secret,
         resource_owner_key=CONF.maas.oauth_token_key,
         resource_owner_secret=CONF.maas.oauth_token_secret,
         signature_method=oauth1.SIGNATURE_PLAINTEXT)
     realm = _Realm("")
     headers = client.sign(url, realm=realm)[1]
     return headers
Exemple #28
0
    def get_auth_data(self, session, auth, headers, **kwargs):
        # Add the oauth specific content into the headers
        oauth_client = oauth1.Client(self.consumer_key,
                                     client_secret=self.consumer_secret,
                                     resource_owner_key=self.access_key,
                                     resource_owner_secret=self.access_secret,
                                     signature_method=oauth1.SIGNATURE_HMAC)
        o_url, o_headers, o_body = oauth_client.sign(auth.token_url,
                                                     http_method='POST')

        headers.update(o_headers)
        return 'oauth1', {}
Exemple #29
0
 def __init__(self, *, client_key, client_secret, resource_owner_key,
              resource_owner_secret):
     self._oauth_client = (oauth.Client(
         client_key=client_key,
         client_secret=client_secret,
         resource_owner_key=resource_owner_key,
         resource_owner_secret=resource_owner_secret))
     self._connector = aiohttp.TCPConnector()
     self._queue = asyncio.Queue()
     self._log = logging.getLogger(TwitterClient.__name__)
     self._subscribe_queue = asyncio.Queue()
     self._home_timeline = {}
     self._timeline_cached = False
Exemple #30
0
 def __init__(self,
              user_agent,
              consumer_key,
              consumer_secret,
              token=None,
              secret=None,
              *args,
              **kwargs):
     super().__init__(user_agent, *args, **kwargs)
     self.client = oauth1.Client(consumer_key,
                                 client_secret=consumer_secret)
     if token and secret:
         self.set_token(token, secret)