From ad67c8fd36877f515932a3695a5d02aae22906f1 Mon Sep 17 00:00:00 2001 From: Abdulaziz Abduvakhobov Date: Sat, 29 Jun 2024 02:29:51 +0300 Subject: [PATCH] fixed issue while sending request, added refreshing token instead of recreating it --- api/bot/commands/sms.py | 5 --- api/management/commands/send_message.py | 4 --- api/migrations/0020_eskizserviceconfig.py | 36 +++++++++++++++++++ api/models.py | 17 +++++++++ api/utils/eskiz.py | 42 +++++++++++++++-------- pyproject.toml | 10 ++++++ 6 files changed, 90 insertions(+), 24 deletions(-) create mode 100644 api/migrations/0020_eskizserviceconfig.py create mode 100644 pyproject.toml diff --git a/api/bot/commands/sms.py b/api/bot/commands/sms.py index 6ea3fff..8eb3643 100644 --- a/api/bot/commands/sms.py +++ b/api/bot/commands/sms.py @@ -12,11 +12,6 @@ def sms_balance(update: Update, context: CallbackContext) -> None: today = date.today() token = get_token() - if token is None: - return # Invalid token - - token = token["data"]["token"] - response = get_balance(token) if not response["status"]: update.message.reply_text("Ошибка при получении баланса от Eskiz.uz") diff --git a/api/management/commands/send_message.py b/api/management/commands/send_message.py index 822d536..e087b93 100644 --- a/api/management/commands/send_message.py +++ b/api/management/commands/send_message.py @@ -75,10 +75,6 @@ def send_messages(): return token = get_token() - if token is None: - return # Invalid token - - token = token["data"]["token"] nick = get_nickname(token) data = {"success": 0, "error": 0, "invalid": 0, "disabled": 0} diff --git a/api/migrations/0020_eskizserviceconfig.py b/api/migrations/0020_eskizserviceconfig.py new file mode 100644 index 0000000..3b4ac86 --- /dev/null +++ b/api/migrations/0020_eskizserviceconfig.py @@ -0,0 +1,36 @@ +# Generated by Django 4.2.11 on 2024-06-28 23:09 + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + dependencies = [ + ("api", "0019_serviceconfiguration"), + ] + + operations = [ + migrations.CreateModel( + name="EskizServiceConfig", + fields=[ + ("created_at", models.DateTimeField(auto_now_add=True)), + ("updated_at", models.DateTimeField(auto_now=True)), + ("is_active", models.BooleanField(default=True)), + ( + "id", + models.UUIDField( + default=uuid.uuid4, + primary_key=True, + serialize=False, + unique=True, + ), + ), + ("token", models.TextField()), + ("expires_at", models.DateTimeField(blank=True, null=True)), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/api/models.py b/api/models.py index 4802691..d29e862 100644 --- a/api/models.py +++ b/api/models.py @@ -1,4 +1,6 @@ import uuid +from datetime import datetime, timedelta +from django.utils import timezone from django.db import models @@ -188,3 +190,18 @@ class ServiceConfiguration(BaseModel): def __str__(self): return self.name + + +class EskizServiceConfig(BaseModel): + id = models.UUIDField(unique=True, default=uuid.uuid4, primary_key=True) + token = models.TextField() + expires_at = models.DateTimeField(null=True, blank=True) + + def __str__(self) -> str: + return self.token + + def refresh_token(self, token: str): + self.token = token + self.created_at = timezone.now() + self.expires_at = timezone.now() + timedelta(days=29) + self.save() diff --git a/api/utils/eskiz.py b/api/utils/eskiz.py index b3a9d24..7b7609c 100644 --- a/api/utils/eskiz.py +++ b/api/utils/eskiz.py @@ -1,35 +1,47 @@ import requests +from datetime import datetime, timedelta +from django.utils import timezone from django.conf import settings +from api.utils.telegram import send_telegram_message +from api.models import EskizServiceConfig + ESKIZ_EMAIL = settings.ESKIZ_EMAIL ESKIZ_PASSWORD = settings.ESKIZ_PASSWORD ESKIZ_URL = settings.ESKIZ_URL ESKIZ_DEFAULT_NICK = settings.ESKIZ_DEFAULT_NICK -def get_token(): - url = f"http://{ESKIZ_URL}/auth/login" +def _create_token() -> str: + url = f"https://{ESKIZ_URL}/auth/login" data = {"email": ESKIZ_EMAIL, "password": ESKIZ_PASSWORD} response = requests.post(url=url, data=data) if response.status_code == 200: - return response.json() - return None + return response.json()["data"]["token"] + + send_telegram_message(response.text) + raise NotImplementedError(response.text) + + +def get_token() -> str: + eskiz = EskizServiceConfig.objects.first() + now = timezone.now() + if not eskiz or not eskiz.token: + eskiz = EskizServiceConfig.objects.create( + token=_create_token(), expires_at=now + timedelta(days=29) + ) -# Removed from provider API -# def delete_token(token): -# url = f'http://{ESKIZ_URL}/auth/invalidate' + if eskiz.expires_at <= now: + token = _create_token() + eskiz.refresh_token(token) -# headers = { -# "Authorization": f"Bearer {token}" -# } -# response = requests.delete(url=url, headers=headers) -# return response + return eskiz.token def get_balance(token: str): - url = f"http://{ESKIZ_URL}/user/get-limit" + url = f"https://{ESKIZ_URL}/user/get-limit" headers = {"Authorization": f"Bearer {token}"} response = requests.get(url=url, headers=headers) @@ -37,7 +49,7 @@ def get_balance(token: str): def get_nickname(token: str) -> str: - url = f"http://{ESKIZ_URL}/nick/me" + url = f"https://{ESKIZ_URL}/nick/me" headers = {"Authorization": f"Bearer {token}"} response = requests.get(url=url, headers=headers) @@ -51,7 +63,7 @@ def get_nickname(token: str) -> str: def send_message(phone: str, message: str, token: str, nick: str): - url = f"http://{ESKIZ_URL}/message/sms/send" + url = f"https://{ESKIZ_URL}/message/sms/send" data = { "mobile_phone": phone, diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..517cc0d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,10 @@ +[tool.black] +exclude = ''' +/( + | migrations + | venv + | env + | .venv + | .env +)/ +''' \ No newline at end of file