def _check_latin1_encoding(self): try: _basic_auth_str(self.login, self.password) except (UnicodeEncodeError, UnicodeDecodeError) as e: msg = "Your login or password contains latin1 character(s) that " \ "are not allowed in BasicAuth used by %s" % self.tracker.name raise FetcherBadDataError(msg)
def issued_tokens(request, superdesk_app, superdesk_client): tokens = [] clients_data = [] # register clients with superdesk_app.app_context(): for param in request.param: clients_data.append({ "name": str(ObjectId()), # just a random string "client_id": str(ObjectId()), "password": str(ObjectId()), # just a random string "scope": param }) RegisterClient().run(**clients_data[-1]) # retrieve tokens with superdesk_app.test_request_context(): for client_data in clients_data: resp = superdesk_client.post( url_for('auth_server.issue_token'), data={'grant_type': 'client_credentials'}, headers={ 'Authorization': _basic_auth_str(client_data['client_id'], client_data['password']) }) tokens.append(json.loads(resp.data.decode('utf-8'))) teardown_app(superdesk_app) del superdesk_client return tokens
def test_not_admin_create_role(self): """ test role creation fail by non admin""" warnings.simplefilter("ignore") request_token = self.client().get( '/api/login/', headers={ 'Content-Type': 'application/json', 'Authorization': _basic_auth_str(self.user_not_admin.get('username'), self.user_not_admin.get('password')) }) json_data = json.loads(request_token.data) self.user_not_admin['token'] = json_data.get('token') json_role = { 'name': string_generator() + 'role_test_name', 'comment': string_generator() + 'role_test_comment' } request_role_not_admin_create = self.client().post( '/api/role/', headers={ 'Content-Type': 'application/json', 'x-access-token': self.user_not_admin['token'] }, data=json.dumps(json_role)) json_data = json.loads(request_role_not_admin_create.data) self.assertTrue(json_data.get('message')) self.assertEqual(json_data.get('message'), 'Cannot perform that function!') self.assertEqual(request_role_not_admin_create.status_code, 200)
def test_not_admin_get_all_roles(self): """ test to get all roles """ # user1 = { # 'user': '******', # 'pwd': 'role123'} warnings.simplefilter("ignore") request_token = self.client().get( '/api/login/', headers={ 'Content-Type': 'application/json', 'Authorization': _basic_auth_str(self.user_not_admin.get('username'), self.user_not_admin.get('password')) }) json_data = json.loads(request_token.data) self.user_not_admin['token'] = json_data.get('token') request_not_admin_get_user = self.client().get( '/api/role/', headers={ 'Content-Type': 'application/json', 'x-access-token': self.user_not_admin.get('token') }) get_data = json.loads(request_not_admin_get_user.data) result = get_data.get('message') self.assertEqual(result, 'Cannot perform that function!')
def test_auth_via_basic_auth(): client = application.test_client() with mock.patch('flask_oauthlib.client.OAuthRemoteApp.http_request') as f: oauth_resp = requests.Response() oauth_resp.status_code = 200 oauth_resp.code = 200 oauth_resp._content = json.dumps({ 'access_token': 'existing-token', }) f.return_value = ( oauth_resp, oauth_resp._content ) resp = client.get( '/other/very/deep/url', headers={ 'Authorization': _basic_auth_str('oauth', 'existing-token'), } ) f.assert_called_once_with( 'https://example.com/oauth2/tokeninfo', { 'Authorization': 'Bearer existing-token', }, data=mock.ANY, method=mock.ANY ) assert resp.status_code == 200 assert resp.data == b'other'
def test_create_team(self): """ test user creation """ warnings.simplefilter("ignore") request_token = self.client().get('/api/login/', headers={ 'Content-Type': 'application/json', 'Authorization': _basic_auth_str( self.user.get('username'), self.user.get('password')) }) json_data = json.loads(request_token.data) self.user['token'] = json_data.get('token') json_team = { "name": string_generator(), "comment": 'This is a Team for CS', "company_id": 1 } request_team_create = self.client().post('/api/team/', headers={ 'Content-Type': 'application/json', 'x-access-token': self.user['token'] }, data=json.dumps(json_team)) json_data = json.loads(request_team_create.data) self.assertTrue(json_data.get('message')) self.assertEqual(json_data.get('message'), 'New Team created!')
def test_create_company(self): """ test company creation """ warnings.simplefilter("ignore") request_token = self.client().get('/api/login/', headers={ 'Content-Type': 'application/json', 'Authorization': _basic_auth_str( self.user.get('username'), self.user.get('password')) }) json_data = json.loads(request_token.data) self.user['token'] = json_data.get('token') json_user = { "name": "Software LTD" + string_generator(), "comment": "a software oriented company" } request_user_create = self.client().post('/api/company/', headers={ 'Content-Type': 'application/json', 'x-access-token': self.user['token'] }, data=json.dumps(json_user)) json_data = json.loads(request_user_create.data) self.assertTrue(json_data.get('message')) self.assertEqual(json_data.get('message'), 'New Company created!') self.assertEqual(request_user_create.status_code, 200)
def __call__( self, request: requests.PreparedRequest) -> requests.PreparedRequest: request = super().__call__(request) request.headers["Authorization"] = _basic_auth_str( self.client_id, self.client_secret) return request
def test_get_token_as_unauthorized_user(self, app, user): with app.test_client() as client: authorization = _basic_auth_str(user.username, app.config['TEST_PASSWORD'] + 'x') response = client.post("/api/tokens", headers={"Authorization": authorization}) data = response.get_json() assert response.status_code == 401 assert data == {'error': 'Unauthorized'}
def setUpClass(cls): host = os.environ['POSTGRES_HOST'] port = os.environ['POSTGRES_PORT'] password = os.environ['POSTGRES_PASSWORD'] schema = os.environ['POSTGRES_SCHEMA'] cls.db_string = f'postgresql://{schema}:{password}@{host}:{port}/{schema}' cls.engine = create_engine( cls.db_string).execution_options(isolation_level="AUTOCOMMIT") cls.Session = sessionmaker(bind=cls.engine) cls.user_id = "00000000-0000-0000-0000-000000000001" cls.email = '*****@*****.**' # register app.test_client().post("/register", data={ 'registration_code': 'code1', 'email': '*****@*****.**', 'password': '******' }) res = app.test_client().get("/get-auth-token", headers={ "Authorization": _basic_auth_str( "*****@*****.**", "student1") }) cls.token = json.loads(res.data.decode('ascii'))['token']
def test_get_token_expired(self, subscription): subs_url = 'https://api.fitbit.com/1/user/-/apiSubscriptions.json' self.fbuser.expires_at = 1483400000 self.fbuser.save() sub = { 'ownerId': self.fbuser.fitbit_user, 'subscriberId': '1', 'subscriptionId': str(self.user.id), 'collectionType': 'user', 'ownerType': 'user' } subs = {'apiSubscriptions': [sub]} tok = { 'access_token': 'fake_return_access_token', 'refresh_token': 'fake_return_refresh_token', 'expires_at': 1483600000, } with requests_mock.mock() as m: m.get(subs_url, text=json.dumps(subs), status_code=200) m.post('https://api.fitbit.com/oauth2/token', text=json.dumps(tok)) response = self._get() mock_requests = m.request_history assert mock_requests[0].path == '/oauth2/token' assert mock_requests[0].headers['Authorization'] == _basic_auth_str( settings.FITAPP_CONSUMER_KEY, settings.FITAPP_CONSUMER_SECRET ) assert mock_requests[1].path == '/1/user/-/apisubscriptions.json' assert mock_requests[1].headers['Authorization'] == 'Bearer {}'.format( tok['access_token'] ) subscription.assert_called_once_with( sub['subscriptionId'], sub['subscriberId'], method="DELETE")
def get_wsgi_auth(auth: Optional[RawAuth], auth_type: Optional[str]) -> Optional[str]: if auth: if auth_type == "digest": raise ValueError("Digest auth is not supported for WSGI apps") return _basic_auth_str(*auth) return None
def get_headers(self): return { 'Authorization': _basic_auth_str(self.settings['secret_access_key'], ''), 'Accept': 'application/json', }
def get_headers_v1_to_v3(self): """ DEPRECATED """ return { 'Authorization': _basic_auth_str(self.settings['api_token'], 'x') }
def test_get_token(self, app, user): with app.test_client() as client: authorization = _basic_auth_str(user.username, app.config['TEST_PASSWORD']) response = client.post("/api/tokens", headers={"Authorization": authorization}) data = response.get_json() assert response.status_code == 200 assert user.token == data['token']
def client_post(client, url, data={}): return client.post(url, data=data, headers={'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS), 'Origin': 'http://example.com', 'content-type': 'application/json' })
def testGetRevokeToken(self): usr = { 'username': '******', 'email': '*****@*****.**', 'password': '******' } # register usr resp = self.client.post('/auth/register', json=usr) self.assertEqual(resp.status_code, 201) username, password = usr['username'], usr['password'] user = User.query.filter_by(username=username).first() self.assertIsNotNone(user) self.assertEqual(user.check_password('test'), True) # get token headers = {'Authorization': _basic_auth_str(username, password)} resp = self.client.post('auth/tokens', headers=headers) status_code, data_json = resp.status_code, resp.json self.assertEqual(status_code, 200) token = data_json.get('token') self.assertIsNotNone(token) # test_token_auth_required headers = {'Authorization': 'Bearer {}'.format(token)} resp = self.client.delete('/auth/tokens', headers=headers) self.assertEqual(resp.status_code, 204)
def test_admin_get_all_company(self): """ test to get all roles """ warnings.simplefilter("ignore") request_token = self.client().get('/api/login/', headers={ 'Content-Type': 'application/json', 'Authorization': _basic_auth_str( self.user.get('username'), self.user.get('password')) }) json_data = json.loads(request_token.data) self.user['token'] = json_data.get('token') request_admin_get_role = self.client().get('/api/company/', headers={ 'Content-Type': 'application/json', 'x-access-token': self.user.get('token') }) get_data = json.loads(request_admin_get_role.data) result = get_data.get('companies')[0] result = result.get('name') self.assertEqual(result, 'Software LTD')
def test_bad_shared_key(superdesk_app, superdesk_client, auth_server_registered_clients): """ Send a request with a token which is signed and verified using different secrets: - register client for auth server - retrieve an acceess token from auth server by providing `id` and `password` - make a request with a token - ensure that request is NOT authenticated by prod api, because of different shared secret :param superdesk_app: superdesk api app :type superdesk_app: eve.flaskapp.Eve :param superdesk_client: client for superdesk api :type superdesk_client: flask.testing.FlaskClient """ client_id = auth_server_registered_clients[0]['client_id'] password = auth_server_registered_clients[0]['password'] # we send a client id and password to get an access token with superdesk_app.test_request_context(): resp = superdesk_client.post( url_for('auth_server.issue_token'), data={'grant_type': 'client_credentials'}, headers={'Authorization': _basic_auth_str(client_id, password)}) # we get an access token resp_data = json.loads(resp.data.decode('utf-8')) token = resp_data['access_token'] # we drop a superdesk flask app and client to avoid conflict between flask apps teardown_app(superdesk_app) del superdesk_client # we create a prodapi flask app and client prodapi_app = get_test_prodapi_app() prodapi_client = prodapi_app.test_client() # we change `AUTH_SERVER_SHARED_SECRET` prodapi_app.config[ 'AUTH_SERVER_SHARED_SECRET'] = '7fZOf0VI9T70vU5uNlKLrc5GlabxVgl6' # we send a request with an auth token with prodapi_app.test_request_context(): for resource in ('archive', ): # we send a request with a token resp = prodapi_client.get( url_for('{}|resource'.format(resource)), headers={'Authorization': 'Bearer {}'.format(token)}) resp_data = json.loads(resp.data.decode('utf-8')) # we get a 401 response assert resp.status_code == 401 assert resp_data == { '_status': 'ERR', '_error': { 'code': 401, 'message': 'Please provide proper credentials' } }
def test_change_currency(self): admin_token, _ = self.register_user(self.admin_payload) noob_token, noob = self.register_user(self.noob_payload) headers={"Authorization": _basic_auth_str(admin_token, "pass"), "Content-Type": "application/json"} req = self.app.post("/users/{}/change-maincurrency?currency={}".format(noob["id"], "usd"), headers=headers) self.assertEqual(req.status_code, 200) user = self.app.get("/users/{}".format(noob["id"]), headers=headers).json["data"]["main_currency"] self.assertEqual(user.lower(), "usd")
def client_get(client, url): # Add fake Origin to ensure CORS kicks in return client.get(url, headers={ 'Authorization': _basic_auth_str(_TEST_USER, _TEST_PASS), 'Origin': 'http://example.com' })
def test_get_basic_auth_username_and_password(self): from requests.auth import _basic_auth_str _username, _password = '******', 'password' credentials = _basic_auth_str(_username, _password).split()[1] username, password = self.backend.get_basic_auth_username_and_password( credentials) self.assertEqual(username, _username) self.assertEqual(password, _password)
def get_headers(self): return { 'Authorization': _basic_auth_str(self.settings['username'], self.settings['password']), 'Accept': 'application/json', }
def test_login2(self): tester = app.test_client(self) response = tester.get('/login',headers= {'Authorization':_basic_auth_str('Fake user','wrong pass')}) data = response.content_type data1 = response.get_json() # print(response.get_json()) assert response.status_code == 401
def _headers(self, **kwargs): auth_string = _basic_auth_str(self.pos_id, self.secret_id) data = { "Content-Type": "application/json", "Authorization": auth_string } data.update(kwargs) return data
def get_headers(self): return { 'Accept': 'application/json', 'Authorization': _basic_auth_str(f"{self.settings['username']}/token", self.settings['api_token']) }
def get_result_from_analyticsai(self, query): return self.app_client.post("/api/v1.0/data_analysis", data=json.dumps(query), headers={ "Authorization": _basic_auth_str("xxxxxx", "xxxxxx"), "Content-Type": "application/json" })
def open(self, *args, **kwargs): if "headers" in kwargs: headers = kwargs["headers"] else: headers = kwargs["headers"] = {} headers["Authorization"] = _basic_auth_str("*****@*****.**", "admin") return super().open(*args, **kwargs)
def put_authorised(self, path, data=None, username='******', password='******'): return self.test_app.put( path, data=data, headers={"Authorization": _basic_auth_str(username, password)})
def get_token(user, password): """Get an auth token for the given user. :param user: The user name to get a token for. :param password: The user password. """ token = _basic_auth_str(user, password) return token.split(None, 1)[-1]
def test_server_polling_requests_should_use_auth_basic(configured_file_sync_client_with_queue, server_address, pending_files_list_json, input_parameters): from requests.auth import _basic_auth_str expected_auth_value = _basic_auth_str(username=input_parameters['user'],password=input_parameters['passwd']) with requests_mock.mock() as m: m.get(server_address, text=pending_files_list_json, request_headers={'Authorization' : expected_auth_value }) response = configured_file_sync_client_with_queue.check_pending_files() assert m.called assert response.text == pending_files_list_json
def test_auth(flask_client): # A request without authorization should fail with 401 response = flask_client.get("/") assert response.status_code == 401 # A request with authorization should not fail with 401 headers = {"Authorization": _basic_auth_str("test", "test")} response = flask_client.get("/", headers=headers) assert response.status_code != 401
def delete(self, url): response = self.client.delete( url, headers={'Authorization': _basic_auth_str("user", "password")}) LOG.info((">>> response code {}").format(response.status_code)) LOG.info((">>> response data {}").format(response.data)) return response
def test_token_expired(superdesk_app, superdesk_client, auth_server_registered_clients): """ Send a request with an expired token: - register client for auth server - retrieve an acceess token from auth server by providing `id` and `password` - wait until token expires - make a request with an expired token - ensure that request is NOT authenticated by prod api :param superdesk_app: superdesk api app :type superdesk_app: eve.flaskapp.Eve :param superdesk_client: client for superdesk api :type superdesk_client: flask.testing.FlaskClient """ client_id = auth_server_registered_clients[0]['client_id'] password = auth_server_registered_clients[0]['password'] expiration_delay = superdesk_app.config['AUTH_SERVER_EXPIRATION_DELAY'] # we send a client id and password to get an access token with superdesk_app.test_request_context(): resp = superdesk_client.post( url_for('auth_server.issue_token'), data={ 'grant_type': 'client_credentials' }, headers={ 'Authorization': _basic_auth_str(client_id, password) } ) # we get an access token assert resp.status_code == 200 resp_data = json.loads(resp.data.decode('utf-8')) token = resp_data['access_token'] # wait until token expire time.sleep(expiration_delay + 1) # we create a prodapi flask app and client prodapi_app = get_test_prodapi_app() prodapi_client = prodapi_app.test_client() # we send a request with an expired auth token with prodapi_app.test_request_context(): for resource in ('archive',): # we send a request with a token resp = prodapi_client.get( url_for('{}|resource'.format(resource)), headers={ 'Authorization': 'Bearer {}'.format(token) } ) # we get a 401 response assert resp.status_code == 401
def _post(self, url, data=None, with_auth=True, **extra): post_extra = { 'QUERY_STRING': urlencode(data, doseq=True) if data else '' } post_extra.update(extra) if with_auth: post_extra['HTTP_AUTHORIZATION'] = _basic_auth_str(self.user.login, self.user.api_key) return self._factory.post(url, **post_extra)
def basic_auth(self, username, password): ''' add basic auth to this client link -- http://stackoverflow.com/questions/6068674/ username -- string password -- string ''' self.headers['authorization'] = _basic_auth_str(username, password)
def test_device_call_last_used(self): self.cio.http.hooks=dict(response=partial(self._check_request, rq={ 'method': 'PUT', 'authorization': _basic_auth_str('siteid', 'apikey'), 'content_type': 'application/json', 'url_suffix': '/customers/1/devices', 'body': {"device": {"id": "device_2", "platform": "android", "last_used": 1234567890}} })) self.cio.add_device(customer_id=1, device_id="device_2", platform="android", last_used=1234567890)
def proxy_headers(self, proxy): headers = {} username, password = get_auth_from_url(proxy) if username and password: username = unquote(username) password = unquote(password) headers["Proxy-Authorization"] = _basic_auth_str(username, password) return headers
def test_device_call_has_device_id(self): self.cio.http.hooks=dict(response=partial(self._check_request, rq={ 'method': 'PUT', 'authorization': _basic_auth_str('siteid', 'apikey'), 'content_type': 'application/json', 'url_suffix': '/customers/1/devices', 'body': {"device": {"id": "device_5", "platform": "ios"}} })) with self.assertRaises(CustomerIOException): self.cio.add_device(customer_id=1, device_id="", platform="ios")
def test_auth_info(self): global active_mock_response active_mock_response = (200, '{"status": "OK", "total": 10, "method": "insert", "trans_id": 352649805417295872}') httpretty.register_uri(httpretty.POST, self.insert_entpoint, body=request_callback) self.api.insert(self.inserted_images) from requests.auth import _basic_auth_str expected_auth_str = _basic_auth_str(self.access_key, self.secret_key) self.assertEqual(request_callback.request.headers['authorization'], expected_auth_str)
def handle_407(response, **kwargs): """ Prompts the user for the proxy username and password and modifies the proxy in the session object to include it. This method is modeled after * requests.auth.HTTPDigestAuth.handle_401() * requests.auth.HTTPProxyAuth * the previous conda.fetch.handle_proxy_407() It both adds 'username:password' to the proxy URL, as well as adding a 'Proxy-Authorization' header. If any of this is incorrect, please file an issue. """ # kwargs = {'verify': True, 'cert': None, 'proxies': OrderedDict(), 'stream': False, # 'timeout': (3.05, 60)} if response.status_code != 407: return response # Consume content and release the original connection # to allow our new request to reuse the same one. response.content response.close() proxies = kwargs.pop('proxies') proxy_scheme = urlparse(response.url).scheme if proxy_scheme not in proxies: raise ProxyError(dals(""" Could not find a proxy for %r. See %s/docs/html#configure-conda-for-use-behind-a-proxy-server for more information on how to configure proxies. """ % (proxy_scheme, CONDA_HOMEPAGE_URL))) # fix-up proxy_url with username & password proxy_url = proxies[proxy_scheme] username, password = get_proxy_username_and_pass(proxy_scheme) proxy_url = add_username_and_password(proxy_url, username, password) proxy_authorization_header = _basic_auth_str(username, password) proxies[proxy_scheme] = proxy_url kwargs['proxies'] = proxies prep = response.request.copy() extract_cookies_to_jar(prep._cookies, response.request, response.raw) prep.prepare_cookies(prep._cookies) prep.headers['Proxy-Authorization'] = proxy_authorization_header _response = response.connection.send(prep, **kwargs) _response.history.append(response) _response.request = prep return _response
def test_device_delete_call(self): self.cio.http.hooks=dict(response=partial(self._check_request, rq={ 'method': 'DELETE', 'authorization': _basic_auth_str('siteid', 'apikey'), 'content_type': 'application/json', 'url_suffix': '/customers/1/devices/device_1', 'body': {} })) self.cio.delete_device(customer_id=1, device_id="device_1") with self.assertRaises(TypeError): self.cio.delete_device(random_attr="some_value")
def _apply_basic_auth(request): # this logic duplicated from Session.prepare_request and PreparedRequest.prepare_auth url_auth = get_auth_from_url(request.url) auth = url_auth if any(url_auth) else None if auth is None: # look for auth information in a .netrc file auth = get_netrc_auth(request.url) if isinstance(auth, tuple) and len(auth) == 2: request.headers['Authorization'] = _basic_auth_str(*auth) return request
def test_pageview_call(self): self.cio.http.hooks=dict(response=partial(self._check_request, rq={ 'method': 'POST', 'authorization': _basic_auth_str('siteid', 'apikey'), 'content_type': 'application/json', 'url_suffix': '/customers/1/events', 'body': {"data": {"referer": "category_1"}, "type": "page", "name": "product_1"}, })) self.cio.pageview(customer_id=1, page='product_1', referer='category_1') with self.assertRaises(TypeError): self.cio.pageview(random_attr="some_value")
def test_track_call(self): self.cio.http.hooks=dict(response=partial(self._check_request, rq={ 'method': 'POST', 'authorization': _basic_auth_str('siteid', 'apikey'), 'content_type': 'application/json', 'url_suffix': '/customers/1/events', 'body': {"data": {"email": "*****@*****.**"}, "name": "sign_up"}, })) self.cio.track(customer_id=1, name='sign_up', email='*****@*****.**') with self.assertRaises(TypeError): self.cio.track(random_attr="some_value")
def test_unsuppress_call(self): self.cio.http.hooks=dict(response=partial(self._check_request, rq={ 'method': 'POST', 'authorization': _basic_auth_str('siteid', 'apikey'), 'content_type': 'application/json', 'url_suffix': '/customers/1/unsuppress', 'body': {}, })) self.cio.unsuppress(customer_id=1) with self.assertRaises(CustomerIOException): self.cio.unsuppress(None)
def test_auto_refresh_token_exception(self): """Test of auto_refresh with Unauthorized exception""" # 1. first call to _request causes a HTTPUnauthorized # 2. the token_refresh call is faked # 3. the second call to _request returns a valid value refresh_cb = mock.MagicMock() kwargs = copy.copy(self.client_kwargs) kwargs.update({ 'access_token': 'fake_access_token', 'refresh_token': 'fake_refresh_token', 'refresh_cb': refresh_cb, }) fb = Fitbit(**kwargs) profile_url = Fitbit.API_ENDPOINT + '/1/user/-/profile.json' with requests_mock.mock() as m: m.get(profile_url, [{ 'text': json.dumps({ "errors": [{ "errorType": "expired_token", "message": "Access token expired:" }] }), 'status_code': 401 }, { 'text': '{"user":{"aboutMe": "python-fitbit developer"}}', 'status_code': 200 }]) token = { 'access_token': 'fake_return_access_token', 'refresh_token': 'fake_return_refresh_token' } m.post(fb.client.refresh_token_url, text=json.dumps(token)) retval = fb.make_request(profile_url) self.assertEqual(m.request_history[1].path, '/oauth2/token') self.assertEqual( m.request_history[1].headers['Authorization'], _basic_auth_str( self.client_kwargs['client_id'], self.client_kwargs['client_secret'] ) ) self.assertEqual(retval['user']['aboutMe'], "python-fitbit developer") self.assertEqual("fake_return_access_token", token['access_token']) self.assertEqual("fake_return_refresh_token", token['refresh_token']) refresh_cb.assert_called_once_with(token)
def test_remove_from_segment_call(self): self.cio.http.hooks=dict(response=partial(self._check_request, rq={ 'method': 'POST', 'authorization': _basic_auth_str('siteid', 'apikey'), 'content_type': 'application/json', 'url_suffix': '/segments/1/remove_customers', 'body': {'ids': ['1','2','3']}, })) self.cio.remove_from_segment(segment_id=1, customer_ids=[1,2,3]) with self.assertRaises(CustomerIOException): self.cio.remove_from_segment(None, None) with self.assertRaises(CustomerIOException): self.cio.add_to_segment(segment_id=1, customer_ids=False) with self.assertRaises(CustomerIOException): self.cio.add_to_segment(segment_id=1, customer_ids=[False,True,False])
def __tortilla_api(self): url = self.get_url() if 'api_key' in self.__dict__ and self.api_key: self.headers.update({'apikey': self.api_key}) if 'user' in self.__dict__ and \ 'password' in self.__dict__ and \ self.user and self.password: self.headers.update({ 'Authorization': _basic_auth_str( self.user, self.password ) }) else: pass args = {} for a in self.tortilla_defaults.keys(): args[a] = self.__dict__[a] return tortilla.wrap(url, **args)
def test_basic_auth_str_is_always_native(self): s = _basic_auth_str("test", "test") assert isinstance(s, builtin_str) assert s == "Basic dGVzdDp0ZXN0"
def test_fetch_token(self): url = "https://example.com/token" for client in self.clients: sess = OAuth2Session(client=client, token=self.token) sess.send = fake_token(self.token) if isinstance(client, LegacyApplicationClient): # this client requires a username+password # if unset, an error will be raised self.assertRaises(ValueError, sess.fetch_token, url) self.assertRaises( ValueError, sess.fetch_token, url, username="******" ) self.assertRaises( ValueError, sess.fetch_token, url, password="******" ) # otherwise it will pass self.assertEqual( sess.fetch_token(url, username="******", password="******"), self.token, ) else: self.assertEqual(sess.fetch_token(url), self.token) error = {"error": "invalid_request"} for client in self.clients: sess = OAuth2Session(client=client, token=self.token) sess.send = fake_token(error) if isinstance(client, LegacyApplicationClient): # this client requires a username+password # if unset, an error will be raised self.assertRaises(ValueError, sess.fetch_token, url) self.assertRaises( ValueError, sess.fetch_token, url, username="******" ) self.assertRaises( ValueError, sess.fetch_token, url, password="******" ) # otherwise it will pass self.assertRaises( OAuth2Error, sess.fetch_token, url, username="******", password="******", ) else: self.assertRaises(OAuth2Error, sess.fetch_token, url) # there are different scenarios in which the `client_id` can be specified # reference `oauthlib.tests.oauth2.rfc6749.clients.test_web_application.WebApplicationClientTest.test_prepare_request_body` # this only needs to test WebApplicationClient client = self.client_WebApplication client.tester = True # this should be a tuple of (r.url, r.body, r.headers.get('Authorization')) _fetch_history = [] def fake_token_history(token): def fake_send(r, **kwargs): resp = mock.MagicMock() resp.text = json.dumps(token) _fetch_history.append( (r.url, r.body, r.headers.get("Authorization", None)) ) return resp return fake_send sess = OAuth2Session(client=client, token=self.token) sess.send = fake_token_history(self.token) expected_auth_header = _basic_auth_str(self.client_id, self.client_secret) # scenario 1 - default request # this should send the `client_id` in the headers, as that is recommended by the RFC self.assertEqual( sess.fetch_token(url, client_secret="someclientsecret"), self.token ) self.assertEqual(len(_fetch_history), 1) self.assertNotIn( "client_id", _fetch_history[0][1] ) # no `client_id` in the body self.assertNotIn( "client_secret", _fetch_history[0][1] ) # no `client_secret` in the body self.assertEqual( _fetch_history[0][2], expected_auth_header ) # ensure a Basic Authorization header # scenario 2 - force the `client_id` into the body self.assertEqual( sess.fetch_token( url, client_secret="someclientsecret", include_client_id=True ), self.token, ) self.assertEqual(len(_fetch_history), 2) self.assertIn("client_id=%s" % self.client_id, _fetch_history[1][1]) self.assertIn("client_secret=%s" % self.client_secret, _fetch_history[1][1]) self.assertEqual( _fetch_history[1][2], None ) # ensure NO Basic Authorization header # scenario 3 - send in an auth object auth = requests.auth.HTTPBasicAuth(self.client_id, self.client_secret) self.assertEqual(sess.fetch_token(url, auth=auth), self.token) self.assertEqual(len(_fetch_history), 3) self.assertNotIn( "client_id", _fetch_history[2][1] ) # no `client_id` in the body self.assertNotIn( "client_secret", _fetch_history[2][1] ) # no `client_secret` in the body self.assertEqual( _fetch_history[2][2], expected_auth_header ) # ensure a Basic Authorization header # scenario 4 - send in a username/password combo # this should send the `client_id` in the headers, like scenario 1 self.assertEqual( sess.fetch_token( url, username=self.user_username, password=self.user_password ), self.token, ) self.assertEqual(len(_fetch_history), 4) self.assertNotIn( "client_id", _fetch_history[3][1] ) # no `client_id` in the body self.assertNotIn( "client_secret", _fetch_history[3][1] ) # no `client_secret` in the body self.assertEqual( _fetch_history[0][2], expected_auth_header ) # ensure a Basic Authorization header self.assertIn("username=%s" % self.user_username, _fetch_history[3][1]) self.assertIn("password=%s" % self.user_password, _fetch_history[3][1]) # scenario 5 - send data in `params` and not in `data` for providers # that expect data in URL self.assertEqual( sess.fetch_token(url, client_secret="somesecret", force_querystring=True), self.token, ) self.assertIn("code=%s" % CODE, _fetch_history[4][0]) # some quick tests for valid ways of supporting `client_secret` # scenario 2b - force the `client_id` into the body; but the `client_secret` is `None` self.assertEqual( sess.fetch_token(url, client_secret=None, include_client_id=True), self.token, ) self.assertEqual(len(_fetch_history), 6) self.assertIn("client_id=%s" % self.client_id, _fetch_history[5][1]) self.assertNotIn( "client_secret=", _fetch_history[5][1] ) # no `client_secret` in the body self.assertEqual( _fetch_history[5][2], None ) # ensure NO Basic Authorization header # scenario 2c - force the `client_id` into the body; but the `client_secret` is an empty string self.assertEqual( sess.fetch_token(url, client_secret="", include_client_id=True), self.token ) self.assertEqual(len(_fetch_history), 7) self.assertIn("client_id=%s" % self.client_id, _fetch_history[6][1]) self.assertIn("client_secret=", _fetch_history[6][1]) self.assertEqual( _fetch_history[6][2], None ) # ensure NO Basic Authorization header
def credentials(): from requests.auth import _basic_auth_str credentials ={'user':'******','passwd':'passwd1'} credentials['_basic_auth_str']=_basic_auth_str(credentials['user'],credentials['passwd']) return credentials
def __call__(self, r): r.headers['Authorization'] = _basic_auth_str(self.username, self.password) return r
def callback(self, *args, **kwargs): """Callback method for issuing requests via the operations defined in the paths""" try: # If the `path` argument is not passed, raise a # `ValueError` exception. path = args[0] except IndexError: raise ValueError('Path argument not provided') if path not in self.paths: # If the `path` does not exist, raise `InvalidPathError` # exception. raise InvalidPathError(path) operation = self.paths[path][fn] # If the `scheme` keyword argument is present, override the # default scheme. Otherwise, use the default scheme for # issuing the request. scheme = kwargs.pop('scheme', self.DefaultScheme) scheme = self._get_scheme(scheme=scheme) fmt = kwargs.pop('format', self.DefaultFormat) if 'consumes' in operation: try: index = operation['consumes'].index(fmt) except ValueError: index = 0 finally: operation['index'] = index if 'security' in operation: try: auth = kwargs.pop('auth') securityDefinitions = self.securityDefinitions for security in operation['security']: for name in security.iterkeys(): if securityDefinitions[name]['type'] == 'apiKey': # If the security object name key exists # in the request header, then assign the # value of the request header the `auth` # token, otherwise, pass it as a query # parameter. if securityDefinitions[name]['in'] == 'header': header = securityDefinitions[name]['name'] self._session.headers[header] = auth else: kwargs[header] = auth if securityDefinitions[name]['type'] == 'basic': auth = _basic_auth_str(*auth) self._session.headers['Authorization'] = auth except KeyError: pass body = kwargs.pop('body', {}) # Override the default headers defined in the root schema. self._set_headers(operation) # Use string interpolation to replace placeholders with # keyword arguments. path = path.format(**kwargs) url = ( '{scheme}://{baseUri}{path}' ).format(scheme=scheme, baseUri=self._baseUri, path=path) # If the `body` keyword argument exists, remove it from the # keyword argument dictionary and pass it as an argument # when issuing the request. try: res = self._session.request(fn, url, params=kwargs, data=body, timeout=self._timeout) except requests.exceptions.SSLError: # If the request fails via a `SSLError`, re-instantiate # the request with the `verify` argument assigned to # `False`. res = self._session.request(fn, url, params=kwargs, data=body, verify=False, timeout=self._timeout) if res.status_code not in range(200, 300): # If the response status code is a non-2XX code, raise a # `ResponseError`. The `reason` variable attempts to # retrieve the `description` key if it is provided in # the `response` object. Otherwise, the default response # `reason` is used. try: response = operation['responses'][str(res.status_code)] reason = response.get('description', res.reason) status_code, reason = res.status_code, reason except KeyError: # Use the default `status_code` and `reason` # returned from the response. status_code, reason = res.status_code, res.reason raise self.ResponseError(status_code, reason) return res