2024-01-02 02:26:20 -05:00
|
|
|
import authConfig from "@/auth.config"
|
|
|
|
import NextAuth from "next-auth"
|
2023-12-30 05:56:40 -05:00
|
|
|
|
2024-01-02 02:26:20 -05:00
|
|
|
import {
|
|
|
|
DEFAULT_REDIRECT,
|
|
|
|
PUBLIC_ROUTES,
|
|
|
|
AUTH_ROUTES,
|
|
|
|
API_PREFIX
|
|
|
|
} from "@/routes"
|
2023-12-30 05:56:40 -05:00
|
|
|
|
2024-01-02 02:26:20 -05:00
|
|
|
const { auth } = NextAuth(authConfig)
|
2023-12-30 05:56:40 -05:00
|
|
|
|
2024-01-02 02:26:20 -05:00
|
|
|
export default auth((req) => {
|
|
|
|
const isLoggedIn = !!req.auth
|
2023-12-30 05:56:40 -05:00
|
|
|
|
2024-01-02 02:26:20 -05:00
|
|
|
const { nextUrl } = req
|
2023-12-30 05:56:40 -05:00
|
|
|
|
2024-01-02 02:26:20 -05:00
|
|
|
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;
|
2023-12-30 05:56:40 -05:00
|
|
|
}
|
2024-01-02 02:26:20 -05:00
|
|
|
|
|
|
|
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)(.*)'],
|
|
|
|
}
|