-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
34 lines (28 loc) · 859 Bytes
/
middleware.ts
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
import { NextRequest, NextResponse } from "next/server"
import { isValidPassword } from "./lib/isValidPassword"
export async function middleware(req: NextRequest) {
if ((await isAuthenticated(req)) === false) {
return new NextResponse("Unauthorized", {
status: 401,
headers: { "WWW-Authenticate": "Basic" },
})
}
}
async function isAuthenticated(req: NextRequest) {
const authHeader =
req.headers.get("authorization") || req.headers.get("Authorization")
if (authHeader == null) return false
const [username, password] = Buffer.from(authHeader.split(" ")[1], "base64")
.toString()
.split(":")
return (
username === process.env.ADMIN_USERNAME &&
(await isValidPassword(
password,
process.env.HASHED_ADMIN_PASSWORD as string
))
)
}
export const config = {
matcher: "/admin/:path*",
}