aboutsummaryrefslogtreecommitdiffstats
path: root/src/middleware.ts
blob: 98d5688d11bed3f9e897145b619115baa283be33 (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
import { Request, Response } from "@tinyhttp/app";
import { Context } from "telegraf";
import config from "./config";

import { getPermittedUsers } from "./db";

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);
    return;
  }

  const token = authHeader.split(" ")[1];
  if (!token || token !== config.authToken) {
    res.sendStatus(401);
    return;
  }

  next();
}

export {
  tgAuth,
  httpHeaderAuth,
};