Files
web/app/[lang]/(live)/(protected)/layout.tsx
2024-08-26 15:40:37 +02:00

67 lines
1.8 KiB
TypeScript

import { headers } from "next/headers"
import { redirect } from "next/navigation"
import { overview } from "@/constants/routes/myPages"
import { serverClient } from "@/lib/trpc/server"
import { auth } from "@/auth"
import { getLang } from "@/i18n/serverContext"
export default async function ProtectedLayout({
children,
}: React.PropsWithChildren) {
const session = await auth()
/**
* Fallback to make sure every route nested in the
* protected route group is actually protected.
*/
const h = headers()
const redirectTo = encodeURIComponent(
h.get("x-url") ?? h.get("x-pathname") ?? overview[getLang()]
)
const redirectURL = `/${getLang()}/login?redirectTo=${redirectTo}`
if (!session) {
console.log(`[layout:protected] no session, redirecting to: ${redirectURL}`)
redirect(redirectURL)
}
const user = await serverClient().user.get()
if (user && "error" in user) {
// redirect(redirectURL)
console.error("[layout:protected] error in user", user)
console.error(
"[layout:protected] full user: ",
JSON.stringify(user, null, 4)
)
switch (user.cause) {
case "unauthorized": // fall through
case "forbidden": // fall through
case "token_expired":
console.error(
`[layout:protected] user error, redirecting to: ${redirectURL}`
)
redirect(redirectURL)
case "notfound":
console.error(`[layout:protected] notfound user loading error`)
case "unknown":
console.error(`[layout:protected] unknown user loading error`)
default:
console.error(`[layout:protected] unhandled user loading error`)
}
return <p>Something went wrong!</p>
}
if (!user) {
console.error(
"[layout:protected] no user found, redirecting to: ",
redirectURL
)
redirect(redirectURL)
}
return children
}