mirror of
https://github.com/complexcaresolutions/telegram-media-bot.git
synced 2026-03-17 15:03:42 +00:00
feat: add auth middleware and bot setup with session and rate limiting
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
e5dd5c6257
commit
a58d6f31fa
2 changed files with 74 additions and 0 deletions
57
src/bot.ts
Normal file
57
src/bot.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { Bot, session, type Context, type SessionFlavor } from 'grammy';
|
||||
import { config } from './config.js';
|
||||
import { authMiddleware } from './middleware/auth.js';
|
||||
import { createLogger } from './utils/logger.js';
|
||||
|
||||
const log = createLogger('Bot');
|
||||
|
||||
interface SessionData {
|
||||
selectedTenantId: number;
|
||||
selectedTenantName: string;
|
||||
}
|
||||
|
||||
type BotContext = Context & SessionFlavor<SessionData>;
|
||||
|
||||
// Rate limiting: track uploads per user
|
||||
const uploadCounts = new Map<number, { count: number; resetAt: number }>();
|
||||
|
||||
function checkRateLimit(userId: number): { allowed: boolean; retryAfter?: number } {
|
||||
const now = Date.now();
|
||||
const entry = uploadCounts.get(userId);
|
||||
|
||||
if (!entry || entry.resetAt <= now) {
|
||||
uploadCounts.set(userId, { count: 1, resetAt: now + 60_000 });
|
||||
return { allowed: true };
|
||||
}
|
||||
|
||||
if (entry.count >= 10) {
|
||||
const retryAfter = Math.ceil((entry.resetAt - now) / 1000);
|
||||
return { allowed: false, retryAfter };
|
||||
}
|
||||
|
||||
entry.count++;
|
||||
return { allowed: true };
|
||||
}
|
||||
|
||||
function createBot(): Bot<BotContext> {
|
||||
const bot = new Bot<BotContext>(config.telegram.botToken);
|
||||
|
||||
// Session middleware
|
||||
bot.use(
|
||||
session({
|
||||
initial: (): SessionData => ({
|
||||
selectedTenantId: config.defaultTenantId,
|
||||
selectedTenantName: 'Default',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
// Auth middleware
|
||||
bot.use(authMiddleware);
|
||||
|
||||
log.info('Bot instance created');
|
||||
return bot;
|
||||
}
|
||||
|
||||
export { createBot, checkRateLimit };
|
||||
export type { BotContext, SessionData };
|
||||
17
src/middleware/auth.ts
Normal file
17
src/middleware/auth.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { type Context, type NextFunction } from 'grammy';
|
||||
import { config } from '../config.js';
|
||||
import { createLogger } from '../utils/logger.js';
|
||||
|
||||
const log = createLogger('Auth');
|
||||
|
||||
export async function authMiddleware(ctx: Context, next: NextFunction): Promise<void> {
|
||||
const userId = ctx.from?.id;
|
||||
|
||||
if (!userId || !config.telegram.allowedUserIds.includes(userId)) {
|
||||
log.warn(`Unauthorized access attempt from user ${userId || 'unknown'}`);
|
||||
await ctx.reply('⛔ Du bist nicht autorisiert, diesen Bot zu verwenden.');
|
||||
return;
|
||||
}
|
||||
|
||||
await next();
|
||||
}
|
||||
Loading…
Reference in a new issue