Merged in monorepo-step-1 (pull request #1080)
Migrate to a monorepo setup - step 1 * Move web to subfolder /apps/scandic-web * Yarn + transitive deps - Move to yarn - design-system package removed for now since yarn doesn't support the parameter for token (ie project currently broken) - Add missing transitive dependencies as Yarn otherwise prevents these imports - VS Code doesn't pick up TS path aliases unless you open /apps/scandic-web instead of root (will be fixed with monorepo) * Pin framer-motion to temporarily fix typing issue https://github.com/adobe/react-spectrum/issues/7494 * Pin zod to avoid typ error There seems to have been a breaking change in the types returned by zod where error is now returned as undefined instead of missing in the type. We should just handle this but to avoid merge conflicts just pin the dependency for now. * Pin react-intl version Pin version of react-intl to avoid tiny type issue where formatMessage does not accept a generic any more. This will be fixed in a future commit, but to avoid merge conflicts just pin for now. * Pin typescript version Temporarily pin version as newer versions as stricter and results in a type error. Will be fixed in future commit after merge. * Setup workspaces * Add design-system as a monorepo package * Remove unused env var DESIGN_SYSTEM_ACCESS_TOKEN * Fix husky for monorepo setup * Update netlify.toml * Add lint script to root package.json * Add stub readme * Fix react-intl formatMessage types * Test netlify.toml in root * Remove root toml * Update netlify.toml publish path * Remove package-lock.json * Update build for branch/preview builds Approved-by: Linus Flood
This commit is contained in:
committed by
Linus Flood
parent
667cab6fb6
commit
80100e7631
99
apps/scandic-web/middlewares/authRequired.ts
Normal file
99
apps/scandic-web/middlewares/authRequired.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { NextResponse } from "next/server"
|
||||
|
||||
import { authRequired, mfaRequired } from "@/constants/routes/authRequired"
|
||||
import { login } from "@/constants/routes/handleAuth"
|
||||
import { getInternalNextURL, getPublicNextURL } from "@/server/utils"
|
||||
|
||||
import { auth } from "@/auth"
|
||||
import { findLang } from "@/utils/languages"
|
||||
|
||||
import type { NextMiddleware } from "next/server"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
/**
|
||||
* AppRouteHandlerFnContext is the context that is passed to the handler as
|
||||
* the second argument. This is only done for Route handlers (route.js) and
|
||||
* not for middleware. Middleware`s second argument is `event` of type
|
||||
* `NextFetchEvent`.
|
||||
*
|
||||
* Auth.js uses the same pattern for both Route handlers and Middleware,
|
||||
* the auth()-wrapper:
|
||||
*
|
||||
* auth((req) => { ... })
|
||||
*
|
||||
* But there is a difference between middleware and route handlers, route
|
||||
* handlers get passed a context which middleware do not get (they get a
|
||||
* NextFetchEvent instead). Using the same function for both works runtime
|
||||
* because Auth.js handles this properly. But fails in typings as the second
|
||||
* argument doesn't match for middleware.
|
||||
*
|
||||
* We want to avoid using ts-expect-error because that hides other errors
|
||||
* not related to this typing error and ts-expect-error cannot be scoped either.
|
||||
*
|
||||
* So we type assert this export to NextMiddleware. The lesser of all evils.
|
||||
*
|
||||
* https://github.com/nextauthjs/next-auth/blob/3c035ec62f2f21d7cab65504ba83fb1a9a13be01/packages/next-auth/src/lib/index.ts#L265
|
||||
* https://authjs.dev/reference/nextjs
|
||||
*/
|
||||
export const middleware = auth(async (request) => {
|
||||
const lang = findLang(request.nextUrl.pathname)!
|
||||
|
||||
const isLoggedIn = !!request.auth
|
||||
const hasError = request.auth?.error
|
||||
|
||||
// Inside auth() we need an internal request for rewrites.
|
||||
// @see getInternalNextURL()
|
||||
const nextUrlInternal = getInternalNextURL(request)
|
||||
|
||||
const nextUrlPublic = getPublicNextURL(request)
|
||||
|
||||
/**
|
||||
* Function to validate MFA from token data
|
||||
* @returns boolean
|
||||
*/
|
||||
function isMFAInvalid() {
|
||||
const isMFATokenValid = request.auth
|
||||
? request.auth.token.mfa_expires_at > Date.now()
|
||||
: false
|
||||
return !(request.auth?.token.mfa_scope && isMFATokenValid)
|
||||
}
|
||||
const isMFAPath = mfaRequired.includes(request.nextUrl.pathname)
|
||||
|
||||
if (isLoggedIn && isMFAPath && isMFAInvalid()) {
|
||||
const headers = new Headers(request.headers)
|
||||
headers.set("x-returnurl", nextUrlPublic.href)
|
||||
headers.set("x-login-source", "mfa")
|
||||
return NextResponse.rewrite(new URL(`/${lang}/login`, nextUrlInternal), {
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (isLoggedIn && !hasError) {
|
||||
const headers = new Headers(request.headers)
|
||||
headers.set("x-continue", "1")
|
||||
return NextResponse.next({
|
||||
headers,
|
||||
})
|
||||
}
|
||||
|
||||
const headers = new Headers()
|
||||
headers.append(
|
||||
"set-cookie",
|
||||
`redirectTo=${encodeURIComponent(nextUrlPublic.href)}; Path=/; HttpOnly; SameSite=Lax`
|
||||
)
|
||||
|
||||
const loginUrl = login[lang]
|
||||
const redirectUrl = new URL(loginUrl, nextUrlPublic)
|
||||
const redirectOpts = {
|
||||
headers,
|
||||
}
|
||||
console.log(`[authRequired] redirecting to: ${redirectUrl}`, redirectOpts)
|
||||
return NextResponse.redirect(redirectUrl, redirectOpts)
|
||||
}) as NextMiddleware // See comment above
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
return authRequired.includes(request.nextUrl.pathname)
|
||||
}
|
||||
22
apps/scandic-web/middlewares/bookingFlow.ts
Normal file
22
apps/scandic-web/middlewares/bookingFlow.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from "next/server"
|
||||
|
||||
import { getDefaultRequestHeaders } from "./utils"
|
||||
|
||||
import type { NextMiddleware } from "next/server"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
export const middleware: NextMiddleware = async (request) => {
|
||||
const headers = getDefaultRequestHeaders(request)
|
||||
return NextResponse.next({
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
return !!request.nextUrl.pathname.match(
|
||||
/^\/(da|de|en|fi|no|sv)\/(hotelreservation)/
|
||||
)
|
||||
}
|
||||
122
apps/scandic-web/middlewares/cmsContent.ts
Normal file
122
apps/scandic-web/middlewares/cmsContent.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import { type NextMiddleware, NextResponse } from "next/server"
|
||||
|
||||
import { notFound } from "@/server/errors/next"
|
||||
|
||||
import { getUidAndContentTypeByPath } from "@/services/cms/getUidAndContentTypeByPath"
|
||||
import { findLang } from "@/utils/languages"
|
||||
import { removeTrailingSlash } from "@/utils/url"
|
||||
|
||||
import { getDefaultRequestHeaders } from "./utils"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
import { PageContentTypeEnum } from "@/types/requests/contentType"
|
||||
|
||||
export const middleware: NextMiddleware = async (request) => {
|
||||
const { nextUrl } = request
|
||||
const lang = findLang(nextUrl.pathname)!
|
||||
|
||||
const pathWithoutTrailingSlash = removeTrailingSlash(nextUrl.pathname)
|
||||
|
||||
const isPreview = request.nextUrl.pathname.includes("/preview")
|
||||
|
||||
const incomingPathName = isPreview
|
||||
? pathWithoutTrailingSlash.replace("/preview", "")
|
||||
: pathWithoutTrailingSlash
|
||||
|
||||
let { contentType, uid } = await getUidAndContentTypeByPath(incomingPathName)
|
||||
|
||||
const searchParams = new URLSearchParams(request.nextUrl.searchParams)
|
||||
|
||||
if (!contentType || !uid) {
|
||||
// Routes to subpages we need to check if the parent of the incomingPathName exists.
|
||||
// Then we considered the incomingPathName to be a subpage. These subpages do not live in the CMS.
|
||||
const incomingPathNameParts = incomingPathName.split("/")
|
||||
|
||||
// If the incomingPathName has 2 or more parts, it could possibly be a subpage.
|
||||
if (incomingPathNameParts.length >= 2) {
|
||||
const subpage = incomingPathNameParts.pop()
|
||||
if (subpage) {
|
||||
let { contentType: parentContentType, uid: parentUid } =
|
||||
await getUidAndContentTypeByPath(incomingPathNameParts.join("/"))
|
||||
|
||||
if (parentUid) {
|
||||
contentType = parentContentType
|
||||
uid = parentUid
|
||||
switch (parentContentType) {
|
||||
case PageContentTypeEnum.hotelPage:
|
||||
// E.g. Dedicated pages for restaurant, parking etc.
|
||||
searchParams.set("subpage", subpage)
|
||||
break
|
||||
case PageContentTypeEnum.destinationCityPage:
|
||||
// E.g. Active filters inside destination pages to filter hotels.
|
||||
searchParams.set("filterFromUrl", subpage)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!contentType || !uid) {
|
||||
throw notFound(
|
||||
`Unable to resolve CMS entry for page "${pathWithoutTrailingSlash}"`
|
||||
)
|
||||
}
|
||||
const headers = getDefaultRequestHeaders(request)
|
||||
headers.set("x-uid", uid)
|
||||
headers.set("x-contenttype", contentType)
|
||||
|
||||
const isCurrent = contentType ? contentType.indexOf("current") >= 0 : false
|
||||
|
||||
if (isPreview) {
|
||||
searchParams.set("isPreview", "true")
|
||||
return NextResponse.rewrite(
|
||||
new URL(
|
||||
`/${lang}/${contentType}/${uid}?${searchParams.toString()}`,
|
||||
nextUrl
|
||||
),
|
||||
{
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (isCurrent) {
|
||||
const contentTypePathName = pathWithoutTrailingSlash.replace(`/${lang}`, "")
|
||||
searchParams.set("uid", uid)
|
||||
searchParams.set("uri", contentTypePathName)
|
||||
return NextResponse.rewrite(
|
||||
new URL(
|
||||
`/${lang}/current-content-page?${searchParams.toString()}`,
|
||||
nextUrl
|
||||
),
|
||||
{
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.rewrite(
|
||||
new URL(
|
||||
`/${lang}/${contentType}/${uid}?${searchParams.toString()}`,
|
||||
nextUrl
|
||||
),
|
||||
{
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
// Do not process paths with file extension.
|
||||
// Only looking for dot might be too brute force/give false positives.
|
||||
// It works right now but adjust accordingly when new use cases/data emerges.
|
||||
const lastPathnameSegment = request.nextUrl.pathname.split("/").pop()
|
||||
return lastPathnameSegment?.indexOf(".") === -1
|
||||
}
|
||||
33
apps/scandic-web/middlewares/currentWebLogin.ts
Normal file
33
apps/scandic-web/middlewares/currentWebLogin.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { NextResponse } from "next/server"
|
||||
|
||||
import { badRequest } from "@/server/errors/next"
|
||||
|
||||
import { findLang } from "@/utils/languages"
|
||||
|
||||
import type { NextMiddleware } from "next/server"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
export const middleware: NextMiddleware = (request) => {
|
||||
const returnUrl = request.nextUrl.searchParams.get("returnurl")
|
||||
|
||||
if (!returnUrl) {
|
||||
return badRequest()
|
||||
}
|
||||
|
||||
const lang = findLang(request.nextUrl.pathname)!
|
||||
|
||||
const headers = new Headers(request.headers)
|
||||
headers.set("x-returnurl", returnUrl)
|
||||
headers.set("x-login-source", "seamless")
|
||||
|
||||
return NextResponse.rewrite(new URL(`/${lang}/login`, request.nextUrl), {
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
return request.nextUrl.pathname.endsWith("/updatelogin")
|
||||
}
|
||||
33
apps/scandic-web/middlewares/currentWebLoginEmail.ts
Normal file
33
apps/scandic-web/middlewares/currentWebLoginEmail.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { NextResponse } from "next/server"
|
||||
|
||||
import { badRequest } from "@/server/errors/next"
|
||||
|
||||
import { findLang } from "@/utils/languages"
|
||||
|
||||
import type { NextMiddleware } from "next/server"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
export const middleware: NextMiddleware = (request) => {
|
||||
const returnUrl = request.nextUrl.searchParams.get("returnurl")
|
||||
|
||||
if (!returnUrl) {
|
||||
return badRequest()
|
||||
}
|
||||
|
||||
const lang = findLang(request.nextUrl.pathname)!
|
||||
|
||||
const headers = new Headers(request.headers)
|
||||
headers.set("x-returnurl", returnUrl)
|
||||
headers.set("x-login-source", "seamless-magiclink")
|
||||
|
||||
return NextResponse.rewrite(new URL(`/${lang}/login`, request.nextUrl), {
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
return request.nextUrl.pathname.endsWith("/updateloginemail")
|
||||
}
|
||||
34
apps/scandic-web/middlewares/currentWebLogout.ts
Normal file
34
apps/scandic-web/middlewares/currentWebLogout.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { NextResponse } from "next/server"
|
||||
|
||||
import { env } from "@/env/server"
|
||||
import { badRequest, internalServerError } from "@/server/errors/next"
|
||||
import { getPublicURL } from "@/server/utils"
|
||||
|
||||
import { findLang } from "@/utils/languages"
|
||||
|
||||
import type { NextMiddleware } from "next/server"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
export const middleware: NextMiddleware = (request) => {
|
||||
const currentwebUrl = request.nextUrl.searchParams.get("currentweb")
|
||||
if (currentwebUrl == null || undefined) {
|
||||
return badRequest()
|
||||
}
|
||||
const lang = findLang(request.nextUrl.pathname)!
|
||||
|
||||
const redirectTo = getPublicURL(request)
|
||||
|
||||
const headers = new Headers(request.headers)
|
||||
headers.set("x-returnurl", redirectTo)
|
||||
headers.set("x-logout-source", "seamless")
|
||||
|
||||
return NextResponse.rewrite(new URL(`/${lang}/logout`, request.nextUrl), {
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
})
|
||||
}
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
return request.nextUrl.pathname.endsWith("/updatelogout")
|
||||
}
|
||||
47
apps/scandic-web/middlewares/dateFormat.ts
Normal file
47
apps/scandic-web/middlewares/dateFormat.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { type NextMiddleware, NextResponse } from "next/server"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
/*
|
||||
Middleware function to normalize date formats to support
|
||||
YYYY-MM-D and YYYY-MM-DD since the current web uses YYYY-MM-D
|
||||
in the URL as parameters (toDate and fromDate)
|
||||
*/
|
||||
const legacyDatePattern = /^([12]\d{3}-(0[1-9]|1[0-2])-([1-9]))$/
|
||||
|
||||
function normalizeDate(date: string): string {
|
||||
const datePattern = /^\d{4}-\d{1,2}-\d{1,2}$/
|
||||
if (datePattern.test(date)) {
|
||||
const [year, month, day] = date.split("-").map(Number)
|
||||
return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`
|
||||
}
|
||||
return date
|
||||
}
|
||||
|
||||
export const middleware: NextMiddleware = (request) => {
|
||||
const url = request.nextUrl.clone()
|
||||
const { searchParams } = url
|
||||
|
||||
if (
|
||||
legacyDatePattern.test(searchParams.get("fromdate")!) ||
|
||||
legacyDatePattern.test(searchParams.get("todate")!)
|
||||
) {
|
||||
const fromDate = searchParams.get("fromdate")!
|
||||
url.searchParams.set("fromdate", normalizeDate(fromDate))
|
||||
|
||||
const toDate = searchParams.get("todate")!
|
||||
url.searchParams.set("todate", normalizeDate(toDate))
|
||||
return NextResponse.redirect(url)
|
||||
} else {
|
||||
const headers = new Headers(request.headers)
|
||||
headers.set("x-continue", "1")
|
||||
return NextResponse.next({
|
||||
headers,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
const { searchParams } = request.nextUrl
|
||||
return searchParams.has("fromdate") || searchParams.has("todate")
|
||||
}
|
||||
15
apps/scandic-web/middlewares/handleAuth.ts
Normal file
15
apps/scandic-web/middlewares/handleAuth.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from "next/server"
|
||||
|
||||
import { handleAuth } from "@/constants/routes/handleAuth"
|
||||
|
||||
import type { NextMiddleware } from "next/server"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
export const middleware: NextMiddleware = () => {
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
return handleAuth.includes(request.nextUrl.pathname)
|
||||
}
|
||||
75
apps/scandic-web/middlewares/myPages.ts
Normal file
75
apps/scandic-web/middlewares/myPages.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { type NextMiddleware, NextResponse } from "next/server"
|
||||
|
||||
import {
|
||||
myPages,
|
||||
overview,
|
||||
profile,
|
||||
profileEdit,
|
||||
} from "@/constants/routes/myPages"
|
||||
import { notFound } from "@/server/errors/next"
|
||||
import { getPublicNextURL } from "@/server/utils"
|
||||
|
||||
import { fetchAndCacheEntry } from "@/services/cms/fetchAndCacheEntry"
|
||||
import { findLang } from "@/utils/languages"
|
||||
|
||||
import { getDefaultRequestHeaders } from "./utils"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
export const middleware: NextMiddleware = async (request) => {
|
||||
const { nextUrl } = request
|
||||
const lang = findLang(nextUrl.pathname)!
|
||||
|
||||
const myPagesRoot = myPages[lang]
|
||||
if (nextUrl.pathname === myPagesRoot) {
|
||||
const nextUrlPublic = getPublicNextURL(request)
|
||||
const overviewUrl = overview[lang]
|
||||
const redirectUrl = new URL(overviewUrl, nextUrlPublic)
|
||||
console.log(`[myPages] redirecting to: ${redirectUrl}`)
|
||||
return NextResponse.redirect(redirectUrl)
|
||||
}
|
||||
|
||||
const pathNameWithoutLang = nextUrl.pathname.replace(`/${lang}`, "")
|
||||
const { uid, contentType } = await fetchAndCacheEntry(
|
||||
pathNameWithoutLang,
|
||||
lang
|
||||
)
|
||||
if (!uid || !contentType) {
|
||||
throw notFound(
|
||||
`Unable to resolve CMS entry for locale "${lang}": ${pathNameWithoutLang}`
|
||||
)
|
||||
}
|
||||
|
||||
const headers = getDefaultRequestHeaders(request)
|
||||
headers.set("x-uid", uid)
|
||||
headers.set("x-contenttype", contentType)
|
||||
|
||||
// Handle profile and profile edit routes, which are not CMS entries
|
||||
if (profile[lang].startsWith(nextUrl.pathname)) {
|
||||
return NextResponse.rewrite(new URL(`/${lang}/my-pages/profile`, nextUrl), {
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
})
|
||||
} else if (profileEdit[lang].startsWith(nextUrl.pathname)) {
|
||||
return NextResponse.rewrite(
|
||||
new URL(`/${lang}/my-pages/profile/edit`, nextUrl),
|
||||
{
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.next({
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
const lang = findLang(request.nextUrl.pathname)!
|
||||
return request.nextUrl.pathname.startsWith(myPages[lang])
|
||||
}
|
||||
22
apps/scandic-web/middlewares/sasXScandic.ts
Normal file
22
apps/scandic-web/middlewares/sasXScandic.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { type NextMiddleware,NextResponse } from "next/server"
|
||||
|
||||
import { Lang } from "@/constants/languages"
|
||||
|
||||
import { getDefaultRequestHeaders } from "./utils"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
export const middleware: NextMiddleware = async (request) => {
|
||||
const headers = getDefaultRequestHeaders(request)
|
||||
return NextResponse.next({
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
return !!request.nextUrl.pathname.match(
|
||||
new RegExp(`^/(${Object.values(Lang).join("|")})/(sas-x-scandic)/.+`)
|
||||
)
|
||||
}
|
||||
22
apps/scandic-web/middlewares/utils.ts
Normal file
22
apps/scandic-web/middlewares/utils.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { getPublicNextURL } from "@/server/utils"
|
||||
|
||||
import { findLang } from "@/utils/languages"
|
||||
import { removeTrailingSlash } from "@/utils/url"
|
||||
|
||||
import type { NextRequest } from "next/server"
|
||||
|
||||
export function getDefaultRequestHeaders(request: NextRequest) {
|
||||
const lang = findLang(request.nextUrl.pathname)!
|
||||
const nextUrlPublic = getPublicNextURL(request)
|
||||
const headers = new Headers(request.headers)
|
||||
headers.set("x-lang", lang)
|
||||
headers.set(
|
||||
"x-pathname",
|
||||
removeTrailingSlash(
|
||||
request.nextUrl.pathname.replace(`/${lang}`, "").replace(`/webview`, "")
|
||||
)
|
||||
)
|
||||
headers.set("x-url", removeTrailingSlash(nextUrlPublic.href))
|
||||
|
||||
return headers
|
||||
}
|
||||
166
apps/scandic-web/middlewares/webView.ts
Normal file
166
apps/scandic-web/middlewares/webView.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
import { type NextMiddleware, NextResponse } from "next/server"
|
||||
|
||||
import {
|
||||
loyaltyPagesWebviews,
|
||||
myPagesWebviews,
|
||||
refreshWebviews,
|
||||
webviews,
|
||||
} from "@/constants/routes/webviews"
|
||||
import { env } from "@/env/server"
|
||||
import { badRequest, notFound } from "@/server/errors/next"
|
||||
|
||||
import { fetchAndCacheEntry } from "@/services/cms/fetchAndCacheEntry"
|
||||
import { decryptData } from "@/utils/aes"
|
||||
import { findLang } from "@/utils/languages"
|
||||
|
||||
import { getDefaultRequestHeaders } from "./utils"
|
||||
|
||||
import type { MiddlewareMatcher } from "@/types/middleware"
|
||||
|
||||
export const middleware: NextMiddleware = async (request) => {
|
||||
const { nextUrl } = request
|
||||
const lang = findLang(nextUrl.pathname)!
|
||||
|
||||
const loginTypeHeader = request.headers.get("loginType")
|
||||
const loginTypeSearchParam = nextUrl.searchParams.get("loginType")
|
||||
|
||||
const adobeMc = nextUrl.searchParams.get("adobe_mc")
|
||||
|
||||
const headers = getDefaultRequestHeaders(request)
|
||||
|
||||
// LoginType is passed from the mobile app as a header and needs to be passed around with each subsequent
|
||||
// request within webviews due to tracking. We set the loginType as a header and pass it along to future
|
||||
// requests, and to read it from TRPC side (which is where the tracking object is created).
|
||||
// The value is appended to all webview links as a search param, just like adobe_mc.
|
||||
const loginType = loginTypeHeader || loginTypeSearchParam
|
||||
if (loginType) {
|
||||
headers.set("loginType", loginType)
|
||||
}
|
||||
|
||||
// adobe_mc (Experience Cloud ID) needs to be passed around as a search param, which will be read
|
||||
// from the URL by the tracking SDK. Adobe_mc is passed from the mobile app as a searchParam, and
|
||||
// then passed to nextjs as a header. In the RSC, the adobe_mc is appended as a searchParam on each webview link.
|
||||
if (adobeMc) {
|
||||
headers.set("adobe_mc", adobeMc)
|
||||
}
|
||||
|
||||
// If user is redirected to /lang/webview/refresh/, the webview token is invalid and we remove the cookie
|
||||
if (refreshWebviews.includes(nextUrl.pathname)) {
|
||||
return NextResponse.rewrite(
|
||||
new URL(
|
||||
`/${lang}/webview/refresh?${nextUrl.searchParams.toString()}`,
|
||||
nextUrl
|
||||
),
|
||||
{
|
||||
headers: {
|
||||
"Set-Cookie": `webviewToken=0; Max-Age=0; Secure; HttpOnly; Path=/; SameSite=Strict;`,
|
||||
},
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const pathNameWithoutLang = nextUrl.pathname.replace(`/${lang}/webview`, "")
|
||||
|
||||
const { uid } = await fetchAndCacheEntry(pathNameWithoutLang, lang)
|
||||
if (!uid) {
|
||||
throw notFound(
|
||||
`Unable to resolve CMS entry for locale "${lang}": ${pathNameWithoutLang}`
|
||||
)
|
||||
}
|
||||
headers.set("x-uid", uid)
|
||||
|
||||
const webviewToken = request.cookies.get("webviewToken")
|
||||
if (webviewToken) {
|
||||
// since the token exists, this is a subsequent visit
|
||||
// we're done, allow it
|
||||
if (myPagesWebviews.includes(nextUrl.pathname)) {
|
||||
return NextResponse.rewrite(
|
||||
new URL(`/${lang}/webview/account-page/${uid}`, nextUrl),
|
||||
{
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
} else if (loyaltyPagesWebviews.includes(nextUrl.pathname)) {
|
||||
return NextResponse.rewrite(
|
||||
new URL(`/${lang}/webview/loyalty-page/${uid}`, nextUrl),
|
||||
{
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
} else {
|
||||
return notFound()
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Authorization header is required for webviews
|
||||
// It should be base64 encoded
|
||||
const authorization = request.headers.get("X-Authorization")!
|
||||
if (!authorization) {
|
||||
console.error("Authorization header is missing")
|
||||
return badRequest("Authorization header is missing")
|
||||
}
|
||||
|
||||
// Initialization vector header is required for webviews
|
||||
// It should be base64 encoded
|
||||
const initializationVector = request.headers.get("X-AES-IV")!
|
||||
if (!initializationVector) {
|
||||
console.error("initializationVector header is missing")
|
||||
return badRequest("initializationVector header is missing")
|
||||
}
|
||||
|
||||
const decryptedData = await decryptData(
|
||||
env.WEBVIEW_ENCRYPTION_KEY,
|
||||
initializationVector,
|
||||
authorization
|
||||
)
|
||||
|
||||
headers.append("Cookie", `webviewToken=${decryptedData}`)
|
||||
|
||||
if (myPagesWebviews.includes(nextUrl.pathname)) {
|
||||
return NextResponse.rewrite(
|
||||
new URL(`/${lang}/webview/account-page/${uid}`, nextUrl),
|
||||
{
|
||||
headers: {
|
||||
"Set-Cookie": `webviewToken=${decryptedData}; Secure; HttpOnly; Path=/; SameSite=Strict;`,
|
||||
},
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
} else if (loyaltyPagesWebviews.includes(nextUrl.pathname)) {
|
||||
return NextResponse.rewrite(
|
||||
new URL(`/${lang}/webview/loyalty-page/${uid}`, nextUrl),
|
||||
{
|
||||
headers: {
|
||||
"Set-Cookie": `webviewToken=${decryptedData}; Secure; HttpOnly; Path=/; SameSite=Strict;`,
|
||||
},
|
||||
request: {
|
||||
headers,
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
console.error("Error in webView middleware")
|
||||
console.error(`${e.name}: ${e.message}`)
|
||||
}
|
||||
|
||||
return badRequest()
|
||||
}
|
||||
}
|
||||
|
||||
export const matcher: MiddlewareMatcher = (request) => {
|
||||
const { nextUrl } = request
|
||||
|
||||
return webviews.includes(nextUrl.pathname)
|
||||
}
|
||||
Reference in New Issue
Block a user