forked from In-Saiyan/dedsecAI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
44 lines (34 loc) · 1.21 KB
/
middleware.ts
File metadata and controls
44 lines (34 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import NextAuth from 'next-auth'
import { routes } from '@/routes'
import authConfig from '@/auth.config'
const { auth: withAuthMiddleware } = NextAuth(authConfig)
export default withAuthMiddleware((req) => {
const isLoggedIn = !!req.auth
const { nextUrl } = req
// console.log({nextUrl})
const isApiAuthRoute = nextUrl.pathname.startsWith(routes.apiAuthPrefix)
const isAuthRoute = routes.auth.includes(nextUrl.pathname)
const isPublicRoute = routes.public.includes(nextUrl.pathname)
const defaultUrl = new URL(routes.defaultLoginRedirect, nextUrl)
if (isApiAuthRoute) {
return undefined
}
if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(defaultUrl)
}
return undefined
}
if (!isPublicRoute && !isLoggedIn) {
let callbackUrl = nextUrl.pathname
if (nextUrl.search) callbackUrl += nextUrl.search
const encodedCallbackUrl = encodeURIComponent(callbackUrl)
return Response.redirect(
new URL(`/signin?callbackUrl=${encodedCallbackUrl}`, nextUrl)
)
}
return undefined
})
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}