aboutsummaryrefslogtreecommitdiffstats
path: root/src/middleware.ts
blob: 6c5635211d5b384a96859e22da7eb1b3a5e975a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * Telegram-only middleware utilities.
 */

import { Context } from "telegraf";
import { getPermittedUsers } from "./db";

/**
 * 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.from?.id;
  if (!userId) {
    await ctx.reply("Käyttäjätunnusta ei voitu lukea (user id puuttuu).");
    return;
  }

  try {
    const permitted = await getPermittedUsers();
    const permittedIds = new Set(permitted.map((u) => u.id));

    if (!permittedIds.has(userId)) {
      await ctx.reply("Käyttäjälläsi ei ole oikeuksia käyttää HommaBottia.");
      return;
    }

    await next();
  } catch (err) {
    console.error("[tgAuth] Authorization check failed:", err);
    await ctx.reply("Odottamaton virhe luvituksessa.");
  }
};