Public
Script
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
import { getUser, verifyPassword } from "https://esm.town/v/pomdtr/lucia_sqlite";
type BasicAuthOptions = {
userTable: string;
};
export function basicAuth(next: (Request) => Response | Promise<Response>, options: BasicAuthOptions) {
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",
},
},
);
}
const isAuth = await isRequestAuthenticated(req, options.userTable);
if (!isAuth) {
return new Response("Unauthorized", {
status: 401,
headers: {
"WWW-Authenticate": "Basic",
},
});
}
return next(req);
};
}
function extractCredentials(authorization): { username: string; password: string } {
const parts = authorization.split(" ");
if (parts[0] != "Basic") {
return null;
}
const plainAuth = atob(parts[1]);
const credentials = plainAuth.split(":");
return {
username: credentials[0],
password: credentials[1],
};
}
async function isRequestAuthenticated(req, userTable: string) {
if (!req.headers.has("authorization")) {
return false;
}
const credentials = extractCredentials(req.headers.get("authorization"));
if (!credentials) {
return false;
}
const user = await getUser(userTable, credentials.username);
if (!user) {
return false;
}
return verifyPassword(user.hashed_password, credentials.password);
}
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!
March 5, 2024