Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Авторизация по OAuth #243

Merged
merged 14 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions fast_bitrix24/bitrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class BitrixAsync:
def __init__(
self,
webhook: str,
token_func: callable,
verbose: bool = True,
respect_velocity_policy: bool = True,
request_pool_size: int = 50,
Expand Down Expand Up @@ -57,6 +58,7 @@ def __init__(

self.srh = ServerRequestHandler(
webhook=webhook,
token_func=token_func,
respect_velocity_policy=respect_velocity_policy,
request_pool_size=request_pool_size,
requests_per_second=requests_per_second,
Expand Down
50 changes: 48 additions & 2 deletions fast_bitrix24/srh.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,16 @@ class ServerError(Exception):
pass


class TokenRejected(Exception):
pass


RETRIED_ERRORS = (
ClientPayloadError,
ClientConnectionError,
ServerError,
TimeoutError,
TokenRejected,
)


Expand All @@ -54,13 +59,22 @@ class ServerRequestHandler:
def __init__(
self,
webhook: str,
token_func: callable,
respect_velocity_policy: bool,
request_pool_size: int,
requests_per_second: float,
client,
ssl: bool = True,
):
self.webhook = self.standardize_webhook(webhook)

self.token_func = token_func
self.token = None

# token_received - сигнал о том, что процесс получения токена уже запущен
self.token_request_in_progress = Event()
self.token_request_in_progress.clear()

self.respect_velocity_policy = respect_velocity_policy

self.active_runs = 0
Expand Down Expand Up @@ -162,8 +176,21 @@ async def request_attempt(self, method, params=None) -> dict:
async with self.acquire(method):
logger.debug(f"Requesting {{'method': {method}, 'params': {params}}}")

params_with_auth = params.copy()

if self.token_func: # если требуется авторизация

# если вдруг процесс получения токена уже запущен,
# то подождать его окончания
await self.token_request_in_progress.wait()

if not self.token: # начальное получение токена
await self.update_token()

params_with_auth["auth"] = self.token

async with self.session.post(
url=self.webhook + method, json=params, ssl=self.ssl
url=self.webhook + method, json=params_with_auth, ssl=self.ssl
) as response:
json = await response.json(encoding="utf-8")

Expand All @@ -174,10 +201,22 @@ async def request_attempt(self, method, params=None) -> dict:
return json

except ClientResponseError as error:

if error.status // 100 == 5: # ошибки вида 5XX
raise ServerError("The server returned an error") from error

raise
# нужно получить или освежить токен

# TODO: нужно как-то отличать проблему протухания токена от других проблем
elif error.status == 403 and self.token_func:

# запрашиваем новый токен, только если процесс получения токена еще не запущен
if not self.token_request_in_progress.is_set():
await self.update_token()

raise TokenRejected("The server rejected the auth token") from error

raise # иначе повторяем полученное исключение

def add_throttler_records(self, method, params: dict, json: dict):
if "result_time" in json:
Expand Down Expand Up @@ -274,3 +313,10 @@ async def limit_concurrent_requests(self):
finally:
self.concurrent_requests -= 1
self.request_complete.set()

async def update_token(self):
"""Запросить новый токен авторизации."""

self.token_request_in_progress.clear()
self.token = await self.token_func()
self.token_request_in_progress.set()
22 changes: 22 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import pytest

def test_first_request():
# нужно проверить, что вызывается функция запроса токена при первом запросе

raise AssertionError

def test_auth_success():
# нужно проверить, что серверу передается токен, полученный от token_func

raise AssertionError

def test_auth_failure():
# нужно проверить, что вызывается функция запроса токена, если сервер вернул ошибку токена

raise AssertionError

def test_abort_on_multiple_failures():
# нужно проверить, что если token_func регулярно возвращает токен, который отвергается сервером,
# то запрос оборвется после MAX_RETRIES неудачных попыток

raise AssertionError
Loading