Example #1
0
 def test_parse_response_url(self):
     url = 'https://i.b/callback?oauth_token=foo&oauth_verifier=bar'
     auth = OAuth1Session('foo')
     resp = auth.parse_authorization_response(url)
     self.assertEqual(resp['oauth_token'], 'foo')
     self.assertEqual(resp['oauth_verifier'], 'bar')
     for k, v in resp.items():
         self.assertTrue(isinstance(k, unicode_type))
         self.assertTrue(isinstance(v, unicode_type))
Example #2
0
    def test_fetch_access_token(self):
        auth = OAuth1Session('foo', verifier='bar')
        auth.send = mock_text_response('oauth_token=foo')
        resp = auth.fetch_access_token('https://example.com/token')
        self.assertEqual(resp['oauth_token'], 'foo')
        for k, v in resp.items():
            self.assertTrue(isinstance(k, unicode_type))
            self.assertTrue(isinstance(v, unicode_type))

        auth = OAuth1Session('foo', verifier='bar')
        auth.send = mock_text_response('{"oauth_token":"foo"}')
        resp = auth.fetch_access_token('https://example.com/token')
        self.assertEqual(resp['oauth_token'], 'foo')

        auth = OAuth1Session('foo')
        auth.send = mock_text_response('oauth_token=foo')
        resp = auth.fetch_access_token('https://example.com/token',
                                       verifier='bar')
        self.assertEqual(resp['oauth_token'], 'foo')
Example #3
0
 def test_fetch_access_token_with_optional_arguments(self):
     auth = OAuth1Session('foo', verifier='bar')
     auth.send = mock_text_response('oauth_token=foo')
     resp = auth.fetch_access_token('https://example.com/token',
                                    verify=False,
                                    stream=True)
     self.assertEqual(resp['oauth_token'], 'foo')
     for k, v in resp.items():
         self.assertTrue(isinstance(k, unicode_type))
         self.assertTrue(isinstance(v, unicode_type))
Example #4
0
 def test_nonascii(self, generate_nonce, generate_timestamp):
     generate_nonce.return_value = 'abc'
     generate_timestamp.return_value = '123'
     signature = (
         'OAuth oauth_nonce="abc", oauth_timestamp="123", oauth_version="1.0", '
         'oauth_signature_method="HMAC-SHA1", oauth_consumer_key="foo", '
         'oauth_signature="W0haoue5IZAZoaJiYCtfqwMf8x8%3D"')
     auth = OAuth1Session('foo')
     auth.send = self.verify_signature(signature)
     auth.post('https://i.b?cjk=%E5%95%A6%E5%95%A6')
    def test_set_token(self):
        sess = OAuth1Session('foo')
        try:
            sess.token = {}
        except OAuthException as exc:
            self.assertEqual(exc.type, 'token_missing')

        sess.token = {'oauth_token': 'a', 'oauth_token_secret': 'b'}
        self.assertIsNone(sess.token['oauth_verifier'])
        sess.token = {'oauth_token': 'a', 'oauth_verifier': 'c'}
        self.assertEqual(sess.token['oauth_token_secret'], 'b')
        self.assertEqual(sess.token['oauth_verifier'], 'c')
Example #6
0
 def test_binary_upload(self, generate_nonce, generate_timestamp):
     generate_nonce.return_value = 'abc'
     generate_timestamp.return_value = '123'
     fake_xml = StringIO('hello world')
     headers = {'Content-Type': 'application/xml'}
     signature = (
         'OAuth oauth_nonce="abc", oauth_timestamp="123", oauth_version="1.0", '
         'oauth_signature_method="HMAC-SHA1", oauth_consumer_key="foo", '
         'oauth_signature="h2sRqLArjhlc5p3FTkuNogVHlKE%3D"')
     auth = OAuth1Session('foo')
     auth.send = self.verify_signature(signature)
     auth.post('https://i.b', headers=headers, files=[('fake', fake_xml)])
Example #7
0
    def test_fetch_request_token(self):
        auth = OAuth1Session('foo')
        auth.send = mock_text_response('oauth_token=foo')
        resp = auth.fetch_request_token('https://example.com/token')
        self.assertEqual(resp['oauth_token'], 'foo')
        for k, v in resp.items():
            self.assertTrue(isinstance(k, unicode_type))
            self.assertTrue(isinstance(v, unicode_type))

        resp = auth.fetch_request_token('https://example.com/token', realm='A')
        self.assertEqual(resp['oauth_token'], 'foo')
        resp = auth.fetch_request_token('https://example.com/token',
                                        realm=['A', 'B'])
        self.assertEqual(resp['oauth_token'], 'foo')
Example #8
0
    def test_signature_types(self):
        def verify_signature(getter):
            def fake_send(r, **kwargs):
                signature = to_unicode(getter(r))
                self.assertIn('oauth_signature', signature)
                resp = mock.MagicMock(spec=requests.Response)
                resp.cookies = []
                return resp

            return fake_send

        header = OAuth1Session('foo')
        header.send = verify_signature(lambda r: r.headers['Authorization'])
        header.post('https://i.b')

        query = OAuth1Session('foo', signature_type=SIGNATURE_TYPE_QUERY)
        query.send = verify_signature(lambda r: r.url)
        query.post('https://i.b')

        body = OAuth1Session('foo', signature_type=SIGNATURE_TYPE_BODY)
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        body.send = verify_signature(lambda r: r.body)
        body.post('https://i.b', headers=headers, data='')
