2022-11-11 22:17:44 -05:00
|
|
|
import { getToken } from "next-auth/jwt"
|
|
|
|
import { withAuth } from "next-auth/middleware"
|
|
|
|
import { NextResponse } from "next/server"
|
2022-03-21 03:46:15 -04:00
|
|
|
|
2023-03-27 23:16:11 -04:00
|
|
|
const PAGES_REQUIRE_AUTH = ["/new", "/settings", "/mine", "/admin"]
|
|
|
|
|
2022-11-11 22:17:44 -05:00
|
|
|
export default withAuth(
|
|
|
|
async function middleware(req) {
|
|
|
|
const token = await getToken({ req })
|
2022-11-14 02:02:31 -05:00
|
|
|
|
2023-02-26 21:41:02 -05:00
|
|
|
const isAuthed = !!token
|
2022-11-11 22:17:44 -05:00
|
|
|
const isAuthPage =
|
|
|
|
req.nextUrl.pathname.startsWith("/signup") ||
|
|
|
|
req.nextUrl.pathname.startsWith("/signin")
|
2022-03-21 03:46:15 -04:00
|
|
|
|
2023-03-27 23:16:11 -04:00
|
|
|
const isPageRequireAuth = PAGES_REQUIRE_AUTH.includes(req.nextUrl.pathname)
|
|
|
|
|
2022-11-11 22:17:44 -05:00
|
|
|
if (isAuthPage) {
|
2023-02-26 21:41:02 -05:00
|
|
|
if (isAuthed) {
|
2022-11-11 22:17:44 -05:00
|
|
|
return NextResponse.redirect(new URL("/new", req.url))
|
|
|
|
}
|
2022-03-21 03:46:15 -04:00
|
|
|
|
2022-11-11 22:17:44 -05:00
|
|
|
return null
|
2023-03-27 23:16:11 -04:00
|
|
|
} else if (isPageRequireAuth && !isAuthed) {
|
2022-11-11 22:17:44 -05:00
|
|
|
return NextResponse.redirect(new URL("/signin", req.url))
|
|
|
|
}
|
2023-03-27 23:16:11 -04:00
|
|
|
|
|
|
|
return NextResponse.next()
|
2022-11-11 22:17:44 -05:00
|
|
|
},
|
|
|
|
{
|
|
|
|
callbacks: {
|
|
|
|
async authorized() {
|
|
|
|
// This is a work-around for handling redirect on auth pages.
|
|
|
|
// We return true here so that the middleware function above
|
|
|
|
// is always called.
|
|
|
|
return true
|
|
|
|
}
|
2022-04-12 19:54:02 -04:00
|
|
|
}
|
2022-04-09 20:48:19 -04:00
|
|
|
}
|
2022-11-11 22:17:44 -05:00
|
|
|
)
|
2022-11-08 03:23:28 -05:00
|
|
|
|
|
|
|
export const config = {
|
2022-11-14 21:39:42 -05:00
|
|
|
matcher: [
|
2023-03-27 23:16:11 -04:00
|
|
|
/*
|
|
|
|
* Match all request paths except for the ones starting with:
|
|
|
|
* - api (API routes)
|
|
|
|
* - _next/static (static files)
|
|
|
|
* - _next/image (image optimization files)
|
|
|
|
* - favicon.ico (favicon file)
|
|
|
|
*/
|
|
|
|
"/((?!api|_next/static|_next/image|favicon.ico).*)"
|
2022-11-08 03:23:28 -05:00
|
|
|
]
|
|
|
|
}
|