-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
79 lines (67 loc) · 2.16 KB
/
middleware.ts
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
import { verify } from "@tsndr/cloudflare-worker-jwt";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// Constants for route management
const PROTECTED_ROUTES = ["/config", "/proj"];
const PUBLIC_API_ROUTES = ["/api/auth/login"];
const DEFAULT_REDIRECT = "/";
export async function middleware(request: NextRequest) {
try {
const token = request.cookies.get("session")?.value;
const { pathname } = request.nextUrl;
const isAuthenticated = token ? await checkAuth(token) : false;
const isApiRoute = pathname.startsWith("/api");
// Handle API routes
if (isApiRoute) {
// Allow public API routes
if (PUBLIC_API_ROUTES.includes(pathname)) {
return NextResponse.next();
}
// Check authentication for protected API routes
if (!isAuthenticated) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
);
}
return NextResponse.next();
}
// Handle page routes
if (isAuthenticated && pathname === DEFAULT_REDIRECT) {
return NextResponse.redirect(new URL("/proj", request.url));
}
if (!isAuthenticated && PROTECTED_ROUTES.some(route => pathname.startsWith(route))) {
return NextResponse.redirect(new URL(DEFAULT_REDIRECT, request.url));
}
return NextResponse.next();
} catch (error) {
console.error("[Middleware Error]:", error);
return NextResponse.redirect(new URL(DEFAULT_REDIRECT, request.url));
}
}
async function checkAuth(token: string): Promise<boolean> {
if (process.env.NODE_ENV === 'development') {
return true;
}
try {
if (!process.env.JWT_SECRET) {
throw new Error("JWT_SECRET is not defined");
}
const verified = await verify(token, process.env.JWT_SECRET);
return !!verified;
} catch (error) {
console.error("[Auth Error]:", error);
return false;
}
}
export const config = {
matcher: [
/*
* Match all request paths except for:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!_next/static|_next/image|favicon.ico).*)",
],
};