-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathauth.ts
More file actions
67 lines (58 loc) · 1.89 KB
/
Copy pathauth.ts
File metadata and controls
67 lines (58 loc) · 1.89 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/** Authentication types and helpers. */
// =============================================================================
// Auth method type
// =============================================================================
/** Supported authentication types. */
export enum AuthType {
BEARER = "bearer",
API_KEY = "apiKey",
NONE = "none",
}
/** Authentication method for API requests. */
export type AuthMethod =
| { type: AuthType.BEARER; token: string }
| { type: AuthType.API_KEY; key: string; header?: string }
| { type: AuthType.NONE };
// =============================================================================
// Auth constructor functions
// =============================================================================
/** Auth namespace for creating authentication configurations. */
export const Auth = {
/**
* Bearer token authentication.
*
* @example
* Auth.bearer("your-jwt-token")
*/
bearer(token: string): AuthMethod {
return { type: AuthType.BEARER, token };
},
/**
* API key authentication.
*
* @example
* Auth.apiKey("your-api-key")
* Auth.apiKey("your-api-key", "X-Custom-Header")
*/
apiKey(key: string, header = "X-API-Key"): AuthMethod {
return { type: AuthType.API_KEY, key, header };
},
/** No authentication. */
none(): AuthMethod {
return { type: AuthType.NONE };
},
};
// =============================================================================
// Auth header builder function
// =============================================================================
/** Builds authorization headers from an auth method. */
export function buildAuthHeaders(auth: AuthMethod): Record<string, string> {
switch (auth.type) {
case AuthType.BEARER:
return { Authorization: `Bearer ${auth.token}` };
case AuthType.API_KEY:
return { [auth.header ?? "X-API-Key"]: auth.key };
default:
return {};
}
}