fix(WEB-132): absolute seamless login return urls

This commit is contained in:
Michael Zetterberg
2024-04-25 08:54:05 +02:00
parent 1ec86f43ff
commit bcbc829e2e
5 changed files with 60 additions and 23 deletions

View File

@@ -3,7 +3,7 @@ import { AuthError } from "next-auth"
import { Lang } from "@/constants/languages" import { Lang } from "@/constants/languages"
import { env } from "@/env/server" import { env } from "@/env/server"
import { badRequest, internalServerError } from "@/server/errors/next" import { badRequest } from "@/server/errors/next"
import { signIn } from "@/auth" import { signIn } from "@/auth"
@@ -11,21 +11,41 @@ export async function GET(
request: NextRequest, request: NextRequest,
context: { params: { lang: Lang } } context: { params: { lang: Lang } }
) { ) {
let redirectHeaders: Headers | undefined = undefined
let redirectTo: string
const returnUrl = request.headers.get("x-returnurl") const returnUrl = request.headers.get("x-returnurl")
if (returnUrl) {
// Seamless login request from Current web
redirectTo = returnUrl
} else {
// Normal login request from New web
redirectTo =
request.cookies.get("redirectTo")?.value || // Cookie gets set by authRequired middleware
request.headers.get("x-redirect-to") ||
request.nextUrl.searchParams.get("redirectTo") ||
request.headers.get("Referer") ||
""
// If all else fails, always redirect to startpage // If above fails, always redirect to startpage
const finalDestination = if (!redirectTo) {
returnUrl || const proto = request.headers.get("x-forwarded-proto") ?? "http"
request.headers.get("x-redirect-to") || const host =
request.nextUrl.searchParams.get("redirectTo") || request.headers.get("x-forwarded-host") ??
request.headers.get("Referer") || request.headers.get("host") ??
"/" env.URL
redirectTo = `${proto}://${host}/`
}
// Clean up cookie from authRequired middleware
redirectHeaders = new Headers()
redirectHeaders.append(
"set-cookie",
"redirectTo=; Expires=Thu, 01 Jan 1970 00:00:00 UTC; Path=/; HttpOnly; SameSite=Lax"
)
let redirectTo = finalDestination
if (!returnUrl) {
// This is a regular login request, not a seamless login request
// We should initiate the seamless login flow
try { try {
// Initiate the seamless login flow
let redirectUrlValue let redirectUrlValue
switch (context.params.lang) { switch (context.params.lang) {
case Lang.da: case Lang.da:
@@ -48,12 +68,13 @@ export async function GET(
break break
} }
const redirectUrl = new URL(redirectUrlValue) const redirectUrl = new URL(redirectUrlValue)
redirectUrl.searchParams.set("returnurl", finalDestination) redirectUrl.searchParams.set("returnurl", redirectTo)
redirectTo = redirectUrl.toString() redirectTo = redirectUrl.toString()
} catch (e) { } catch (e) {
console.error("Unable to create URL for seamless login") console.error(
"Unable to create URL for seamless login, proceeding without it."
)
console.error(e) console.error(e)
return internalServerError()
} }
} }
@@ -63,7 +84,7 @@ export async function GET(
* automatically redirecting to it inside of `signIn`. * automatically redirecting to it inside of `signIn`.
* https://github.com/nextauthjs/next-auth/blob/3c035ec/packages/next-auth/src/lib/actions.ts#L76 * https://github.com/nextauthjs/next-auth/blob/3c035ec/packages/next-auth/src/lib/actions.ts#L76
*/ */
const url = await signIn( const redirectUrl = await signIn(
"curity", "curity",
{ {
redirectTo, redirectTo,
@@ -74,8 +95,10 @@ export async function GET(
} }
) )
if (url) { if (redirectUrl) {
return NextResponse.redirect(url) return NextResponse.redirect(redirectUrl, {
headers: redirectHeaders,
})
} }
} catch (error) { } catch (error) {
if (error instanceof AuthError) { if (error instanceof AuthError) {

2
env/server.ts vendored
View File

@@ -34,6 +34,7 @@ export const env = createEnv({
SEAMLESS_LOGIN_FI: z.string(), SEAMLESS_LOGIN_FI: z.string(),
SEAMLESS_LOGIN_NO: z.string(), SEAMLESS_LOGIN_NO: z.string(),
SEAMLESS_LOGIN_SV: z.string(), SEAMLESS_LOGIN_SV: z.string(),
URL: z.string().optional(),
WEBVIEW_ENCRYPTION_KEY: z.string(), WEBVIEW_ENCRYPTION_KEY: z.string(),
}, },
emptyStringAsUndefined: true, emptyStringAsUndefined: true,
@@ -63,6 +64,7 @@ export const env = createEnv({
SEAMLESS_LOGIN_FI: process.env.SEAMLESS_LOGIN_FI, SEAMLESS_LOGIN_FI: process.env.SEAMLESS_LOGIN_FI,
SEAMLESS_LOGIN_NO: process.env.SEAMLESS_LOGIN_NO, SEAMLESS_LOGIN_NO: process.env.SEAMLESS_LOGIN_NO,
SEAMLESS_LOGIN_SV: process.env.SEAMLESS_LOGIN_SV, SEAMLESS_LOGIN_SV: process.env.SEAMLESS_LOGIN_SV,
URL: process.env.URL,
WEBVIEW_ENCRYPTION_KEY: process.env.WEBVIEW_ENCRYPTION_KEY, WEBVIEW_ENCRYPTION_KEY: process.env.WEBVIEW_ENCRYPTION_KEY,
}, },
}) })

View File

@@ -1,11 +1,11 @@
import { NextMiddleware } from "next/server" import { NextMiddleware } from "next/server"
import * as handleAuth from "./middlewares/handleAuth"
import * as authRequired from "./middlewares/authRequired" import * as authRequired from "./middlewares/authRequired"
import * as cmsContent from "./middlewares/cmsContent"
import * as currentWebLogin from "./middlewares/currentWebLogin" import * as currentWebLogin from "./middlewares/currentWebLogin"
import * as ensureLang from "./middlewares/ensureLang" import * as ensureLang from "./middlewares/ensureLang"
import * as cmsContent from "@/middlewares/cmsContent" import * as handleAuth from "./middlewares/handleAuth"
import * as webView from "@/middlewares/webView" import * as webView from "./middlewares/webView"
export const middleware: NextMiddleware = async (request, event) => { export const middleware: NextMiddleware = async (request, event) => {
const middlewares = [ const middlewares = [

View File

@@ -1,10 +1,11 @@
import { NextResponse } from "next/server" import { NextResponse } from "next/server"
import { auth } from "@/auth"
import { findLang } from "@/constants/languages" import { findLang } from "@/constants/languages"
import { authRequired } from "@/constants/routes/authRequired" import { authRequired } from "@/constants/routes/authRequired"
import { login } from "@/constants/routes/handleAuth" import { login } from "@/constants/routes/handleAuth"
import { auth } from "@/auth"
import type { NextMiddleware } from "next/server" import type { NextMiddleware } from "next/server"
import type { MiddlewareMatcher } from "@/types/middleware" import type { MiddlewareMatcher } from "@/types/middleware"
@@ -44,8 +45,15 @@ export const middleware = auth(async (request) => {
return NextResponse.next() return NextResponse.next()
} }
const headers = new Headers()
headers.append(
"set-cookie",
`redirectTo=${encodeURIComponent(nextUrl.href)}; Path=/; HttpOnly; SameSite=Lax`
)
const loginUrl = login[lang] const loginUrl = login[lang]
return NextResponse.redirect(new URL(loginUrl, request.nextUrl)) return NextResponse.redirect(new URL(loginUrl, request.nextUrl), {
headers,
})
}) as NextMiddleware // See comment above }) as NextMiddleware // See comment above
export const matcher: MiddlewareMatcher = (request) => { export const matcher: MiddlewareMatcher = (request) => {

View File

@@ -23,6 +23,10 @@ jiti("./env/client")
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
env: { env: {
URL:
process.env.CONTEXT === "production"
? process.env.URL
: process.env.DEPLOY_PRIME_URL,
NEXTAUTH_URL: NEXTAUTH_URL:
(process.env.CONTEXT === "production" (process.env.CONTEXT === "production"
? process.env.URL ? process.env.URL