fix: refactor session handling

This commit is contained in:
Christel Westerberg
2024-05-28 14:41:05 +02:00
parent cd3c5491ec
commit 07f81c34e3
7 changed files with 34 additions and 36 deletions
+15 -2
View File
@@ -1,11 +1,16 @@
import { cookies, headers } from "next/headers"
import { type Session } from "next-auth"
import { Lang } from "@/constants/languages"
import { auth } from "@/auth"
import { unauthorizedError } from "./errors/trpc"
typeof auth
type CreateContextOptions = {
auth: typeof auth
auth: () => Promise<Session>
lang: Lang
pathname: string
uid?: string | null
@@ -39,7 +44,15 @@ export function createContext() {
const webviewTokenCookie = cookie.get("webviewToken")
return createContextInner({
auth,
auth: async () => {
const session = await auth()
const webToken = webviewTokenCookie?.value
if (!session?.token && !webToken) {
throw unauthorizedError()
}
return session || ({ token: { access_token: webToken } } as Session)
},
lang: h.get("x-lang") as Lang,
pathname: h.get("x-pathname")!,
uid: h.get("x-uid"),
+1 -5
View File
@@ -41,13 +41,9 @@ export const protectedProcedure = t.procedure.use(async function (opts) {
throw sessionExpiredError()
}
if (!session?.token.access_token && !opts.ctx.webToken) {
throw unauthorizedError()
}
return opts.next({
ctx: {
session: session || { token: { access_token: opts.ctx.webToken } },
session,
},
})
})