From 7f3a70c396b498a8b10553d11cf78c3ea9a872b1 Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Mon, 19 Apr 2021 14:51:34 +0300 Subject: Should be ready now --- src/middleware.ts | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 3 deletions(-) (limited to 'src/middleware.ts') diff --git a/src/middleware.ts b/src/middleware.ts index 9aa0775..8239121 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,7 +1,11 @@ +import { Request, Response } from "@tinyhttp/app"; import { Context } from "telegraf"; +import got from "got"; +import jwt from "jsonwebtoken"; + import { getPermittedUsers } from "./db"; -const auth = async (ctx: Context, next: () => Promise): Promise => { +const tgAuth = async (ctx: Context, next: () => Promise): Promise => { const userId = ctx.message?.from.id; const tgUsers = await getPermittedUsers(); @@ -14,8 +18,51 @@ const auth = async (ctx: Context, next: () => Promise): Promise => { } }; +const verifyGoogleJWT = async (req: Request, res: Response, next: () => void): Promise => { + const authHeader = req.headers.authorization || null; + if (!authHeader) { + res.sendStatus(401); + return; + } + + const token = authHeader.split(" ")[1]; + if (!token) { + 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 = { - auth, + tgAuth, }; -export const httpMiddleware = {}; +export const httpMiddleware = { + verifyGoogleJWT, +}; -- cgit v1.3