Skip to content

Commit

Permalink
fix: env var
Browse files Browse the repository at this point in the history
  • Loading branch information
yuta-ike committed Oct 28, 2023
1 parent f930f6c commit a27913c
Showing 1 changed file with 17 additions and 18 deletions.
35 changes: 17 additions & 18 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { NextRequest, NextResponse } from "next/server"

const BASIC_AUTH_USER = process.env["BASIC_AUTH_USER"]!
const BASIC_AUTH_USERNAME = process.env["BASIC_AUTH_USERNAME"]!
const BASIC_AUTH_PASSWORD = process.env["BASIC_AUTH_PASSWORD"]!

/**
* @see https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
*/
// export const config = {
// matcher: ["/:path*", "/index/:path*"],
// }
export const config = {
matcher: ["/:path*", "/index/:path*"],
}

export function middleware(req: NextRequest) {
if (process.env.NODE_ENV === "development") {
Expand All @@ -17,23 +17,22 @@ export function middleware(req: NextRequest) {

const basicAuth = req.headers.get("Authorization")

if (basicAuth) {
const authValue = basicAuth.split(" ")[1]
// atob is deprecated but Buffer.from is not available in Next.js edge.
const [user, password] = atob(authValue ?? "").split(":")

if (user === BASIC_AUTH_USER && password === BASIC_AUTH_PASSWORD) {
return NextResponse.next()
}

return NextResponse.json(
{ error: "Invalid credentials" },
{ headers: { "WWW-Authenticate": 'Basic realm="Secure Area"' }, status: 401 },
)
} else {
if (basicAuth == null) {
return NextResponse.json(
{ error: "Please enter credentials" },
{ headers: { "WWW-Authenticate": 'Basic realm="Secure Area"' }, status: 401 },
)
}

const authValue = basicAuth.split(" ")[1]
const [user, password] = atob(authValue ?? "").split(":")

if (user === BASIC_AUTH_USERNAME && password === BASIC_AUTH_PASSWORD) {
return NextResponse.next()
}

return NextResponse.json(
{ error: "Invalid credentials" },
{ headers: { "WWW-Authenticate": 'Basic realm="Secure Area"' }, status: 401 },
)
}

0 comments on commit a27913c

Please sign in to comment.