Files
web/apps/scandic-web/components/ProtectedLayout.tsx
Linus Flood 4b3dbadf24 Merged in feat/sw-3610-basicProfile (pull request #3144)
Feat(SW-3610): basic profile endpoint on protected layouts

* Basic profile in protected layouts

* .


Approved-by: Anton Gunnarsson
2025-11-13 07:35:16 +00:00

61 lines
1.7 KiB
TypeScript

import { TRPCError } from "@trpc/server"
import { headers } from "next/headers"
import { redirect } from "next/navigation"
import { overview } from "@scandic-hotels/common/constants/routes/myPages"
import { logger } from "@scandic-hotels/common/logger"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { isValidSession } from "@scandic-hotels/trpc/utils/session"
import { getBasicProfile } from "@/lib/trpc/memoizedRequests"
import { auth } from "@/auth"
import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"
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 headersList = await headers()
const lang = await getLang()
const redirectTo = encodeURIComponent(
headersList.get("x-url") ?? headersList.get("x-pathname") ?? overview[lang]
)
const redirectURL = `/${lang}/login?redirectTo=${redirectTo}`
if (!isValidSession(session)) {
logger.debug(
`[layout:protected] no session, redirecting to: ${redirectURL}`
)
redirect(redirectURL)
}
const [user, error] = await safeTry(getBasicProfile())
if (error instanceof TRPCError && error.code === "INTERNAL_SERVER_ERROR") {
return (
<p>
{intl.formatMessage({
id: "errorMessage.somethingWentWrong",
defaultMessage: "Something went wrong!",
})}
</p>
)
}
if (!user) {
logger.error(
"[layout:protected] no user found, redirecting to: ",
redirectURL
)
redirect(redirectURL)
}
return children
}