fix(auth): make things work

This commit is contained in:
Michael Zetterberg
2024-05-20 09:05:49 +02:00
parent c4912bbb94
commit 476e9f7582
19 changed files with 122 additions and 82 deletions

View File

@@ -44,11 +44,7 @@ export const middleware = auth(async (request) => {
const isLoggedIn = !!request.auth
const hasError = request.auth?.error
if (hasError) {
throw internalServerError(request.auth?.error)
}
if (isLoggedIn) {
if (isLoggedIn && !hasError) {
const headers = new Headers(request.headers)
headers.set("x-continue", "1")
return NextResponse.next({

View File

@@ -19,7 +19,9 @@ export const middleware: NextMiddleware = async (request) => {
const { contentType, uid } = await resolveEntry(pathNameWithoutLang, lang)
if (!contentType || !uid) {
throw notFound()
throw notFound(
`Unable to resolve CMS entry for locale "${lang}": ${pathNameWithoutLang}`
)
}
const isCurrent = contentType ? contentType.indexOf("current") >= 0 : false

View File

@@ -2,23 +2,53 @@ import { NextResponse } from "next/server"
import { findLang } from "@/constants/languages"
import { myPages, overview } from "@/constants/routes/myPages"
import { env } from "@/env/server"
import { internalServerError, notFound } from "@/server/errors/next"
import { resolve as resolveEntry } from "@/utils/entry"
import type { NextMiddleware } from "next/server"
import type { MiddlewareMatcher } from "@/types/middleware"
export const middleware: NextMiddleware = (request) => {
const lang = findLang(request.nextUrl.pathname)!
return NextResponse.redirect(overview[lang])
export const middleware: NextMiddleware = async (request) => {
const { nextUrl } = request
const lang = findLang(nextUrl.pathname)!
const myPagesRoot = myPages[lang]
if (nextUrl.pathname === myPagesRoot) {
if (!env.PUBLIC_URL) {
throw internalServerError("Missing value for env.PUBLIC_URL")
}
const publicUrl = new URL(env.PUBLIC_URL)
const nextUrlClone = nextUrl.clone()
nextUrlClone.host = publicUrl.host
nextUrlClone.hostname = publicUrl.hostname
const overviewUrl = overview[lang]
return NextResponse.redirect(new URL(overviewUrl, nextUrlClone))
}
const pathNameWithoutLang = nextUrl.pathname.replace(`/${lang}`, "")
const { uid } = await resolveEntry(pathNameWithoutLang, lang)
if (!uid) {
throw notFound(
`Unable to resolve CMS entry for locale "${lang}": ${pathNameWithoutLang}`
)
}
const headers = new Headers(request.headers)
headers.set("x-uid", uid)
return NextResponse.next({
request: {
headers,
},
})
}
export const matcher: MiddlewareMatcher = (request) => {
return [
myPages.da,
myPages.de,
myPages.en,
myPages.fi,
myPages.no,
myPages.sv,
].includes(request.nextUrl.pathname)
const lang = findLang(request.nextUrl.pathname)!
return request.nextUrl.pathname.startsWith(myPages[lang])
}