taxonomy/middleware.ts

47 lines
1.1 KiB
TypeScript
Raw Permalink Normal View History

2022-11-07 12:37:47 +00:00
import { getToken } from "next-auth/jwt"
2022-10-28 07:43:38 +00:00
import { withAuth } from "next-auth/middleware"
2022-11-07 12:37:47 +00:00
import { NextResponse } from "next/server"
2022-10-26 13:18:06 +00:00
export default withAuth(
async function middleware(req) {
2022-11-07 12:37:47 +00:00
const token = await getToken({ req })
const isAuth = !!token
const isAuthPage =
req.nextUrl.pathname.startsWith("/login") ||
req.nextUrl.pathname.startsWith("/register")
if (isAuthPage) {
2022-11-07 12:37:47 +00:00
if (isAuth) {
return NextResponse.redirect(new URL("/dashboard", req.url))
}
return null
}
2022-11-07 12:37:47 +00:00
if (!isAuth) {
let from = req.nextUrl.pathname;
if (req.nextUrl.search) {
from += req.nextUrl.search;
}
return NextResponse.redirect(
new URL(`/login?from=${encodeURIComponent(from)}`, req.url)
);
}
2022-10-28 07:43:38 +00: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-10-26 13:18:06 +00:00
export const config = {
2022-11-07 12:37:47 +00:00
matcher: ["/dashboard/:path*", "/editor/:path*", "/login", "/register"],
}