Readme

Val Town Basic Auth

Add basic auth on top of any http val

Usage

Wrap your HTTP handler in the basicAuth middleware.

import { basicAuth } from "https://esm.town/v/pomdtr/basicAuth"; function handler(req: Request) { return new Response("You are authenticated!"); } export default basicAuth(handler, { verifyUser: (username, password) => username == "user" && password == "password" });

If you want to use an apiToken as a password:

import { basicAuth } from "https://esm.town/v/pomdtr/basicAuth"; import { verifyToken } from "https://www.val.town/v/pomdtr/verifyToken" function handler(req: Request) { return new Response("You are authenticated!"); } export default basicAuth(handler, { verifyUser: (_, password) => verifyToken(password) });
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
function extractCredentials(authorization) {
const parts = authorization.split(" ");
if (parts[0] != "Basic") {
return null;
}
const plainAuth = atob(parts[1]);
return plainAuth.split(":");
}
export type ServeHandler = (req: Request) => Response | Promise<Response>
export function basicAuth(next: ServeHandler, params: {
verifyUser: (username: string, password: string) => boolean | Promise<boolean>;
}): ServeHandler {
return async (req: Request) => {
if (req.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 (!req.headers.get("authorization")) {
return new Response("Unauthorized", {
status: 401,
headers: {
"WWW-Authenticate": "Basic",
},
});
}
const credentials = await extractCredentials(req.headers.get("authorization"));
if (!credentials) {
return new Response("Unauthorized", {
status: 401,
headers: {
"WWW-Authenticate": "Basic",
},
});
}
if (!await params.verifyUser(credentials[0], credentials[1])) {
return new Response("Unauthorized", {
status: 403,
headers: {
"WWW-Authenticate": "Basic",
},
});
}
return next(req);
};
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
v66
June 23, 2024