CoastalCommitsPastes/client/middleware.ts

79 lines
2.1 KiB
TypeScript
Raw Normal View History

import { NextFetchEvent, NextResponse } from "next/server"
import type { NextRequest } from "next/server"
2022-11-09 22:02:06 -05:00
import { TOKEN_COOKIE_NAME, USER_COOKIE_NAME } from "@lib/constants"
2022-11-10 02:11:36 -05:00
import serverConfig from "@lib/config"
const PUBLIC_FILE = /\.(.*)$/
export function middleware(req: NextRequest, event: NextFetchEvent) {
2022-04-09 20:48:19 -04:00
const pathname = req.nextUrl.pathname
2022-11-09 22:02:06 -05:00
const signedIn = req.cookies.get(TOKEN_COOKIE_NAME)
2022-04-09 20:48:19 -04:00
const getURL = (pageName: string) => new URL(`/${pageName}`, req.url).href
const isPageRequest =
!PUBLIC_FILE.test(pathname) &&
// header added when next/link pre-fetches a route
!req.headers.get("x-middleware-preflight")
2022-04-09 20:48:19 -04:00
if (!req.headers.get("x-middleware-preflight") && pathname === "/signout") {
// If you're signed in we remove the cookie and redirect to the home page
// If you're not signed in we redirect to the home page
if (signedIn) {
const resp = NextResponse.redirect(getURL(""))
2022-11-09 22:02:06 -05:00
resp.cookies.delete(TOKEN_COOKIE_NAME)
resp.cookies.delete(USER_COOKIE_NAME)
2022-04-09 20:48:19 -04:00
const signoutPromise = new Promise((resolve) => {
2022-11-10 02:11:36 -05:00
fetch(`${serverConfig.url}/auth/signout`, {
2022-04-09 20:48:19 -04:00
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${signedIn}`,
"x-secret-key": process.env.SECRET_KEY || ""
}
}).then(() => {
resolve(true)
})
})
event.waitUntil(signoutPromise)
2022-04-09 20:48:19 -04:00
return resp
}
} else if (isPageRequest) {
2022-11-09 01:14:43 -05:00
// if (signedIn) {
// if (
// pathname === "/" ||
// pathname === "/signin" ||
// pathname === "/signup"
// ) {
// return NextResponse.redirect(getURL("new"))
// }
// } else if (!signedIn) {
// if (pathname.startsWith("/new")) {
// return NextResponse.redirect(getURL("signin"))
// }
// }
if (pathname.includes("/protected/") || pathname.includes("/private/")) {
const urlWithoutVisibility = pathname
.replace("/protected/", "/")
.replace("/private/", "/")
.substring(1)
return NextResponse.redirect(getURL(urlWithoutVisibility))
}
2022-04-09 20:48:19 -04:00
}
2022-04-09 20:48:19 -04:00
return NextResponse.next()
}
export const config = {
match: [
2022-11-10 02:11:36 -05:00
// "/signout",
2022-11-09 21:38:05 -05:00
// "/",
"/signin",
"/signup",
"/new",
"/protected/:path*",
"/private/:path*"
]
}