diff options
Diffstat (limited to 'src/middleware.ts')
| -rw-r--r-- | src/middleware.ts | 53 |
1 files changed, 50 insertions, 3 deletions
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<void>): Promise<void> => { +const tgAuth = async (ctx: Context, next: () => Promise<void>): Promise<void> => { const userId = ctx.message?.from.id; const tgUsers = await getPermittedUsers(); @@ -14,8 +18,51 @@ const auth = async (ctx: Context, next: () => Promise<void>): Promise<void> => { } }; +const verifyGoogleJWT = 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) { + 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<string, string> = 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, +}; |
