-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
120 lines (109 loc) · 2.63 KB
/
middleware.ts
File metadata and controls
120 lines (109 loc) · 2.63 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Always allow access to auth routes, public pages, and tracker endpoints
if (
pathname.startsWith("/api/auth") ||
pathname.startsWith("/api/flows/suggest") ||
pathname === "/login" ||
pathname === "/signup" ||
pathname === "/" ||
pathname.startsWith("/_next") ||
pathname.startsWith("/reev.js")
) {
return NextResponse.next();
}
// Get token for protected routes
const token = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET
});
// Define protected routes
const protectedRoutes = [
"/reports",
"/patterns",
"/flows",
"/settings",
"/setup",
"/projects",
// Legacy routes (redirect to /reports)
"/issues",
"/dashboard",
"/insights",
"/analytics",
"/pages",
"/session",
"/sessions",
"/feedback",
];
const protectedApiRoutes = [
"/api/reports",
"/api/patterns",
"/api/flows",
"/api/projects",
// Legacy
"/api/sessions",
"/api/tags",
"/api/stats",
"/api/insights",
"/api/feedback",
];
// Check if the current route is protected
const isProtectedRoute = protectedRoutes.some((route) =>
pathname.startsWith(route)
);
const isProtectedApiRoute = protectedApiRoutes.some((route) =>
pathname.startsWith(route)
);
// Protect API routes
if (isProtectedApiRoute) {
if (!token) {
return NextResponse.json(
{ success: false, error: "Unauthorized" },
{ status: 401 }
);
}
return NextResponse.next();
}
// Protect page routes
if (isProtectedRoute) {
if (!token) {
const loginUrl = new URL("/login", req.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
}
return NextResponse.next();
}
export const config = {
matcher: [
"/reports/:path*",
"/patterns/:path*",
"/settings/:path*",
"/setup/:path*",
"/projects/:path*",
"/issues/:path*",
"/dashboard/:path*",
"/insights/:path*",
"/analytics/:path*",
"/pages/:path*",
"/session/:path*",
"/sessions/:path*",
"/feedback/:path*",
"/api/reports/:path*",
"/api/patterns/:path*",
"/api/sessions/:path*",
"/api/tags/:path*",
"/api/stats/:path*",
"/api/projects/:path*",
"/api/insights/:path*",
"/api/feedback/:path*",
"/api/flows/:path*",
"/api/auth/:path*",
"/flows/:path*",
"/login",
"/signup",
],
};