diff --git a/apps/infoalloggi/src/pages/api/stripe-webhook.ts b/apps/infoalloggi/src/pages/api/stripe-webhook.ts index 24dc0eb..d36e023 100644 --- a/apps/infoalloggi/src/pages/api/stripe-webhook.ts +++ b/apps/infoalloggi/src/pages/api/stripe-webhook.ts @@ -4,17 +4,13 @@ import { env } from "~/env"; import stripe from "~/lib/stripe"; import type { PaymentsId } from "~/schemas/public/Payments"; import { appRouter } from "~/server/api/root"; -import { createTRPCContext, t } from "~/server/api/trpc"; +import { addApiAuthToContext, createTRPCContext, t } from "~/server/api/trpc"; const handler = async ( req: NextApiRequest, res: NextApiResponse, ): Promise => { if (req.method === "POST") { - const ctx = await createTRPCContext({ req: req, res: res }); - const createCaller = t.createCallerFactory(appRouter); - const caller = createCaller(ctx); - const sig = req.headers["stripe-signature"]; let event: Stripe.Event; @@ -34,6 +30,10 @@ const handler = async ( res.status(400).send(`Webhook Error: ${(err as Error).message}`); return; } + const ctx = await createTRPCContext({ req: req, res: res }); + addApiAuthToContext(ctx); + const createCaller = t.createCallerFactory(appRouter); + const caller = createCaller(ctx); // Handle the event switch (event.type) { diff --git a/apps/infoalloggi/src/server/api/trpc.ts b/apps/infoalloggi/src/server/api/trpc.ts index 3a5d42c..8d86df0 100644 --- a/apps/infoalloggi/src/server/api/trpc.ts +++ b/apps/infoalloggi/src/server/api/trpc.ts @@ -75,8 +75,19 @@ export const createTRPCContext = async ({ res, }; }; - export type Context = Awaited>; +export const addApiAuthToContext = (ctx: Context) => { + if (!ctx.req || !ctx.res) { + throw new Error( + "You are missing `req` or `res` in your call to addApiAuthToContext.", + ); + } + const authString = Buffer.from( + `${env.EXP_API_USER}:${env.EXP_API_PASS}`, + ).toString("base64"); + ctx.req.headers.authorization = `Basic ${authString}`; + return ctx; +}; /** * 2. INITIALIZATION @@ -185,7 +196,9 @@ const enforceUserIsAuthedOrOverride = t.middleware(({ ctx, next, path }) => { * @see https://trpc.io/docs/procedures */ export const protectedProcedure = t.procedure.use(enforceUserIsAuthed); -export const overridableProcedure = t.procedure.use(enforceUserIsAuthedOrOverride); +export const overridableProcedure = t.procedure.use( + enforceUserIsAuthedOrOverride, +); /** Reusable middleware that enforces users are logged in before running the procedure. */ const enforceUserIsAdmin = t.middleware(({ ctx, next, path }) => {