-
Notifications
You must be signed in to change notification settings - Fork 16
/
auth_tokens.ts
64 lines (57 loc) · 1.63 KB
/
auth_tokens.ts
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
// Copyright 2018-2024 the Deno authors. MIT license.
interface BearerAuthToken {
type: "bearer";
host: string;
token: string;
}
interface BasicAuthToken {
type: "basic";
host: string;
username: string;
password: string;
}
type AuthToken = BearerAuthToken | BasicAuthToken;
export function splitLast(
value: string,
delimiter: string,
): [string, string] {
const split = value.split(delimiter);
return [split.slice(0, -1).join(delimiter)].concat(split.slice(-1)) as [
string,
string,
];
}
function tokenAsValue(authToken: AuthToken): string {
return authToken.type === "basic"
? `Basic ${btoa(`${authToken.username}:${authToken.password}`)}`
: `Bearer ${authToken.token}`;
}
export class AuthTokens {
#tokens: AuthToken[];
constructor(tokensStr = "") {
const tokens: AuthToken[] = [];
for (const tokenStr of tokensStr.split(";").filter((s) => s.length > 0)) {
if (tokensStr.includes("@")) {
const [token, host] = splitLast(tokenStr, "@");
if (token.includes(":")) {
const [username, password] = splitLast(token, ":");
tokens.push({ type: "basic", host, username, password });
} else {
tokens.push({ type: "bearer", host, token });
}
} else {
// todo(dsherret): feel like this should error?
// deno-lint-ignore no-console
console.error("Badly formed auth token discarded.");
}
}
this.#tokens = tokens;
}
get(specifier: URL): string | undefined {
for (const token of this.#tokens) {
if (token.host.endsWith(specifier.host)) {
return tokenAsValue(token);
}
}
}
}