diff options
| author | Jan Tuomi <jan@jantuomi.fi> | 2025-10-07 13:04:03 +0300 |
|---|---|---|
| committer | Jan Tuomi <jan@jantuomi.fi> | 2025-10-07 16:03:28 +0300 |
| commit | b0db0e55c0c400bc948a4934b0e4fddfbfdcca51 (patch) | |
| tree | 0d29e8015178a0eaa52e9f821ad243c5435da99f /src/middleware.ts | |
| parent | fe57e4996ec79267dffd77e503ef8164eceea229 (diff) | |
Rewrite to run as a traditional script, update deps
Diffstat (limited to 'src/middleware.ts')
| -rw-r--r-- | src/middleware.ts | 67 |
1 files changed, 38 insertions, 29 deletions
diff --git a/src/middleware.ts b/src/middleware.ts index 98d5688..589022f 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,39 +1,48 @@ -import { Request, Response } from "@tinyhttp/app"; -import { Context } from "telegraf"; -import config from "./config"; +/** + * Telegram-only middleware utilities. + * + * HTTP server functionality has been removed, so any HTTP-specific middleware + * (e.g. header-based auth) has been deleted. + * + * This module currently exposes: + * tgAuth - Ensures that only permitted Telegram user IDs can invoke bot commands. + */ +import { Context } from "telegraf"; import { getPermittedUsers } from "./db"; -const tgAuth = async (ctx: Context, next: () => Promise<void>): Promise<void> => { +/** + * Telegram authorization middleware. + * + * Logic: + * 1. Extract the Telegram user ID from the incoming context. + * 2. Load the list of permitted user IDs from the SQLite database. + * 3. If the user ID is not present, reply with an authorization failure message + * and do NOT call next(). + * 4. Otherwise, continue to the next middleware/handler. + */ +export const tgAuth = async ( + ctx: Context, + next: () => Promise<void>, +): Promise<void> => { const userId = ctx.message?.from.id; - - const tgUsers = await getPermittedUsers(); - const tgUserIds = tgUsers.map(u => u.id); - - if (!userId || !tgUserIds.includes(userId)) { - ctx.reply("Käyttäjälläsi ei ole oikeuksia startata HommaBottia."); - } else { - await next(); - } -}; - -const httpHeaderAuth = async (req: Request, res: Response, next: () => void): Promise<void> => { - const authHeader = req.headers.authorization || null; - if (!authHeader) { - res.sendStatus(401); + if (!userId) { + await ctx.reply("Käyttäjätunnusta ei voitu lukea (user id puuttuu)."); return; } - const token = authHeader.split(" ")[1]; - if (!token || token !== config.authToken) { - res.sendStatus(401); - return; - } + try { + const permitted = await getPermittedUsers(); + const permittedIds = new Set(permitted.map((u) => u.id)); - next(); -} + if (!permittedIds.has(userId)) { + await ctx.reply("Käyttäjälläsi ei ole oikeuksia käyttää HommaBottia."); + return; + } -export { - tgAuth, - httpHeaderAuth, + await next(); + } catch (err) { + console.error("[tgAuth] Authorization check failed:", err); + await ctx.reply("Odottamaton virhe valtuutuksessa."); + } }; |
