From 64608e0137b89682bcbdd62aec2c82ac10b55138 Mon Sep 17 00:00:00 2001 From: Tim Raderschad Date: Wed, 28 Aug 2024 21:16:37 +0200 Subject: [PATCH] fix(web): hono auth middleware --- apps/web/src/api/helpers.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/apps/web/src/api/helpers.ts b/apps/web/src/api/helpers.ts index 9437a4e0..10422419 100644 --- a/apps/web/src/api/helpers.ts +++ b/apps/web/src/api/helpers.ts @@ -1,7 +1,9 @@ +import { env } from "env/server.mjs"; import type { Context, MiddlewareHandler } from "hono"; import { getCookie } from "hono/cookie"; import type { GetServerSidePropsContext } from "next"; import type { DefaultSession } from "next-auth"; +import { decode } from "next-auth/jwt"; import { getServerAuthSession } from "server/common/get-server-auth-session"; import type { UserSession } from "types/next-auth"; @@ -24,7 +26,15 @@ export const authMiddleware: MiddlewareHandler<{ user: UserSession & DefaultSession["user"]; }; }> = async (c, next) => { - const session = await getHonoSession(c); + const tokenCookie = getCookie(c, "next-auth.session-token"); + if (!tokenCookie) return next(); + if (!env.NEXTAUTH_SECRET) { + throw new Error("NEXTAUTH_SECRET is not set"); + } + const session = await decode({ + secret: env.NEXTAUTH_SECRET, + token: tokenCookie, + }); if (!session || !session.user) { return c.json({ error: "Unauthorized" }, { status: 401 }); }