Files
web/apps/scandic-web/components/ProtectedLayout.tsx
Linus Flood ddefe2e59b Merged in fix/tracking-issue (pull request #1643)
Fix/tracking issue: add try/catch around promises

* Test

* Cleaning


Approved-by: Anton Gunnarsson
2025-03-26 12:59:59 +00:00

71 lines
2.0 KiB
TypeScript

import { headers } from "next/headers"
import { redirect } from "next/navigation"
import { overview } from "@/constants/routes/myPages"
import { getProfile } from "@/lib/trpc/memoizedRequests"
import { auth } from "@/auth"
import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"
import { isValidSession } from "@/utils/session"
export async function ProtectedLayout({ children }: React.PropsWithChildren) {
const intl = await getIntl()
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 (!isValidSession(session)) {
console.log(`[layout:protected] no session, redirecting to: ${redirectURL}`)
redirect(redirectURL)
}
const user = await getProfile()
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`)
break
case "unknown":
console.error(`[layout:protected] unknown user loading error`)
break
default:
console.error(`[layout:protected] unhandled user loading error`)
break
}
return <p>{intl.formatMessage({ id: "Something went wrong!" })}</p>
}
if (!user) {
console.error(
"[layout:protected] no user found, redirecting to: ",
redirectURL
)
redirect(redirectURL)
}
return children
}