-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproxy.ts
More file actions
66 lines (55 loc) · 1.82 KB
/
Copy pathproxy.ts
File metadata and controls
66 lines (55 loc) · 1.82 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const ADMIN_COOKIE = "admin_session";
// Must match sessionToken() in utils/adminAuth.ts. Recomputed here with Web
// Crypto because proxy code can't rely on node:crypto.
async function sessionToken(secret: string): Promise<string> {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const signature = await crypto.subtle.sign(
"HMAC",
key,
encoder.encode(ADMIN_COOKIE)
);
return Array.from(new Uint8Array(signature))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
export async function proxy(request: NextRequest) {
const { pathname, search } = request.nextUrl;
// Admin is a local authoring tool; dev runs unauthenticated, same as
// checkAdminAuth().
if (process.env.NODE_ENV !== "production") {
return NextResponse.next();
}
if (pathname === "/api/admin/login" || pathname === "/admin/login") {
return NextResponse.next();
}
if (pathname.startsWith("/admin")) {
return NextResponse.redirect(new URL("/", request.url));
}
const secret = process.env.ADMIN_SECRET;
const cookie = request.cookies.get(ADMIN_COOKIE)?.value;
const authorized =
Boolean(secret) &&
Boolean(cookie) &&
cookie === (await sessionToken(secret!));
if (authorized) {
return NextResponse.next();
}
if (pathname.startsWith("/api/admin")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const loginUrl = new URL("/admin/login", request.url);
loginUrl.searchParams.set("next", pathname + search);
return NextResponse.redirect(loginUrl);
}
export const config = {
matcher: ["/admin/:path*", "/api/admin/:path*"],
};