43 lines
933 B
TypeScript
43 lines
933 B
TypeScript
import authConfig from "@/auth.config"
|
|
import NextAuth from "next-auth"
|
|
|
|
import {
|
|
DEFAULT_REDIRECT,
|
|
PUBLIC_ROUTES,
|
|
AUTH_ROUTES,
|
|
API_PREFIX
|
|
} from "@/routes"
|
|
|
|
const { auth } = NextAuth(authConfig)
|
|
|
|
export default auth((req) => {
|
|
const isLoggedIn = !!req.auth
|
|
|
|
const { nextUrl } = req
|
|
|
|
const isApiRoute = nextUrl.pathname.startsWith(API_PREFIX)
|
|
const isPublicRoute = PUBLIC_ROUTES.includes(nextUrl.pathname)
|
|
const isAuthRoute = AUTH_ROUTES.includes(nextUrl.pathname)
|
|
|
|
if (isApiRoute) {
|
|
return null
|
|
}
|
|
|
|
if (isAuthRoute) {
|
|
if (isLoggedIn) {
|
|
return Response.redirect(new URL(DEFAULT_REDIRECT, nextUrl))
|
|
}
|
|
return null;
|
|
}
|
|
|
|
if (!isLoggedIn && !isPublicRoute) {
|
|
return Response.redirect(new URL("/auth/login", nextUrl))
|
|
}
|
|
|
|
return null
|
|
})
|
|
|
|
// Optionally, don't invoke Middleware on some paths
|
|
export const config = {
|
|
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
|
|
} |