Example #9
0
    def test_fetch_token_invalid_response(self):
        auth = OAuth1Session('foo')
        auth.send = mock_text_response('not valid urlencoded response!')
        self.assertRaises(ValueError, auth.fetch_request_token,
                          'https://example.com/token')

        for code in (400, 401, 403):
            auth.send = mock_text_response('valid=response', code)
            # use try/catch rather than self.assertRaises, so we can
            # assert on the properties of the exception
            try:
                auth.fetch_request_token('https://example.com/token')
            except OAuthError as err:
                self.assertEqual(err.error, 'fetch_token_denied')
            else:  # no exception raised
                self.fail("ValueError not raised")
Example #10
0
    def test_set_token(self):
        sess = OAuth1Session('foo')
        try:
            sess.token = {}
        except OAuthError as exc:
            self.assertEqual(exc.error, 'missing_token')

        sess.token = {'oauth_token': 'a', 'oauth_token_secret': 'b'}
        self.assertIsNone(sess.token['oauth_verifier'])
        sess.token = {'oauth_token': 'a', 'oauth_verifier': 'c'}
        self.assertEqual(sess.token['oauth_token_secret'], 'b')
        self.assertEqual(sess.token['oauth_verifier'], 'c')

        sess.token = None
        self.assertIsNone(sess.token['oauth_token'])
        self.assertIsNone(sess.token['oauth_token_secret'])
        self.assertIsNone(sess.token['oauth_verifier'])
Example #11
0
    def __init__(self, key=None, secret=None, environment=None, **kwargs):
        logging.info("Initializing CNCM Client")

        # Handle the key
        if not key:
            assert 'key' in kwargs
            key = kwargs['key']
        assert type(
            key) == str, "The key must be an string. Current type '{}'".format(
                type(key))
        self.key = key

        # Handle the secret
        if not secret:
            assert 'secret' in kwargs
            secret = kwargs['secret']
        assert type(
            secret
        ) == str, "The key must be an string. Current type '{}'".format(
            type(secret))
        self.secret = secret

        # Handle environment, default value "prod"
        self.environment = "prod"
        if not environment:
            if 'environment' in kwargs:
                assert type(kwargs['environment']
                            ) == str, "environment argument must be an string"
                assert kwargs['environment'] in CNCM_envs.keys(
                ), "Provided environment '{}' not recognized in defined CNMC_envs {}".format(
                    kwargs['environment'], str(FACE_ENVS.keys()))
                self.environment = kwargs['environment']

        self.url = CNCM_envs[self.environment]

        self.session = OAuth1Session(self.key,
                                     self.secret,
                                     signature_method="HMAC-SHA1",
                                     signature_type="HEADER")
        self.NIF = self.get_NIF()
Example #12
0
def verify_osm_access_token(osm_access_token, osm_access_token_secret):
    # OSM access tokens do not expire, so there is no manual expiry check here - it is
    # sufficient to look up the row in the database. If we want to block a user, we can
    # just prevent their JWT access and drop the OSM access row.

    # Check the DB for an entry - if it matches, we're happy.
    oauth_token_row = OpenStreetMapToken.query.filter_by(
        osm_access_token=osm_access_token,
        osm_access_token_secret=osm_access_token_secret
    ).first()

    # This might be a new user requesting access. We will use their OSM access token
    # and secret to retrieve their user_id, demonstrating that the tokens work and
    # producing the necessary info for storing their account
    if item is None:
        session = OAuth1Session(
            CLIENT_ID,
            CLIENT_SECRET,
            token=item.osm_token,
            token_secret=item.osm_token_secret
        )
        # Need to create new user - fetch from OSM
        resp = session.get(OSM_USER_DETAILS_URL)

        try:
            # TODO: this code is replicated twice - consolidate
            xml = resp.text
            etree = ET.fromstring(xml)
            user = etree.findall("user")[0]
            user_dict = dict(user.attrib)
            osm_uid = user_dict["id"]
            osm_display_name = user_dict["display_name"]
        except:
            return False
    else:
        osm_uid = oauth_token_row.osm_uid
        osm_display_name = oauth_token_row.display_name

    return osm_uid, osm_display_name
 def test_fetch_access_token_has_verifier_is_none(self):
     session = OAuth1Session('foo')
     session.auth.verifier = None
     self._test_fetch_access_token_raises_error(session)
Example #14
0
 def test_no_client_id(self):
     self.assertRaises(ValueError, lambda: OAuth1Session(None))
Example #15
0
 def test_fetch_access_token_has_verifier_is_none(self):
     auth = OAuth1Session('foo')
     auth._client.verifier = None
     self._test_fetch_access_token_raises_error(auth)
Example #16
0
 def test_fetch_access_token_missing_verifier(self):
     self._test_fetch_access_token_raises_error(OAuth1Session('foo'))
 def get_oauth_session(self, token=None, token_secret=None):
     session = OAuth1Session(self.flickr_api_key,
                             self.flickr_api_secret,
                             token=token,
                             token_secret=token_secret)
     return session
Example #18
0
 def test_redirect_uri(self):
     sess = OAuth1Session('foo')
     self.assertIsNone(sess.redirect_uri)
     url = 'https://i.b'
     sess.redirect_uri = url
     self.assertEqual(sess.redirect_uri, url)