-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
77 lines (64 loc) · 1.96 KB
/
proxy.js
File metadata and controls
77 lines (64 loc) · 1.96 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
import { NextResponse } from "next/server";
function unauthorizedResponse(request) {
const pathname = request.nextUrl.pathname || "";
const accept = request.headers.get("accept") || "";
const isApiRequest =
pathname === "/api" ||
pathname.startsWith("/api/") ||
pathname.endsWith("/api") ||
pathname.includes("/api/") ||
accept.includes("application/json");
if (isApiRequest) {
return NextResponse.json(
{
success: false,
error: {
message: "Authentication required.",
code: "admin_auth_required",
},
},
{
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Admin Area"',
},
}
);
}
return new Response("Authentication required", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Admin Area"',
},
});
}
export function proxy(request) {
const { pathname } = request.nextUrl;
const isAdminPage = pathname.startsWith("/admin");
const isAdminApi = pathname.startsWith("/api/admin");
const isProtectedRelationshipWrite =
pathname.match(/^\/api\/policies\/\d+\/relationships$/) &&
request.method === "POST";
if (!isAdminPage && !isAdminApi && !isProtectedRelationshipWrite) {
return NextResponse.next();
}
const authHeader = request.headers.get("authorization");
if (!authHeader || !authHeader.startsWith("Basic ")) {
return unauthorizedResponse(request);
}
const base64Credentials = authHeader.split(" ")[1];
const decoded = atob(base64Credentials);
const [username, password] = decoded.split(":");
const expectedUsername = process.env.ADMIN_USERNAME;
const expectedPassword = process.env.ADMIN_PASSWORD;
if (
username !== expectedUsername ||
password !== expectedPassword
) {
return unauthorizedResponse(request);
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*", "/api/admin/:path*", "/api/policies/:path*/relationships"],
};