Repository navigation
Expand file tree
/
Copy pathmiddleware.ts
More file actions
65 lines (54 loc) · 1.87 KB
/
Copy pathmiddleware.ts
File metadata and controls
65 lines (54 loc) · 1.87 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
import { auth } from "@/lib/auth"
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
// Define protected routes
const adminRoutes = ["/admin"]
const protectedRoutes = ["/profile", "/orders", "/wishlist", "/checkout"]
const authRoutes = ["/auth/signin", "/auth/signup"]
export default async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// Get the session
const session = await auth()
// Check if user is trying to access auth pages while already authenticated
if (authRoutes.some(route => pathname.startsWith(route))) {
if (session?.user) {
return NextResponse.redirect(new URL("/", request.url))
}
return NextResponse.next()
}
// Check admin routes
if (adminRoutes.some(route => pathname.startsWith(route))) {
if (!session?.user) {
return NextResponse.redirect(new URL("/auth/signin", request.url))
}
// Check if user has admin role
if (session.user.role !== "ADMIN") {
return NextResponse.redirect(new URL("/", request.url))
}
return NextResponse.next()
}
// Check protected routes
if (protectedRoutes.some(route => pathname.startsWith(route))) {
if (!session?.user) {
// Store the attempted URL to redirect after login
const signInUrl = new URL("/auth/signin", request.url)
signInUrl.searchParams.set("callbackUrl", pathname)
return NextResponse.redirect(signInUrl)
}
return NextResponse.next()
}
return NextResponse.next()
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public (public files)
*/
'/((?!api|_next/static|_next/image|favicon.ico|public).*)',
],
}