1
- import { Construct , Lazy , Resource , SecretValue } from '@aws-cdk/core' ;
1
+ import { Construct , Lazy , Resource , SecretValue , Stack } from '@aws-cdk/core' ;
2
2
import { IGroup } from './group' ;
3
3
import { CfnUser } from './iam.generated' ;
4
4
import { IIdentity } from './identity-base' ;
@@ -10,7 +10,15 @@ import { IPrincipal } from './principals';
10
10
import { AttachedPolicies , undefinedIfEmpty } from './util' ;
11
11
12
12
export interface IUser extends IIdentity {
13
+ /**
14
+ * The user's name
15
+ * @attribute
16
+ */
13
17
readonly userName : string ;
18
+
19
+ /**
20
+ * Adds this user to a group.
21
+ */
14
22
addToGroup ( group : IGroup ) : void ;
15
23
}
16
24
@@ -97,7 +105,53 @@ export interface UserProps {
97
105
readonly passwordResetRequired ?: boolean ;
98
106
}
99
107
100
- export class User extends Resource implements IIdentity {
108
+ /**
109
+ * Define a new IAM user
110
+ */
111
+ export class User extends Resource implements IIdentity , IUser {
112
+ /**
113
+ * Import an existing user given a username
114
+ */
115
+ public static fromUserName ( scope : Construct , id : string , userName : string ) : IUser {
116
+ const arn = Stack . of ( scope ) . formatArn ( {
117
+ service : 'iam' ,
118
+ region : '' ,
119
+ resource : 'user' ,
120
+ resourceName : userName
121
+ } ) ;
122
+
123
+ class Import extends Resource implements IUser {
124
+ public readonly grantPrincipal : IPrincipal = this ;
125
+ public readonly userName : string = userName ;
126
+ public readonly assumeRoleAction : string = 'sts:AssumeRole' ;
127
+ public readonly policyFragment : PrincipalPolicyFragment = new ArnPrincipal ( arn ) . policyFragment ;
128
+ private defaultPolicy ?: Policy ;
129
+
130
+ public addToPolicy ( statement : PolicyStatement ) : boolean {
131
+ if ( ! this . defaultPolicy ) {
132
+ this . defaultPolicy = new Policy ( this , 'Policy' ) ;
133
+ this . defaultPolicy . attachToUser ( this ) ;
134
+ }
135
+ this . defaultPolicy . addStatements ( statement ) ;
136
+ return true ;
137
+ }
138
+
139
+ public addToGroup ( _group : IGroup ) : void {
140
+ throw new Error ( 'Cannot add imported User to Group' ) ;
141
+ }
142
+
143
+ public attachInlinePolicy ( _policy : Policy ) : void {
144
+ throw new Error ( 'Cannot add inline policy to imported User' ) ;
145
+ }
146
+
147
+ public addManagedPolicy ( _policy : IManagedPolicy ) : void {
148
+ throw new Error ( 'Cannot add managed policy to imported User' ) ;
149
+ }
150
+ }
151
+
152
+ return new Import ( scope , id ) ;
153
+ }
154
+
101
155
public readonly grantPrincipal : IPrincipal = this ;
102
156
public readonly assumeRoleAction : string = 'sts:AssumeRole' ;
103
157
0 commit comments