-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
basic-auth.ts
105 lines (93 loc) · 2.31 KB
/
basic-auth.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import * as kms from '@aws-cdk/aws-kms';
import * as secretsmanager from '@aws-cdk/aws-secretsmanager';
import { Construct, SecretValue } from '@aws-cdk/core';
/**
* Properties for a BasicAuth
*/
export interface BasicAuthProps {
/**
* The username
*/
readonly username: string;
/**
* The password
*
* @default - A Secrets Manager generated password
*/
readonly password?: SecretValue;
/**
* The encryption key to use to encrypt the password when it's generated
* in Secrets Manager
*
* @default - default master key
*/
readonly encryptionKey?: kms.IKey;
}
/**
* A Basic Auth configuration
*/
export interface BasicAuthConfig {
/**
* Whether to enable Basic Auth
*/
readonly enableBasicAuth: boolean;
/**
* The username
*/
readonly username: string;
/**
* The password
*/
readonly password: string;
}
/**
* Basic Auth configuration
*/
export class BasicAuth {
/**
* Creates a Basic Auth configuration from a username and a password
*
* @param username The username
* @param password The password
*/
public static fromCredentials(username: string, password: SecretValue) {
return new BasicAuth({ username, password });
}
/**
* Creates a Basic Auth configuration with a password generated in Secrets
* Manager.
*
* @param username The username
* @param encryptionKey The encryption key to use to encrypt the password in
* Secrets Manager
*/
public static fromGeneratedPassword(username: string, encryptionKey?: kms.IKey) {
return new BasicAuth({ username, encryptionKey });
}
constructor(private readonly props: BasicAuthProps) {}
/**
* Binds this Basic Auth configuration to an App
*/
public bind(scope: Construct, id: string): BasicAuthConfig {
const config = {
enableBasicAuth: true,
username: this.props.username,
};
if (this.props.password) {
return {
...config,
password: this.props.password.toString(),
};
}
const secret = new secretsmanager.Secret(scope, id, {
generateSecretString: {
secretStringTemplate: JSON.stringify({ username: this.props.username }),
generateStringKey: 'password',
},
});
return {
...config,
password: secret.secretValueFromJson('password').toString(),
};
}
}