Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Basic Authentication support in middleware and update .env.example #238

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
add Basic Authentication support in middleware and update .env.example
roku-ft committed Mar 11, 2025
commit 75ac8350ea2b0dfc0c3eaafade297eeb625fc987
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
API_KEY="SOME_APIKEY"
SERVICE_DOMAIN=SERVCIE_DOMAIN
NEXT_PUBLIC_SITE_URL=https://funtech.inc/
NEXT_PUBLIC_SITE_URL=https://funtech.inc/
# Basic認証 (以下を追加するとBasic認証が有効になります)
# BASIC_AUTH_USERNAME=username
# BASIC_AUTH_PASSWORD=password
27 changes: 27 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -27,6 +27,33 @@ function getLocale(request: NextRequest): string | undefined {
const PUBLIC_FILE = /\.(.*)$/;

export function middleware(request: NextRequest) {

// Basic Auth
if (process.env.NODE_ENV !== "development" && process.env.BASIC_AUTH_USERNAME && process.env.BASIC_AUTH_PASSWORD) {
const basicAuth = request.headers.get("authorization");

if (!basicAuth) {
return new Response("Authentication required", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Secure Area"',
},
});
}

try {
const authValue = basicAuth.split(" ")[1];
const [user, pwd] = atob(authValue).split(":");

if (user !== process.env.BASIC_AUTH_USERNAME || pwd !== process.env.BASIC_AUTH_PASSWORD) {
return new Response("Unauthorized", { status: 401 });
}
} catch (e) {
return new Response("Invalid Authentication", { status: 400 });
}
}


const pathname = request.nextUrl.pathname;

// skips adding the public files