Esempio n. 1
0
File: lti.py Progetto: ematan/a-plus
 def sign_post_parameters(self, url=None):
     client = Client(self.service.consumer_key,
                     client_secret=self.service.consumer_secret,
                     signature_method=SIGNATURE_HMAC,
                     signature_type=SIGNATURE_TYPE_BODY)
     uri, headers, body = client.sign(
         url or self.service.url,
         http_method="POST",
         body=self.parameters,
         headers={"Content-Type": "application/x-www-form-urlencoded"})
     return urldecode(body)
Esempio n. 2
0
 def sign_get_query(self, url=None):
     client = Client(self.service.consumer_key,
         client_secret=self.service.consumer_secret,
         signature_method=SIGNATURE_HMAC,
         signature_type=SIGNATURE_TYPE_QUERY)
     uri = update_url_params(self._get_url(url), self.parameters)
     try:
         query, headers, body = client.sign(uri, http_method="GET")
     except ValueError as e:
         raise ValueError("Invalid url %r for %r: %s" % (uri, self.service, e))
     return query
Esempio n. 3
0
 def getAuthorization(self, method, url, callback=None, verifier=None):
     client = Client(
         safe_unicode(self.consumer_key),
         safe_unicode(self.consumer_secret),
         safe_unicode(self.key),
         safe_unicode(self.secret),
         callback_uri=safe_unicode(callback),
         verifier=safe_unicode(verifier),
     )
     safe_method = safe_unicode(method)
     safe_url = safe_unicode(url)
     # data is omitted because no www-form-encoded data
     _, header, _ = client.sign(safe_url, safe_method)
     return header
Esempio n. 4
0
def xauth(base_url_template=DEFAULT_READER_URL_TEMPLATE, **xargs):
    """
    Returns an OAuth token tuple that can be used with clients.ReaderClient.

    :param base_url_template: Template for generating Readability API urls.
    :param consumer_key:  Readability consumer key, otherwise read from READABILITY_CONSUMER_KEY.
    :param consumer_secret: Readability consumer secret, otherwise read from READABILITY_CONSUMER_SECRET.
    :param username: A username, otherwise read from READABILITY_USERNAME.
    :param password: A password, otherwise read from READABILITY_PASSWORD.

    """
    consumer_key = xargs.get('consumer_key') or required_from_env(
        'READABILITY_CONSUMER_KEY')
    consumer_secret = xargs.get('consumer_secret') or required_from_env(
        'READABILITY_CONSUMER_SECRET')
    username = xargs.get('username') or required_from_env(
        'READABILITY_USERNAME')
    password = xargs.get('password') or required_from_env(
        'READABILITY_PASSWORD')

    client = Client(consumer_key,
                    client_secret=consumer_secret,
                    signature_type='BODY')
    url = base_url_template.format(ACCESS_TOKEN_URL)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    params = {
        'x_auth_username': username,
        'x_auth_password': password,
        'x_auth_mode': 'client_auth'
    }

    uri, headers, body = client.sign(url,
                                     http_method='POST',
                                     body=urlencode(params),
                                     headers=headers)

    response = requests.post(uri, data=body)
    logger.debug('POST to %s.', uri)

    token = parse_qs(response.content)
    try:
        # The indexes below are a little weird. parse_qs above gives us
        # back a dict where each value is a list. We want the first value
        # in those lists.
        token = (token[b'oauth_token'][0].decode(),
                 token[b'oauth_token_secret'][0].decode())
    except KeyError:
        raise ValueError('Invalid Credentials.')

    return token
Esempio n. 5
0
    def getAuthorization(self, request):
        client = Client(
            safe_unicode(self.client_key),
            safe_unicode(self.client_secret),
            safe_unicode(self.key),
            safe_unicode(self.secret),
            callback_uri=safe_unicode(self.callback),
            verifier=safe_unicode(self.verifier),
        )
        method = safe_unicode(request.get_method())
        url = safe_unicode(request.get_full_url())

        # data is omitted because no www-form-encoded data
        uri, headers, body = client.sign(url, method)
        return headers['Authorization']
Esempio n. 6
0
    def __init__(self, consumer_key: str, consumer_secret: str, resource_owner_key: Optional[str] = None,
                 resource_owner_secret: Optional[str] = None, callback_uri: Optional[str] = None,
                 oauth_verifier: Optional[str] = None, debug_mode: Optional[bool] = None):
        if debug_mode:
            self.session = aiohttp.ClientSession(trace_configs=[AIOTumblrDebugger(logger=log)])
        else:
            self.session = aiohttp.ClientSession()

        self.oauth_client = Client(
            client_key=consumer_key,
            client_secret=consumer_secret,
            resource_owner_key=resource_owner_key,
            resource_owner_secret=resource_owner_secret,
            callback_uri=callback_uri,
            verifier=oauth_verifier,
        )
Esempio n. 7
0
    def __init__(self, client_key,
            client_secret=None,
            resource_owner_key=None,
            resource_owner_secret=None,
            callback_uri=None,
            signature_method=SIGNATURE_HMAC,
            signature_type=SIGNATURE_TYPE_AUTH_HEADER,
            rsa_key=None, verifier=None,
            decoding='utf-8'):

        try:
            signature_type = signature_type.upper()
        except AttributeError:
            pass

        self.client = Client(client_key, client_secret, resource_owner_key,
            resource_owner_secret, callback_uri, signature_method,
            signature_type, rsa_key, verifier, decoding=decoding)
