-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
71 lines (63 loc) · 1.53 KB
/
index.ts
File metadata and controls
71 lines (63 loc) · 1.53 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
67
68
69
70
71
export type VercelEnvTarget = "only-production" | "all" | "disabled";
export type BasicAuthOptions = {
username: string;
password: string;
/**
* Vercel 環境のどの範囲で Basic 認証を適用するか
* @default 'only-production'
*/
vercelEnvTarget?: VercelEnvTarget;
/**
* NODE_ENV=development でも Basic 認証を適用するか
* @default false
*/
dev?: boolean;
};
export function basicAuth(
request: Request,
{
username: authUsername,
password: authPassword,
vercelEnvTarget = "only-production",
dev = false,
}: BasicAuthOptions,
): Response | null {
function unauthorized() {
return new Response("Auth required", {
status: 401,
headers: {
"WWW-Authenticate": "Basic",
},
});
}
if (process.env.NODE_ENV === "development") {
if (!dev) {
return null;
}
}
if (process.env.VERCEL === "1") {
if (vercelEnvTarget === "disabled") {
return null;
}
if (vercelEnvTarget === "only-production" && process.env.VERCEL_ENV !== "production") {
return null;
}
}
const authorization = request.headers.get("authorization");
if (!authorization) {
return unauthorized();
}
const authValue = authorization.split(" ")[1];
if (authValue === undefined) {
return unauthorized();
}
try {
const [username, password] = atob(authValue).split(":");
if (username !== authUsername || password !== authPassword) {
return unauthorized();
}
} catch {
return unauthorized();
}
return null;
}