-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
43 lines (41 loc) · 1.3 KB
/
index.ts
File metadata and controls
43 lines (41 loc) · 1.3 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
/**
* Consume the value of the `Authorization` HTTP header field, succeeding when the
* value adheres to the "Basic" authentication scheme described by IETF RFC 2617.
*
* For example,
*
* writeBasicAuth({ username: "Aladdin", password: "open sesame" })
*
* produces
*
* "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
*/
export function readBasicAuth(authorization: string):
| {
success: true;
username: string;
password: string;
}
| { success: false } {
if (!authorization.startsWith(prefix)) return { success: false };
const encodedCredentials = authorization.slice(prefix.length)
const decodedCredentials = Buffer.from(encodedCredentials, "base64").toString(
"utf8",
);
const i = decodedCredentials.indexOf(':')
if (i === -1) return { success: false };
const username = decodedCredentials.slice(0, i)
const password = decodedCredentials.slice(i + 1)
return { success: true, username, password };
}
/**
* Produce a string suitable for use as the value of the `Authorization` HTTP header
* field according to the "Basic" authentication scheme described by IETF RFC 2617.
*/
export function writeBasicAuth(x: {
username: string;
password: string;
}): string {
return `${prefix}${Buffer.from(`${x.username}:${x.password}`).toString("base64")}`;
}
const prefix = "Basic "