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
type Options = {
username: string;
password: string;
};
export const validAuthHeader = (options: Options): string => {
const { username, password } = options;
return `Basic ${btoa(`${username}:${password}`)}`;
};
export function authMiddleware(
handler: (Request) => Promise<Response>,
options: Options,
): (Request) => Promise<Response> {
const validAuth = validAuthHeader(options);
return async (request: Request): Promise<Response> => {
// iframe logic borrowed from pomdtr/basicAuth
if (request.headers.get("referer") == "https://www.val.town/") {
return new Response(
`Basic Auth is disabled in Val Town iframes.
<a href="/" target="blank_">Open in a new tab.</a>`,
{
status: 400,
headers: {
"Content-type": "text/html",
},
},
);
}
// If we received JSON or the request wants JSON, respond with JSON
const isJson = request.headers.get("Accept") === "application/json"
|| request.headers.get("Content-Type") === "application/json";
const authHeader = request.headers.get("Authorization");
if (authHeader == null) {
if (isJson) return Response.json({ ok: false, error: "Unauthorized" }, { status: 401 });
return new Response("Unauthorized", {
status: 401,
// This header tells browsers to try to authenticate with the builtin username/password prompt
headers: {
"WWW-Authenticate": "Basic",
},
});
}
if (authHeader !== validAuth) {
console.log({ authHeader, validAuth });
if (isJson) return Response.json({ ok: false, error: "Unauthorized" }, { status: 401 });
return new Response("Unauthorized", { status: 401 });
}
return handler(request);
};
}
export default async function(req: Request): Promise<Response> {
return new Response("This is middleware only");
}