Access rights verification - best practices #2276
-
Hello everyone, I am writing to ask about the best practices for implementing access rights verification for my bot. My bot should only respond to commands from users whose ID is on a list of allowed IDs. For everyone else, it should give a message about lack of access. I have implemented this using middleware, but I noticed that it does not seem to work for Thank you for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
What is your problem with middlewares? Add inline_query to update_types? |
Beta Was this translation helpful? Give feedback.
-
The issue is that the middleware in my setup is not processing the incoming request from the bot as expected. I have explicitly removed the bot's ID from the list of allowed users, but the lock is still not working: 2024-05-20 16:37:37 - pyTMbot - INFO - Request from: **********, user_id *********. Accepted. [auth.py | pre_process:34]
2024-05-20 16:37:37 - pyTMbot - INFO - Start handling session. User: ********, user_id: *********, lang: ru, is_bot: False [memory_handler.py | get_memory:59]
2024-05-20 16:37:39 - pyTMbot - INFO - Start handling session. User: ******_bot, user_id: ************, lang: None, is_bot: True [swap_handler.py | swap:24] At the same time, if you exclude the user ID from the list of allowed IDs, the lock will work correctly. In other words, it is only for bots. 2024-05-20 16:44:15 - pyTMbot - ERROR - Request from: ************ user_id ***********. Ignored. Reason: user_id not allowed (see BotSettings class in app/settings/bot_settings.py) [auth.py | pre_process:42] The middleware setup process is as follows: def build_bot_instance() -> telebot.TeleBot:
"""Build PyTMBot instance"""
bot_mode = parse_cli_args()
match bot_mode.mode:
case "dev":
configured_bot = telebot.TeleBot(
config.dev_bot_token.get_secret_value(),
use_class_middlewares=True,
exception_handler=CustomExceptionHandler()
)
case "prod":
configured_bot = telebot.TeleBot(
config.bot_token.get_secret_value(),
use_class_middlewares=True,
exception_handler=CustomExceptionHandler()
)
case _:
raise ValueError(f"Invalid PyTMBot mode: {bot_mode.mode}, use -h option to see more")
return configured_bot And middleware registration: def run_bot(self):
"""Run the bot"""
try:
self.bot.setup_middleware(AllowedUser())
self.handler.run_handlers()
bot_logger.info(f"New instance started! PyTMBot v.{__version__} ({__repository__})")
self._start_polling()
except ConnectionError as e:
bot_logger.error(f"Connection error.: {e}", exc_info=False) |
Beta Was this translation helpful? Give feedback.
-
Did you add inline_query to update_types in middleware? |
Beta Was this translation helpful? Give feedback.
-
I'm not paying attention. Indeed, I only added I will add Thank you very much! |
Beta Was this translation helpful? Give feedback.
Did you add inline_query to update_types in middleware?