Skip to content

Commit

Permalink
fixed issue while sending request, added refreshing token instead of …
Browse files Browse the repository at this point in the history
…recreating it
  • Loading branch information
aabduvak committed Jun 28, 2024
1 parent f0989ba commit ad67c8f
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 24 deletions.
5 changes: 0 additions & 5 deletions api/bot/commands/sms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
4 changes: 0 additions & 4 deletions api/management/commands/send_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
36 changes: 36 additions & 0 deletions api/migrations/0020_eskizserviceconfig.py
Original file line number Diff line number Diff line change
@@ -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,
},
),
]
17 changes: 17 additions & 0 deletions api/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import uuid
from datetime import datetime, timedelta
from django.utils import timezone
from django.db import models


Expand Down Expand Up @@ -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()
42 changes: 27 additions & 15 deletions api/utils/eskiz.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,55 @@
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)
return response.json()


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)
Expand All @@ -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,
Expand Down
10 changes: 10 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[tool.black]
exclude = '''
/(
| migrations
| venv
| env
| .venv
| .env
)/
'''

0 comments on commit ad67c8f

Please sign in to comment.