Esempio n. 8
0
def _sign_lti_message(body, key, secret, url):
    client = Client(client_key=key, client_secret=secret)

    __, headers, __ = client.sign(
        unicode(url),
        http_method=u'POST',
        body=body,
        headers={'Content-Type': 'application/x-www-form-urlencoded'})

    auth_header = headers['Authorization'][len('OAuth '):]
    auth = dict([
        param.strip().replace('"', '').split('=')
        for param in auth_header.split(',')
    ])

    body['oauth_nonce'] = auth['oauth_nonce']
    body['oauth_signature'] = auth['oauth_signature']
    body['oauth_timestamp'] = auth['oauth_timestamp']
    body['oauth_signature_method'] = auth['oauth_signature_method']
    body['oauth_version'] = auth['oauth_version']
Esempio n. 9
0
    def _sign_lti_message(self, body, key, secret, url):
        client = Client(client_key=key, client_secret=secret)

        __, headers, __ = client.sign(
            url,
            http_method=u"POST",
            body=body,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
        )

        auth_header = headers["Authorization"][len("OAuth "):]
        auth = dict([
            param.strip().replace('"', "").split("=")
            for param in auth_header.split(",")
        ])

        body["oauth_nonce"] = auth["oauth_nonce"]
        body["oauth_signature"] = auth["oauth_signature"]
        body["oauth_timestamp"] = auth["oauth_timestamp"]
        body["oauth_signature_method"] = auth["oauth_signature_method"]
        body["oauth_version"] = auth["oauth_version"]
Esempio n. 10
0
    def __init__(self,
                 callback_uri=None,
                 signature_method=SIGNATURE_HMAC,
                 signature_type=SIGNATURE_TYPE_AUTH_HEADER,
                 rsa_key=None,
                 verifier=None,
                 decoding='utf-8',
                 **kwargs):
        kwargs = DotDot(kwargs)
        if signature_type:
            signature_type = signature_type.upper()

        self.client = Client(kwargs.consumer_key,
                             kwargs.consumer_secret,
                             kwargs.access_token_key,
                             kwargs.access_token_secret,
                             callback_uri,
                             signature_method,
                             signature_type,
                             rsa_key,
                             verifier,
                             decoding=decoding)
Esempio n. 11
0
    def _get_oauth_headers(self, method, url, data=None, headers=None):
        """Basic wrapper around oauthlib that we use for Twitter and Flickr."""
        # "Client" == "Consumer" in oauthlib parlance.
        key = self._account.consumer_key
        secret = self._account.consumer_secret

        # "resource_owner" == secret and token.
        resource_owner_key = self._get_access_token()
        resource_owner_secret = self._account.secret_token
        oauth_client = Client(key, secret, resource_owner_key,
                              resource_owner_secret)

        headers = headers or {}
        if data is not None:
            headers['Content-Type'] = 'application/x-www-form-urlencoded'

        # All we care about is the headers, which will contain the
        # Authorization header necessary to satisfy OAuth.
        uri, headers, body = oauth_client.sign(url,
                                               body=data,
                                               headers=headers or {},
                                               http_method=method)

        return headers
Esempio n. 12
0
    def _log_correct_authorization_header(self, request):
        """
        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 = str(base64.b64encode(sha1.digest()))
        log.debug(f"[LTI] oauth_body_hash = {oauth_body_hash}")
        client_key, client_secret = self.get_client_key_secret()
        client = Client(client_key, client_secret)
        mock_request = mock.Mock(
            uri=str(parse.unquote(request.url)),
            headers=request.headers,
            body="",
            decoded_body="",
            http_method=str(request.method),
        )
        params = client.get_oauth_params(mock_request)
        mock_request.oauth_params = params
        mock_request.oauth_params.append(('oauth_body_hash', oauth_body_hash))
        sig = client.get_oauth_signature(mock_request)
        mock_request.oauth_params.append(('oauth_signature', sig))

        _, headers, _ = client._render(mock_request)  # pylint: disable=protected-access
        log.debug(
            "\n\n#### COPY AND PASTE AUTHORIZATION HEADER ####\n{}\n####################################\n\n"
            .format(headers['Authorization']))
Esempio n. 13
0
 def create_client(self, **kwargs):
     return Client(self.consumer_key,
                   signature_method=SIGNATURE_RSA,
                   rsa_key=self.rsa_key,
                   **kwargs)
Esempio n. 14
0
password = '******'
#-----------------------------------------

resource_owner_key = ''
resource_owner_secret = ''

if client_key == '' or client_secret == '':
    print "Please change your client key and secret in connectXAuth.py header"
    sys.exit(0)

if username == 'USER_NAME' or password == 'USER_PASSWORD':
    print "Please change username and password in connectXAuth.py header"
    sys.exit(0)

client = Client(client_key,
                client_secret=client_secret,
                signature_type=SIGNATURE_TYPE_BODY)
headers = {"Content-Type": CONTENT_TYPE_FORM_URLENCODED}
body = 'x_auth_mode=client_auth&x_auth_username='******'&x_auth_password='******'oauth_token')
resource_owner_secret = oauth_tokens.get('oauth_token_secret')
Esempio n. 15
0
 def __init__(self, client_key: str, client_secret: str):
     self.__key = client_key,
     self.__secret = client_secret
     self.__client = Client(client_id=self.__key)
     self._urls = facebook_urls