Add more security in webhooks

This commit is contained in:
2024-08-07 02:38:33 +03:00
parent a8f39d4630
commit 3b12868201
3 changed files with 26 additions and 16 deletions
+13 -13
View File
@@ -1,35 +1,35 @@
from flask import Flask, Blueprint, request, abort, g
from flask import Flask, request, abort, g
from telebot import TeleBot
from telebot.types import Update
from ..config import Config
bot_bp = Blueprint("bot", __name__)
@bot_bp.route("/", methods=["GET", "POST"])
def handle_updates():
if request.method == "GET":
abort(404)
abort(404) # safer to 404
if g.config.webhook.use_secret_token:
if request.headers.get("X-Telegram-Bot-Api-Secret-Token") != g.config.webhook.secret_token:
abort(404)
if request.headers.get("content-type") == "application/json":
update = Update.de_json(request.get_json())
g.bot.process_new_updates([update])
return ""
else:
abort(403)
abort(404) # safer to 404
def inject_g(bot: TeleBot, config: Config):
def inject_g(**kwargs):
def inner():
g.bot = bot
g.config = config
for k, v in kwargs.items():
setattr(g, k, v)
return inner
def create_app(bot: TeleBot, config: Config):
app = Flask(__name__)
app.register_blueprint(bot_bp, url_prefix=f"{config.webhook.url_path}")
app.before_request(inject_g(bot, config))
app.add_url_rule(config.webhook.url_path,
view_func=handle_updates,
methods=["GET", "POST"])
app.before_request(inject_g(bot=bot, config=config))
return app