-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.js
151 lines (128 loc) · 4.42 KB
/
middleware.js
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import { NextResponse } from "next/server";
export async function middleware(request) {
// console.log("\n--- Middleware Start ---");
// console.log("URL:", request.nextUrl.pathname);
// console.log("Method:", request.method);
// console.log("All Cookies:", request.cookies.getAll());
// console.log("Session Cookie:", request.cookies.get("session"));
// console.log("Headers:", Object.fromEntries(request.headers));
// Allow public paths
const publicPaths = [
"/login",
"/_next",
"/favicon.ico",
"/api/plate-reads", // API auth handled in the route itself
"/api/verify-session",
"/api/health-check",
"/api/verify-key",
"/api/verify-whitelist",
];
// Check for API key in query parameters for iframe embeds (insecure)
const url = new URL(request.url);
const queryApiKey = url.searchParams.get("api_key");
if (queryApiKey) {
try {
const response = await fetch(new URL("/api/verify-key", request.url), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ apiKey: queryApiKey }),
});
const result = await response.json();
if (result.valid) {
// Create a new response that preserves the API key in all internal links
const res = NextResponse.next();
// Rewrite the request URL to include the API key
const rewrittenUrl = new URL(request.url);
if (!rewrittenUrl.searchParams.has("api_key")) {
rewrittenUrl.searchParams.set("api_key", queryApiKey);
}
// Set a header that your frontend can use to maintain the API key
res.headers.set("x-api-key", queryApiKey);
return res;
}
} catch (error) {
console.error("API key verification error:", error);
}
}
if (publicPaths.some((path) => request.nextUrl.pathname.startsWith(path))) {
if (request.nextUrl.pathname === "/api/plates") {
const authHeader = request.headers.get("Authorization");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return new Response("Unauthorized", { status: 401 });
}
const apiKey = authHeader.replace("Bearer ", "");
try {
const response = await fetch(new URL("/api/verify-key", request.url), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ apiKey }),
});
if (!response.ok) {
return new Response("Invalid API Key", { status: 401 });
}
} catch (error) {
console.error("Auth verification error:", error);
return new Response("Internal Server Error", { status: 500 });
}
}
return NextResponse.next();
}
// Check session cookie for authenticated routes
const session = request.cookies.get("session");
if (!session) {
const isWhitelistedIpResponse = await fetch(
new URL("/api/verify-whitelist", request.url),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
ip: request.ip,
headers: Object.fromEntries(request.headers),
}),
}
);
const isWhitelistedIp = (await isWhitelistedIpResponse.json()).allowed;
if (isWhitelistedIp) {
return NextResponse.next();
}
console.log("No session cookie block run");
return NextResponse.redirect(new URL("/login", request.url));
}
try {
console.log("Verifying session", session.value);
const response = await fetch(new URL("/api/verify-session", request.url), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
sessionId: session.value,
}),
});
if (!response.ok) {
throw new Error(`Failed to verify session. Status: ${response.status}`);
}
const result = await response.json();
console.log("Response JSON:", result);
if (!result.valid) {
console.log("Invalid session, clearing cookie");
const res = NextResponse.redirect(new URL("/login", request.url));
res.cookies.delete("session");
return res;
}
return NextResponse.next();
} catch (error) {
console.error("Session verification error:", error);
return NextResponse.redirect(new URL("/login", request.url));
}
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
runtime: "nodejs",
};