-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
40 lines (34 loc) · 1.08 KB
/
Copy pathmiddleware.ts
File metadata and controls
40 lines (34 loc) · 1.08 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const decodeBase64 = (value: string) => {
if (typeof atob === "function") {
return atob(value);
}
return Buffer.from(value, "base64").toString("utf8");
};
export function middleware(request: NextRequest) {
const username = process.env.CMS_ADMIN_USER || process.env.KEYSTATIC_ADMIN_USER;
const password = process.env.CMS_ADMIN_PASSWORD || process.env.KEYSTATIC_ADMIN_PASSWORD;
if (!username || !password) {
return new NextResponse("CMS auth is not configured.", {
status: 500,
});
}
const auth = request.headers.get("authorization") || "";
if (auth.startsWith("Basic ")) {
const decoded = decodeBase64(auth.slice(6));
const [user, pass] = decoded.split(":");
if (user === username && pass === password) {
return NextResponse.next();
}
}
return new NextResponse("Authentication required.", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="CMS"',
},
});
}
export const config = {
matcher: ["/admin", "/admin/:path*"],
};