def test_create_authorization_url(self): auth = OAuth1Session('foo') url = 'https://example.comm/authorize' token = 'asluif023sf' auth_url = auth.create_authorization_url(url, request_token=token) self.assertEqual(auth_url, url + '?oauth_token=' + token) redirect_uri = 'https://c.b' auth = OAuth1Session('foo', redirect_uri=redirect_uri) auth_url = auth.create_authorization_url(url, request_token=token) self.assertIn(escape(redirect_uri), auth_url)
async def oauth(message: types.Message): user_in_db = await db.check_user() if user_in_db: global oauth global oauth_id global boards global boards_dict oauth_token, oauth_token_secret = await db.access() oauth = OAuth1Session(client_key, client_secret, token=oauth_token, token_secret=oauth_token_secret) url = 'https://api.trello.com/1/members/me' oauth_id = oauth.get(url).json()['id'] url_board = f'https://api.trello.com/1/members/{oauth_id}/boards' boards = oauth.get(url_board).json() boards_dict = {} # словарь name-id досок for board in boards: boards_dict[board['id']] = board['name'] boards_keyboard = types.InlineKeyboardMarkup() # Создаем кнопки for board_id in boards_dict.keys(): bt_board = types.InlineKeyboardButton(boards_dict[board_id], callback_data=board_id) boards_keyboard.add(bt_board) await message.answer("Выберите доску:", reply_markup=boards_keyboard) else: await message.answer( 'Для получения полного функционала вам необходимо авторизоваться /oauth' )
def send_tweet(auth, tweet, in_reply_to=None): """Actually send a tweet""" if isinstance(tweet, list): # It's a thread of tweets prev = ret = None for part in tweet: if not part: continue info = send_tweet(auth, part, in_reply_to=prev) if "error" in info: return info if not ret: ret = info # Return the info for the *first* tweet sent prev = info["tweet_id"] return ret or {"error": "Can't send a thread of nothing but empty tweets"} twitter = OAuth1Session(config.TWITTER_CLIENT_ID, config.TWITTER_CLIENT_SECRET, auth[0], auth[1]) resp = twitter.post("https://api.twitter.com/1.1/statuses/update.json", data={"status": tweet, "in_reply_to_status_id": in_reply_to}) if resp.status_code != 200: print("Unknown response from Twitter") print(resp.status_code) print("---") print(resp.json()) print("---") try: # TODO: Report these to the front end somehow even if asynchronous return {"error": "Unable to send tweet: " + resp.json()["errors"][0]["message"]} except LookupError: return {"error": "Unknown error response from Twitter (see server console)"} r = resp.json() url = "https://twitter.com/%s/status/%s" % (r["user"]["screen_name"], r["id_str"]) return {"screen_name": r["user"]["screen_name"], "tweet_id": r["id"], "url": url}
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))
def login_twitter(): twitter = OAuth1Session(config.TWITTER_CLIENT_ID, config.TWITTER_CLIENT_SECRET, redirect_uri=url_for("authorized_twitter", _external=True)) session["twitter_state"] = twitter.fetch_request_token( "https://api.twitter.com/oauth/request_token") return redirect( twitter.create_authorization_url( "https://api.twitter.com/oauth/authenticate"))
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_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))
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')
def fetch_access_token(client: OAuth1Session, oauth_verifier: str) -> dict: """Fetch and return the OAuth1 access token.""" access_token_url = urljoin(API_HOST, f"{API_URL}/oauth1/access_token") try: oauth_token = client.fetch_access_token(access_token_url, verifier=oauth_verifier) except Exception as e: log.warning(f"Failed to fetch the OAuth1 access token: {e}") raise return oauth_token
def authorized_twitter(): if "denied" in request.args: # User cancelled the auth flow - discard auth (most likely there won't be any) session.pop("twitter_oauth", None) return redirect(url_for("mainpage")) req_token = session["twitter_state"] twitter = OAuth1Session(config.TWITTER_CLIENT_ID, config.TWITTER_CLIENT_SECRET, req_token["oauth_token"], req_token["oauth_token_secret"]) resp = twitter.fetch_access_token("https://api.twitter.com/oauth/access_token", request.args["oauth_verifier"]) session["twitter_oauth"] = resp return redirect(url_for("mainpage"))
async def oauth(message: types.Message): global oauth #global resource_owner_key #global resource_owner_secret id_user = message.from_user.id id_chat = message.chat.id check = await db.check_user() if check == False: if id_user != id_chat: bot_keyboard = types.InlineKeyboardMarkup() bot_keyboard.add( types.InlineKeyboardButton( text="Start dialog with bot", url='https://t.me/Shcherbatkin_Bot')) await message.answer("Начните диалог с ботом", reply_markup=bot_keyboard) else: request_token_url = 'https://trello.com/1/OAuthGetRequestToken' oauth = OAuth1Session(client_key, client_secret=client_secret) oauth.redirect_uri = f'http://84.201.165.21:9090' # перенаправление на сервер fetch_response = oauth.fetch_request_token(request_token_url) resource_owner_key = fetch_response.get('oauth_token') resource_owner_secret = fetch_response.get('oauth_token_secret') base_authorization_url = 'https://trello.com/1/OAuthAuthorizeToken' authorization_url = oauth.create_authorization_url( base_authorization_url, expiration='never', scope='read,write') keyboard = types.InlineKeyboardMarkup() keyboard.add( types.InlineKeyboardButton(text="Login with Oauth", url=authorization_url)) await message.answer( "Продите процедуру авторизации, после чего введите полученный url", reply_markup=keyboard) await Date.D5.set() @dp.message_handler(state=Date.D5) async def add_task(message: types.Message, state: FSMContext): global oauth redirect_url = message.text await state.finish() oauth.parse_authorization_response(redirect_url) access_token_url = 'https://trello.com/1/OAuthGetAccessToken' token = oauth.fetch_access_token(access_token_url) oauth_token = token['oauth_token'] oauth_token_secret = token['oauth_token_secret'] await db.oauth(oauth_token, oauth_token_secret) text = [ 'Авторизация прошла успешно', 'Для получения справки введите /help' ] await message.answer('\n'.join(text)) else: await dp.bot.send_message(message.from_user.id, 'Вы уже авторизированы')
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)])
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'} def fake_send(r, **kwargs): auth_header = r.headers['Authorization'] self.assertIn('oauth_body_hash', auth_header) auth = OAuth1Session('foo', force_include_body=True) auth.send = fake_send auth.post('https://i.b', headers=headers, files=[('fake', fake_xml)])
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')
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='')
async def oauth(message: types.Message): check = await db.check_user() if check == False: request_token_url = 'https://trello.com/1/OAuthGetRequestToken' oauth = OAuth1Session(client_key, client_secret=client_secret) oauth.redirect_uri = 'http://localhost:9090' # перенаправление на сервер fetch_response = oauth.fetch_request_token(request_token_url) resource_owner_key = fetch_response.get('oauth_token') resource_owner_secret = fetch_response.get('oauth_token_secret') base_authorization_url = 'https://trello.com/1/OAuthAuthorizeToken' authorization_url = oauth.create_authorization_url( base_authorization_url, expiration='never', scope='read,write') #print(authorization_url) keyboard = types.InlineKeyboardMarkup() keyboard.add( types.InlineKeyboardButton(text="Login with Oauth", url=authorization_url)) await message.answer("Продите процедуру авторизации", reply_markup=keyboard) # Магия обработки url sock = socket.socket() sock.connect(('localhost', 9090)) data = sock.recv(1024) print('Сервер прислал', data) sock.close() # конец магии await message.answer(data) """ # Парсинг url и получение токенов oauth.parse_authorization_response(url) access_token_url = 'https://trello.com/1/OAuthGetAccessToken' token = oauth.fetch_access_token(access_token_url) print('Получаем наши любименькие токены :)') print(token) #save_access_token(token) oauth_token = token['oauth_token'] oauth_token_secret = token['oauth_token_secret'] await db.oauth(oauth_token, oauth_token_secret) #balance = await database.check_money() text = [ 'Авторизация прошла успешно', 'Для получения справки введите /help' ] await message.answer('\n'.join(text)) """ else: await message.answer('Вы уже авторизированы')
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")
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'])
def get_new_api_session(config: Box): """Return an authenticated session to the Discovergy API.""" if "oauth_token" in config: token = config["oauth_token"] else: get_oauth1_token(config) token = config["oauth_token"] # Construct OAuth session with access token discovergy_oauth_session = OAuth1Session( token["key"], client_secret=token["client_secret"], token=token["token"], token_secret=token["token_secret"], ) return discovergy_oauth_session
async def oauth(message: types.Message): global oauth global oauth_id global boards_list global boards oauth_token, oauth_token_secret = await database.access() oauth = OAuth1Session(client_key, client_secret, token=oauth_token, token_secret=oauth_token_secret) url = 'https://api.trello.com/1/members/me' oauth_id = oauth.get(url).json()['id'] url_board = f'https://api.trello.com/1/members/{oauth_id}/boards' boards = oauth.get(url_board).json() boards_list = [] for board in boards: boards_list.append(board['name']) boards_keyboard = types.InlineKeyboardMarkup() for name in boards_list: bt_board = types.InlineKeyboardButton(name, callback_data=name) boards_keyboard.add(bt_board) await message.answer("Выберите доску:", reply_markup=boards_keyboard)
def fetch_new_oauth1_token(config: Box, save: bool = True) -> OAuth1Token: """Return a new OAuth1 token. Also, update the config.""" consumer_token = get_consumer_token(config) log.debug( f"Fetched a new consumer token: {get_consumer_token.retry.statistics}") oauth_key, oauth_secret = (consumer_token[k] for k in ("key", "secret")) client = OAuth1Session(oauth_key, oauth_secret) oauth_verifier = get_oath_verifier(config, client) access_token = fetch_access_token(client, oauth_verifier) token = OAuth1Token( key=oauth_key, client_secret=oauth_secret, token=access_token["oauth_token"], token_secret=access_token["oauth_token_secret"], ) config["oauth_token"] = token._asdict() if save: path, config_updater = config_updater_factory(config) write_config_updater(path, config_updater) return token
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)
def test_fetch_access_token_missing_verifier(self): self._test_fetch_access_token_raises_error(OAuth1Session('foo'))
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)
def test_no_client_id(self): self.assertRaises(ValueError, lambda: OAuth1Session(None))