-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
53 lines (47 loc) · 1.48 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
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
// Define the configuration for the middleware
export const config = {
// Limit the middleware to paths starting with specific patterns
matcher: [
"/ccadmin/:function*",
"/adminfile/:function*",
"/ccadminx/:function*",
"/ccagent/:function*",
"/file/:function*",
],
};
// Middleware function to be executed for each request
export function middleware(request) {
// Extract X-InstanceId header from the request
const hostId = cookies().get("x-instanceid")?.value;
const accessToken = cookies().get("x-authorization")?.value;
// Check if X-InstanceId header is missing
if (!hostId) {
// Return a JSON response indicating an error
return NextResponse.json(
{
errorCode: "01",
message: `X-InstanceId header is missing in the request.`,
},
{ status: 400 },
);
}
// Call the isAuthenticated function to check the request's authentication
if (!accessToken) {
// Respond with JSON indicating an authentication error
return NextResponse.json(
{ errorCode: "02", message: "authorization token is missing" },
{ status: 400 },
);
}
const newHeaders = new Headers(request.headers);
newHeaders.set("Authorization", `Bearer ${accessToken}`);
newHeaders.set("X-InstanceId", hostId);
// Continue processing if authentication is successful
return NextResponse.next({
request: {
headers: newHeaders,
},
});
}