105 lines
2.2 KiB
Go
105 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/go-telegram/bot"
|
|
"github.com/go-telegram/bot/models"
|
|
)
|
|
|
|
func (appCtx *App) LoggingMiddleware() bot.Middleware {
|
|
return func(next bot.HandlerFunc) bot.HandlerFunc {
|
|
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
|
|
|
var chatID int64
|
|
var text string
|
|
|
|
if update.Message != nil {
|
|
chatID = update.Message.Chat.ID
|
|
text = update.Message.Text
|
|
} else {
|
|
chatID = 0
|
|
text = "<no message>"
|
|
}
|
|
|
|
appCtx.logger.Debug(
|
|
"Update received",
|
|
"module", "Bot",
|
|
"chat_id", chatID,
|
|
"text", text,
|
|
)
|
|
|
|
next(ctx, b, update)
|
|
|
|
appCtx.logger.Debug(
|
|
"Update processed",
|
|
"module", "Bot",
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (appCtx *App) RecoveryMiddleware() bot.Middleware {
|
|
return func(next bot.HandlerFunc) bot.HandlerFunc {
|
|
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
appCtx.logger.Error(
|
|
"Recovered from panic",
|
|
"module", "Bot",
|
|
"panic", r,
|
|
)
|
|
}
|
|
}()
|
|
next(ctx, b, update)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (appCtx *App) AuthMiddleware() bot.Middleware {
|
|
return func(next bot.HandlerFunc) bot.HandlerFunc {
|
|
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
|
|
|
var user *models.User
|
|
var chatID int64
|
|
|
|
if update.Message != nil && update.Message.From != nil {
|
|
user = update.Message.From
|
|
chatID = update.Message.Chat.ID
|
|
|
|
} else if update.CallbackQuery != nil {
|
|
|
|
if update.CallbackQuery.Message.Message == nil {
|
|
return
|
|
}
|
|
|
|
user = &update.CallbackQuery.From
|
|
chatID = update.CallbackQuery.Message.Message.Chat.ID
|
|
|
|
} else {
|
|
return
|
|
}
|
|
|
|
// Bootstrap primer usuario
|
|
if appCtx.store.IsEmpty() {
|
|
if err := appCtx.store.FirstUser(user.ID); err != nil {
|
|
appCtx.logger.Error("Failed to save first user", "error", err)
|
|
} else {
|
|
appCtx.logger.Info("First user registered", "user_id", user.ID)
|
|
}
|
|
next(ctx, b, update)
|
|
return
|
|
}
|
|
|
|
// Autorización
|
|
if !appCtx.store.IsAllowed(user.ID) {
|
|
appCtx.logger.Warn("Unauthorized access", "user_id", user.ID, "chat_id", chatID)
|
|
appCtx.sendMessage(ctx, b, chatID, appCtx.T("i.auth.unauthorized"), true, nil)
|
|
return
|
|
}
|
|
|
|
next(ctx, b, update)
|
|
}
|
|
}
|
|
}
|