Added API key verification for permissions
This commit is contained in:
@@ -84,7 +84,7 @@ path_separator = os
|
||||
# database URL. This is consumed by the user-maintained env.py script only.
|
||||
# other means of configuring database URLs may be customized within the env.py
|
||||
# file.
|
||||
sqlalchemy.url = sqlite+aiosqlite:///./database/dbs/stcs.db
|
||||
sqlalchemy.url = sqlite+aiosqlite:///./database/stcs.db
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
|
||||
32
alembic/versions/f6e7eb3f25c0_initial.py
Normal file
32
alembic/versions/f6e7eb3f25c0_initial.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""initial
|
||||
|
||||
Revision ID: f6e7eb3f25c0
|
||||
Revises:
|
||||
Create Date: 2025-11-12 22:53:02.189445
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'f6e7eb3f25c0'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
pass
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
pass
|
||||
# ### end Alembic commands ###
|
||||
@@ -38,7 +38,7 @@ async def get_active_positions(tg_id: int) -> list | None:
|
||||
return None
|
||||
|
||||
|
||||
async def get_active_positions_by_symbol(tg_id: int, symbol: str) -> dict | None:
|
||||
async def get_active_positions_by_symbol(tg_id: int, symbol: str):
|
||||
"""
|
||||
Get active positions for a user by symbol
|
||||
"""
|
||||
@@ -62,6 +62,10 @@ async def get_active_positions_by_symbol(tg_id: int, symbol: str) -> dict | None
|
||||
)
|
||||
return None
|
||||
except Exception as e:
|
||||
errors = str(e)
|
||||
if errors.startswith("Permission denied, please check your API key permissions"):
|
||||
return "Invalid API key permissions"
|
||||
else:
|
||||
logger.error("Error getting active positions for user %s: %s", tg_id, e)
|
||||
return None
|
||||
|
||||
|
||||
@@ -109,6 +109,7 @@ async def start_trading_cycle(
|
||||
"The number of contracts exceeds maximum limit allowed",
|
||||
"The number of contracts exceeds minimum limit allowed",
|
||||
"Order placement failed as your position may exceed the max",
|
||||
"Permission denied, please check your API key permissions"
|
||||
}
|
||||
else None
|
||||
)
|
||||
@@ -371,6 +372,7 @@ async def open_positions(
|
||||
"The number of contracts exceeds maximum limit allowed": "The number of contracts exceeds maximum limit allowed",
|
||||
"The number of contracts exceeds minimum limit allowed": "The number of contracts exceeds minimum limit allowed",
|
||||
"Order placement failed as your position may exceed the max": "Order placement failed as your position may exceed the max",
|
||||
"Permission denied, please check your API key permissions": "Permission denied, please check your API key permissions"
|
||||
}
|
||||
for key, msg in known_errors.items():
|
||||
if key in error_text:
|
||||
|
||||
@@ -37,7 +37,7 @@ async def user_profile_bybit(tg_id: int, message: Message, state: FSMContext) ->
|
||||
)
|
||||
else:
|
||||
await message.answer(
|
||||
text="Ошибка при подключении к платформе. Проверьте ключи и повторите попытку.",
|
||||
text="Ошибка при подключении к платформе. Проверьте корректность и разрешения API ключа и добавьте повторно.",
|
||||
reply_markup=kbi.connect_the_platform,
|
||||
)
|
||||
logger.error("Error processing user profile for user %s", tg_id)
|
||||
|
||||
@@ -299,6 +299,12 @@ async def settings_for_margin_type(
|
||||
deals = await get_active_positions_by_symbol(
|
||||
tg_id=callback_query.from_user.id, symbol=symbol
|
||||
)
|
||||
if deals == "Invalid API key permissions":
|
||||
await callback_query.answer(
|
||||
text="API ключ не имеет достаточных прав для смены маржи",
|
||||
)
|
||||
return
|
||||
|
||||
position = next((d for d in deals if d.get("symbol") == symbol), None)
|
||||
|
||||
if position:
|
||||
@@ -676,6 +682,15 @@ async def set_leverage_handler(message: Message, state: FSMContext) -> None:
|
||||
|
||||
await state.clear()
|
||||
except Exception as e:
|
||||
errors_text = str(e)
|
||||
known_errors = {
|
||||
"Permission denied, please check your API key permissions": "API ключ не имеет достаточных прав для установки кредитного плеча"
|
||||
|
||||
}
|
||||
for key, msg in known_errors.items():
|
||||
if key in errors_text:
|
||||
await message.answer(msg, reply_markup=kbi.back_to_additional_settings)
|
||||
else:
|
||||
await message.answer(
|
||||
text="Произошла ошибка при установке кредитного плеча. Пожалуйста, попробуйте позже.",
|
||||
reply_markup=kbi.back_to_additional_settings,
|
||||
|
||||
@@ -38,6 +38,12 @@ async def start_trading(callback_query: CallbackQuery, state: FSMContext) -> Non
|
||||
deals = await get_active_positions_by_symbol(
|
||||
tg_id=callback_query.from_user.id, symbol=symbol
|
||||
)
|
||||
if deals == "Invalid API key permissions":
|
||||
await callback_query.answer(
|
||||
text="API ключ не имеет достаточных прав для запуска торговли",
|
||||
)
|
||||
return
|
||||
|
||||
position = next((d for d in deals if d.get("symbol") == symbol), None)
|
||||
|
||||
if position:
|
||||
@@ -109,7 +115,9 @@ async def start_trading(callback_query: CallbackQuery, state: FSMContext) -> Non
|
||||
"The number of contracts exceeds minimum limit allowed": "️️Лимит ставки меньше минимально допустимого",
|
||||
"Order placement failed as your position may exceed the max":
|
||||
"Не удалось разместить ордер, так как ваша позиция может превышать максимальный лимит."
|
||||
"Пожалуйста, уменьшите кредитное плечо, чтобы увеличить максимальное значение"
|
||||
"Пожалуйста, уменьшите кредитное плечо, чтобы увеличить максимальное значение",
|
||||
"Permission denied, please check your API key permissions": "API ключ не имеет достаточных прав для запуска торговли"
|
||||
|
||||
}
|
||||
|
||||
if res == "OK":
|
||||
@@ -131,6 +139,15 @@ async def start_trading(callback_query: CallbackQuery, state: FSMContext) -> Non
|
||||
await add_start_task_merged(user_id=callback_query.from_user.id, task=task)
|
||||
|
||||
except Exception as e:
|
||||
error_text = str(e)
|
||||
known_errors = {
|
||||
"Permission denied, please check your API key permissions": "API ключ не имеет достаточных прав для запуска торговли"
|
||||
|
||||
}
|
||||
for key, msg in known_errors.items():
|
||||
if key in error_text:
|
||||
await callback_query.answer(msg)
|
||||
else:
|
||||
await callback_query.answer(text="Произошла ошибка при запуске торговли")
|
||||
logger.error(
|
||||
"Error processing command start_trading for user %s: %s",
|
||||
|
||||
Reference in New Issue
Block a user