From 7991ad93470cf42b9c4c96477fc920bbb8899eee Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Sun, 7 Nov 2021 22:13:49 +0200 Subject: Prepare for move to DO --- .dockerignore | 1 + Dockerfile | 1 + docker-compose.yml | 4 +++- src/config.ts | 2 ++ src/index.ts | 9 ++++++--- src/middleware.ts | 47 ++++++----------------------------------------- src/tg.ts | 4 ++-- 7 files changed, 21 insertions(+), 47 deletions(-) diff --git a/.dockerignore b/.dockerignore index c85b5de..e790acd 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,3 +2,4 @@ Dockerfile .dockerignore .gitignore .git/ +node_modules/ diff --git a/Dockerfile b/Dockerfile index a47288a..b62d30e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,5 +20,6 @@ ENV NODE_ENV production COPY --from=builder /app/build ./build COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/package.json ./package.json +COPY ./sql ./sql CMD ["npm", "run", "start"] diff --git a/docker-compose.yml b/docker-compose.yml index dc39ea7..d82dd22 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,9 +12,11 @@ services: - ./sql:/sql hommabot2: build: . - image: eu.gcr.io/jan-systems/hommabot2:latest + image: registry.digitalocean.com/jan-systems-registry/hommabot2:latest + env_file: .env environment: PORT: 3000 + PG_CONNECTION_URI: postgresql://postgres:postgres@db/postgres ports: - 3000:3000 diff --git a/src/config.ts b/src/config.ts index ca60b97..4e034fa 100644 --- a/src/config.ts +++ b/src/config.ts @@ -15,6 +15,7 @@ class ConfigError extends Error { const nodeEnv = process.env.NODE_ENV || "development"; const port = process.env.PORT ? Number(process.env.PORT) : 3000; +const authToken = process.env.AUTH_TOKEN || ""; const tgWebhookUrl = process.env.TELEGRAM_WEBHOOK_URL || null; if (!tgWebhookUrl) { @@ -55,6 +56,7 @@ fs.writeFileSync(googleSaJsonPath, googleSaJsonUtf8); const config = { nodeEnv, port, + authToken, tgWebhookUrl, tgBotToken, sheetsSpreadsheetId, diff --git a/src/index.ts b/src/index.ts index 773ae3c..b675584 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,9 +2,9 @@ import { App } from "@tinyhttp/app"; import { logger } from "@tinyhttp/logger"; import bodyParser from "body-parser"; import config from "./config"; -import { httpMiddleware } from "./middleware"; import { buildSheetsClient } from "./sheets"; import { bot, broadcastMessage } from "./tg"; +import { httpHeaderAuth } from "./middleware"; const main = async () => { const sheets = await buildSheetsClient(); @@ -27,7 +27,7 @@ const main = async () => { .get("/", async (_, res) => { res.send({ service: "hommabot2 API" }); }) - .post("/scheduler/trigger", httpMiddleware.verifyGoogleJWT, async (_req, res) => { + .post("/scheduler/trigger", httpHeaderAuth, async (_req, res) => { try { const sheetData = await sheets.fetchSheetData(); const entries = sheets.processRows(sheetData); @@ -38,8 +38,11 @@ const main = async () => { const taskText = tasks.join("\n"); const msg = `Tällä viikolla tehtävät hommat:\n${taskText}`; await broadcastMessage(msg); + console.log("Broadcasted message:", msg); } else { - await broadcastMessage("Tällä viikolla ei toistuvia hommia! 🎉"); + const msg = "Tällä viikolla ei toistuvia hommia! 🎉"; + await broadcastMessage(msg); + console.log("Broadcasted message:", msg); } const newDateStamps = sheets.updatedLastDoneDateStamps(entries); diff --git a/src/middleware.ts b/src/middleware.ts index 46d6e00..98d5688 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,10 +1,8 @@ import { Request, Response } from "@tinyhttp/app"; import { Context } from "telegraf"; -import got from "got"; -import jwt from "jsonwebtoken"; +import config from "./config"; import { getPermittedUsers } from "./db"; -import config from "./config"; const tgAuth = async (ctx: Context, next: () => Promise): Promise => { const userId = ctx.message?.from.id; @@ -19,12 +17,7 @@ const tgAuth = async (ctx: Context, next: () => Promise): Promise => } }; -const verifyGoogleJWT = async (req: Request, res: Response, next: () => void): Promise => { - if (config.nodeEnv !== "production") { - next(); - return; - } - +const httpHeaderAuth = async (req: Request, res: Response, next: () => void): Promise => { const authHeader = req.headers.authorization || null; if (!authHeader) { res.sendStatus(401); @@ -32,43 +25,15 @@ const verifyGoogleJWT = async (req: Request, res: Response, next: () => void): P } const token = authHeader.split(" ")[1]; - if (!token) { + if (!token || token !== config.authToken) { res.sendStatus(401); return; } - const decoded = jwt.decode(token, { complete: true }); - if (!decoded) { - res.sendStatus(401); - return; - } - - const kid: string = decoded.header.kid; - - const response = await got("https://www.googleapis.com/oauth2/v1/certs", { json: true }); - const googleCerts: Record = response.body; - - const cert = googleCerts[kid]; - if (!cert) { - console.error("KID not found in google certificates"); - res.sendStatus(500); - return; - } - - try { - jwt.verify(token, cert); - } catch (err) { - res.sendStatus(403); - return; - } - next(); -}; +} -export const tgMiddleware = { +export { tgAuth, -}; - -export const httpMiddleware = { - verifyGoogleJWT, + httpHeaderAuth, }; diff --git a/src/tg.ts b/src/tg.ts index 45c60c7..4850c88 100644 --- a/src/tg.ts +++ b/src/tg.ts @@ -1,12 +1,12 @@ import { Telegraf } from "telegraf"; import config from "./config"; import { addActiveChat, getActiveChats, removeActiveChat } from "./db"; -import { tgMiddleware } from "./middleware"; +import { tgAuth } from "./middleware"; console.log(`Setting up Telegram bot with token ${config.tgBotToken}`); const bot = new Telegraf(config.tgBotToken); -bot.use(tgMiddleware.tgAuth); +bot.use(tgAuth); bot.command("/start", async (ctx) => { await addActiveChat(ctx.chat.id); -- cgit v1.3