-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
73 lines (64 loc) · 2.02 KB
/
middleware.ts
File metadata and controls
73 lines (64 loc) · 2.02 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { getToken } from 'next-auth/jwt'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
function isAppInstalled()
{
return process.env.IS_INSTALLED === 'true'
}
export async function middleware(request: NextRequest)
{
const isInstalled = isAppInstalled()
const { pathname } = request.nextUrl
// 1. Before install: only allow /install and static
if (!isInstalled) {
if (
pathname.startsWith('/install') ||
pathname.startsWith('/_next') ||
pathname.startsWith('/favicon.ico')
) {
return NextResponse.next()
}
return NextResponse.redirect(new URL('/install', request.url))
}
// 2. If authenticated and visiting /login, redirect home
if (pathname.startsWith('/login')) {
const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET })
if (token) {
// User is already logged in, redirect to home
return NextResponse.redirect(new URL('/', request.url))
}
return NextResponse.next()
}
// 3. Allow public routes (api/auth, install, static)
if (
pathname.startsWith('/api/auth') ||
pathname.startsWith('/api/content') ||
pathname.startsWith('/install') ||
pathname.startsWith('/_next') ||
pathname.startsWith('/favicon.ico')
) {
return NextResponse.next()
}
// 4. Require authentication for all other routes
const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET })
if (!token) {
const shouldSkipCallback =
pathname === '/' ||
pathname === '/login' ||
pathname === '/install'
if (shouldSkipCallback) {
return NextResponse.redirect(new URL('/login', request.url))
}
// Otherwise, add callbackUrl
const loginUrl = new URL('/login', request.url)
loginUrl.searchParams.set('callbackUrl', pathname)
return NextResponse.redirect(loginUrl)
}
// 5. User authenticated, allow access
return NextResponse.next()
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico).*)',
],
}