feat(LOY-403): removed seamless login/logout * feat(LOY-403): removed seamless login/logout Approved-by: Joakim Jäderberg
64 lines
2.0 KiB
TypeScript
64 lines
2.0 KiB
TypeScript
import { type NextRequest, NextResponse } from "next/server"
|
|
import { AuthError } from "next-auth"
|
|
|
|
import { logger } from "@scandic-hotels/common/logger"
|
|
|
|
import { env } from "@/env/server"
|
|
import { internalServerError } from "@/server/errors/next"
|
|
import { getPublicURL } from "@/server/utils"
|
|
|
|
import { signOut } from "@/auth"
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const publicURL = getPublicURL(request)
|
|
|
|
let redirectTo: string = ""
|
|
|
|
logger.debug(
|
|
`[logout] source: ${request.headers.get("x-logout-source") || "normal"}`
|
|
)
|
|
|
|
const redirectToSearchParamValue =
|
|
request.nextUrl.searchParams.get("redirectTo")
|
|
const redirectToFallback = "/"
|
|
|
|
redirectTo = redirectToSearchParamValue || redirectToFallback
|
|
|
|
// Make relative URL to absolute URL
|
|
if (redirectTo.startsWith("/")) {
|
|
logger.debug(`[logout] make redirectTo absolute, from ${redirectTo}`)
|
|
redirectTo = new URL(redirectTo, publicURL).href
|
|
logger.debug(`[logout] make redirectTo absolute, to ${redirectTo}`)
|
|
}
|
|
|
|
try {
|
|
redirectTo = `${env.CURITY_ISSUER_USER}/authn/authenticate/logout?redirect_uri=${encodeURIComponent(redirectTo)}`
|
|
logger.debug(`[logout] final redirectUrl: ${redirectTo}`)
|
|
|
|
/**
|
|
* Passing `redirect: false` to `signOut` will return a result object
|
|
* instead of automatically redirecting inside of `signOut`.
|
|
* https://github.com/nextauthjs/next-auth/blob/3c035ec/packages/next-auth/src/lib/actions.ts#L104
|
|
*/
|
|
const redirectUrlObj = await signOut({
|
|
redirectTo,
|
|
redirect: false,
|
|
})
|
|
|
|
if (redirectUrlObj) {
|
|
logger.debug(`[logout] redirecting to: ${redirectUrlObj.redirect}`)
|
|
return NextResponse.redirect(redirectUrlObj.redirect)
|
|
} else {
|
|
logger.error(`[logout] missing redirectUrlObj reponse from signOut()`)
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof AuthError) {
|
|
logger.error("signOutAuthError", { signOutAuthError: error })
|
|
} else {
|
|
logger.error("signOutError", { signOutError: error })
|
|
}
|
|
}
|
|
|
|
return internalServerError()
|
|
}
|