-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
user-pool.ts
1207 lines (1057 loc) · 42.6 KB
/
user-pool.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { IRole, PolicyDocument, PolicyStatement, Role, ServicePrincipal } from '@aws-cdk/aws-iam';
import { IKey } from '@aws-cdk/aws-kms';
import * as lambda from '@aws-cdk/aws-lambda';
import { ArnFormat, Duration, IResource, Lazy, Names, RemovalPolicy, Resource, Stack, Token } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { toASCII as punycodeEncode } from 'punycode/';
import { CfnUserPool } from './cognito.generated';
import { StandardAttributeNames } from './private/attr-names';
import { ICustomAttribute, StandardAttribute, StandardAttributes } from './user-pool-attr';
import { UserPoolClient, UserPoolClientOptions } from './user-pool-client';
import { UserPoolDomain, UserPoolDomainOptions } from './user-pool-domain';
import { UserPoolEmail } from './user-pool-email';
import { IUserPoolIdentityProvider } from './user-pool-idp';
import { UserPoolResourceServer, UserPoolResourceServerOptions } from './user-pool-resource-server';
/**
* The different ways in which users of this pool can sign up or sign in.
*/
export interface SignInAliases {
/**
* Whether user is allowed to sign up or sign in with a username
* @default true
*/
readonly username?: boolean;
/**
* Whether a user is allowed to sign up or sign in with an email address
* @default false
*/
readonly email?: boolean;
/**
* Whether a user is allowed to sign up or sign in with a phone number
* @default false
*/
readonly phone?: boolean;
/**
* Whether a user is allowed to sign in with a secondary username, that can be set and modified after sign up.
* Can only be used in conjunction with `USERNAME`.
* @default false
*/
readonly preferredUsername?: boolean;
}
/**
* Attributes that can be automatically verified for users in a user pool.
*/
export interface AutoVerifiedAttrs {
/**
* Whether the email address of the user should be auto verified at sign up.
*
* Note: If both `email` and `phone` is set, Cognito only verifies the phone number. To also verify email, see here -
* https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-email-phone-verification.html
*
* @default - true, if email is turned on for `signIn`. false, otherwise.
*/
readonly email?: boolean;
/**
* Whether the phone number of the user should be auto verified at sign up.
* @default - true, if phone is turned on for `signIn`. false, otherwise.
*/
readonly phone?: boolean;
}
/**
* Triggers for a user pool
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html
*/
export interface UserPoolTriggers {
/**
* Creates an authentication challenge.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-create-auth-challenge.html
* @default - no trigger configured
*/
readonly createAuthChallenge?: lambda.IFunction;
/**
* A custom Message AWS Lambda trigger.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html
* @default - no trigger configured
*/
readonly customMessage?: lambda.IFunction;
/**
* Defines the authentication challenge.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html
* @default - no trigger configured
*/
readonly defineAuthChallenge?: lambda.IFunction;
/**
* A post-authentication AWS Lambda trigger.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-authentication.html
* @default - no trigger configured
*/
readonly postAuthentication?: lambda.IFunction;
/**
* A post-confirmation AWS Lambda trigger.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-confirmation.html
* @default - no trigger configured
*/
readonly postConfirmation?: lambda.IFunction;
/**
* A pre-authentication AWS Lambda trigger.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-authentication.html
* @default - no trigger configured
*/
readonly preAuthentication?: lambda.IFunction;
/**
* A pre-registration AWS Lambda trigger.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html
* @default - no trigger configured
*/
readonly preSignUp?: lambda.IFunction;
/**
* A pre-token-generation AWS Lambda trigger.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html
* @default - no trigger configured
*/
readonly preTokenGeneration?: lambda.IFunction;
/**
* A user-migration AWS Lambda trigger.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html
* @default - no trigger configured
*/
readonly userMigration?: lambda.IFunction;
/**
* Verifies the authentication challenge response.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-verify-auth-challenge-response.html
* @default - no trigger configured
*/
readonly verifyAuthChallengeResponse?: lambda.IFunction;
/**
* Amazon Cognito invokes this trigger to send email notifications to users.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-email-sender.html
* @default - no trigger configured
*/
readonly customEmailSender?: lambda.IFunction
/**
* Amazon Cognito invokes this trigger to send SMS notifications to users.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-sms-sender.html
* @default - no trigger configured
*/
readonly customSmsSender?: lambda.IFunction
/**
* Index signature
*/
[trigger: string]: lambda.IFunction | undefined;
}
/**
* User pool operations to which lambda triggers can be attached.
*/
export class UserPoolOperation {
/**
* Creates a challenge in a custom auth flow
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-create-auth-challenge.html
*/
public static readonly CREATE_AUTH_CHALLENGE = new UserPoolOperation('createAuthChallenge');
/**
* Advanced customization and localization of messages
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html
*/
public static readonly CUSTOM_MESSAGE = new UserPoolOperation('customMessage');
/**
* Determines the next challenge in a custom auth flow
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html
*/
public static readonly DEFINE_AUTH_CHALLENGE = new UserPoolOperation('defineAuthChallenge');
/**
* Event logging for custom analytics
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-authentication.html
*/
public static readonly POST_AUTHENTICATION = new UserPoolOperation('postAuthentication');
/**
* Custom welcome messages or event logging for custom analytics
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-confirmation.html
*/
public static readonly POST_CONFIRMATION = new UserPoolOperation('postConfirmation');
/**
* Custom validation to accept or deny the sign-in request
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-authentication.html
*/
public static readonly PRE_AUTHENTICATION = new UserPoolOperation('preAuthentication');
/**
* Custom validation to accept or deny the sign-up request
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html
*/
public static readonly PRE_SIGN_UP = new UserPoolOperation('preSignUp');
/**
* Add or remove attributes in Id tokens
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html
*/
public static readonly PRE_TOKEN_GENERATION = new UserPoolOperation('preTokenGeneration');
/**
* Migrate a user from an existing user directory to user pools
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html
*/
public static readonly USER_MIGRATION = new UserPoolOperation('userMigration');
/**
* Determines if a response is correct in a custom auth flow
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-verify-auth-challenge-response.html
*/
public static readonly VERIFY_AUTH_CHALLENGE_RESPONSE = new UserPoolOperation('verifyAuthChallengeResponse');
/**
* Amazon Cognito invokes this trigger to send email notifications to users.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-email-sender.html
*/
public static readonly CUSTOM_EMAIL_SENDER = new UserPoolOperation('customEmailSender');
/**
* Amazon Cognito invokes this trigger to send email notifications to users.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-sms-sender.html
*/
public static readonly CUSTOM_SMS_SENDER = new UserPoolOperation('customSmsSender');
/** A custom user pool operation */
public static of(name: string): UserPoolOperation {
const lowerCamelCase = name.charAt(0).toLowerCase() + name.slice(1);
return new UserPoolOperation(lowerCamelCase);
}
/** The key to use in `CfnUserPool.LambdaConfigProperty` */
public readonly operationName: string;
private constructor(operationName: string) {
this.operationName = operationName;
}
}
/**
* The email verification style
*/
export enum VerificationEmailStyle {
/** Verify email via code */
CODE = 'CONFIRM_WITH_CODE',
/** Verify email via link */
LINK = 'CONFIRM_WITH_LINK',
}
/**
* User pool configuration for user self sign up.
*/
export interface UserVerificationConfig {
/**
* The email subject template for the verification email sent to the user upon sign up.
* See https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-templates.html to
* learn more about message templates.
* @default 'Verify your new account'
*/
readonly emailSubject?: string;
/**
* The email body template for the verification email sent to the user upon sign up.
* See https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-templates.html to
* learn more about message templates.
*
* @default - 'The verification code to your new account is {####}' if VerificationEmailStyle.CODE is chosen,
* 'Verify your account by clicking on {##Verify Email##}' if VerificationEmailStyle.LINK is chosen.
*/
readonly emailBody?: string;
/**
* Emails can be verified either using a code or a link.
* Learn more at https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-email-verification-message-customization.html
* @default VerificationEmailStyle.CODE
*/
readonly emailStyle?: VerificationEmailStyle;
/**
* The message template for the verification SMS sent to the user upon sign up.
* See https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-message-templates.html to
* learn more about message templates.
*
* @default - 'The verification code to your new account is {####}' if VerificationEmailStyle.CODE is chosen,
* not configured if VerificationEmailStyle.LINK is chosen
*/
readonly smsMessage?: string;
}
/**
* User pool configuration when administrators sign users up.
*/
export interface UserInvitationConfig {
/**
* The template to the email subject that is sent to the user when an administrator signs them up to the user pool.
* @default 'Your temporary password'
*/
readonly emailSubject?: string;
/**
* The template to the email body that is sent to the user when an administrator signs them up to the user pool.
* @default 'Your username is {username} and temporary password is {####}.'
*/
readonly emailBody?: string;
/**
* The template to the SMS message that is sent to the user when an administrator signs them up to the user pool.
* @default 'Your username is {username} and temporary password is {####}'
*/
readonly smsMessage?: string;
}
/**
* The different ways in which a user pool's MFA enforcement can be configured.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html
*/
export enum Mfa {
/** Users are not required to use MFA for sign in, and cannot configure one. */
OFF = 'OFF',
/** Users are not required to use MFA for sign in, but can configure one if they so choose to. */
OPTIONAL = 'OPTIONAL',
/** Users are required to configure an MFA, and have to use it to sign in. */
REQUIRED = 'ON',
}
/**
* The different ways in which a user pool can obtain their MFA token for sign in.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html
*/
export interface MfaSecondFactor {
/**
* The MFA token is sent to the user via SMS to their verified phone numbers
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-sms-text-message.html
* @default true
*/
readonly sms: boolean;
/**
* The MFA token is a time-based one time password that is generated by a hardware or software token
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-totp.html
* @default false
*/
readonly otp: boolean;
}
/**
* Password policy for User Pools.
*/
export interface PasswordPolicy {
/**
* The length of time the temporary password generated by an admin is valid.
* This must be provided as whole days, like Duration.days(3) or Duration.hours(48).
* Fractional days, such as Duration.hours(20), will generate an error.
* @default Duration.days(7)
*/
readonly tempPasswordValidity?: Duration;
/**
* Minimum length required for a user's password.
* @default 8
*/
readonly minLength?: number;
/**
* Whether the user is required to have lowercase characters in their password.
* @default true
*/
readonly requireLowercase?: boolean;
/**
* Whether the user is required to have uppercase characters in their password.
* @default true
*/
readonly requireUppercase?: boolean;
/**
* Whether the user is required to have digits in their password.
* @default true
*/
readonly requireDigits?: boolean;
/**
* Whether the user is required to have symbols in their password.
* @default true
*/
readonly requireSymbols?: boolean;
}
/**
* Email settings for the user pool.
*/
export interface EmailSettings {
/**
* The 'from' address on the emails received by the user.
* @default [email protected]
*/
readonly from?: string;
/**
* The 'replyTo' address on the emails received by the user as defined by IETF RFC-5322.
* When set, most email clients recognize to change 'to' line to this address when a reply is drafted.
* @default - Not set.
*/
readonly replyTo?: string;
}
/**
* How will a user be able to recover their account?
*
* When a user forgets their password, they can have a code sent to their verified email or verified phone to recover their account.
* You can choose the preferred way to send codes below.
* We recommend not allowing phone to be used for both password resets and multi-factor authentication (MFA).
*
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-recover-a-user-account.html
*/
export enum AccountRecovery {
/**
* Email if available, otherwise phone, but don’t allow a user to reset their password via phone if they are also using it for MFA
*/
EMAIL_AND_PHONE_WITHOUT_MFA,
/**
* Phone if available, otherwise email, but don’t allow a user to reset their password via phone if they are also using it for MFA
*/
PHONE_WITHOUT_MFA_AND_EMAIL,
/**
* Email only
*/
EMAIL_ONLY,
/**
* Phone only, but don’t allow a user to reset their password via phone if they are also using it for MFA
*/
PHONE_ONLY_WITHOUT_MFA,
/**
* (Not Recommended) Phone if available, otherwise email, and do allow a user to reset their password via phone if they are also using it for MFA.
*/
PHONE_AND_EMAIL,
/**
* None – users will have to contact an administrator to reset their passwords
*/
NONE,
}
/**
* Device tracking settings
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html
*/
export interface DeviceTracking {
/**
* Indicates whether a challenge is required on a new device. Only applicable to a new device.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html
* @default false
*/
readonly challengeRequiredOnNewDevice: boolean;
/**
* If true, a device is only remembered on user prompt.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html
* @default false
*/
readonly deviceOnlyRememberedOnUserPrompt: boolean;
}
/**
* Props for the UserPool construct
*/
export interface UserPoolProps {
/**
* Name of the user pool
*
* @default - automatically generated name by CloudFormation at deploy time
*/
readonly userPoolName?: string;
/**
* Whether self sign up should be enabled. This can be further configured via the `selfSignUp` property.
* @default false
*/
readonly selfSignUpEnabled?: boolean;
/**
* Configuration around users signing themselves up to the user pool.
* Enable or disable self sign-up via the `selfSignUpEnabled` property.
* @default - see defaults in UserVerificationConfig
*/
readonly userVerification?: UserVerificationConfig;
/**
* Configuration around admins signing up users into a user pool.
* @default - see defaults in UserInvitationConfig
*/
readonly userInvitation?: UserInvitationConfig;
/**
* The IAM role that Cognito will assume while sending SMS messages.
* @default - a new IAM role is created
*/
readonly smsRole?: IRole;
/**
* The 'ExternalId' that Cognito service must using when assuming the `smsRole`, if the role is restricted with an 'sts:ExternalId' conditional.
* Learn more about ExternalId here - https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html
*
* This property will be ignored if `smsRole` is not specified.
* @default - No external id will be configured
*/
readonly smsRoleExternalId?: string;
/**
* Setting this would explicitly enable or disable SMS role creation.
* When left unspecified, CDK will determine based on other properties if a role is needed or not.
* @default - CDK will determine based on other properties of the user pool if an SMS role should be created or not.
*/
readonly enableSmsRole?: boolean;
/**
* Methods in which a user registers or signs in to a user pool.
* Allows either username with aliases OR sign in with email, phone, or both.
*
* Read the sections on usernames and aliases to learn more -
* https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html
*
* To match with 'Option 1' in the above link, with a verified email, this property should be set to
* `{ username: true, email: true }`. To match with 'Option 2' in the above link with both a verified email and phone
* number, this property should be set to `{ email: true, phone: true }`.
*
* @default { username: true }
*/
readonly signInAliases?: SignInAliases;
/**
* Attributes which Cognito will look to verify automatically upon user sign up.
* EMAIL and PHONE are the only available options.
*
* @default - If `signInAlias` includes email and/or phone, they will be included in `autoVerifiedAttributes` by default.
* If absent, no attributes will be auto-verified.
*/
readonly autoVerify?: AutoVerifiedAttrs;
/**
* The set of attributes that are required for every user in the user pool.
* Read more on attributes here - https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html
*
* @default - All standard attributes are optional and mutable.
*/
readonly standardAttributes?: StandardAttributes;
/**
* Define a set of custom attributes that can be configured for each user in the user pool.
*
* @default - No custom attributes.
*/
readonly customAttributes?: { [key: string]: ICustomAttribute };
/**
* Configure whether users of this user pool can or are required use MFA to sign in.
*
* @default Mfa.OFF
*/
readonly mfa?: Mfa;
/**
* The SMS message template sent during MFA verification.
* Use '{####}' in the template where Cognito should insert the verification code.
* @default 'Your authentication code is {####}.'
*/
readonly mfaMessage?: string;
/**
* Configure the MFA types that users can use in this user pool. Ignored if `mfa` is set to `OFF`.
*
* @default - { sms: true, otp: false }, if `mfa` is set to `OPTIONAL` or `REQUIRED`.
* { sms: false, otp: false }, otherwise
*/
readonly mfaSecondFactor?: MfaSecondFactor;
/**
* Password policy for this user pool.
* @default - see defaults on each property of PasswordPolicy.
*/
readonly passwordPolicy?: PasswordPolicy;
/**
* Email settings for a user pool.
*
* @default - see defaults on each property of EmailSettings.
* @deprecated Use 'email' instead.
*/
readonly emailSettings?: EmailSettings;
/**
* Email settings for a user pool.
* @default - cognito will use the default email configuration
*/
readonly email?: UserPoolEmail;
/**
* Lambda functions to use for supported Cognito triggers.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html
* @default - No Lambda triggers.
*/
readonly lambdaTriggers?: UserPoolTriggers;
/**
* Whether sign-in aliases should be evaluated with case sensitivity.
* For example, when this option is set to false, users will be able to sign in using either `MyUsername` or `myusername`.
* @default true
*/
readonly signInCaseSensitive?: boolean;
/**
* How will a user be able to recover their account?
*
* @default AccountRecovery.PHONE_WITHOUT_MFA_AND_EMAIL
*/
readonly accountRecovery?: AccountRecovery;
/**
* Policy to apply when the user pool is removed from the stack
*
* @default RemovalPolicy.RETAIN
*/
readonly removalPolicy?: RemovalPolicy;
/**
* Device tracking settings
* @default - see defaults on each property of DeviceTracking.
*/
readonly deviceTracking?: DeviceTracking;
/**
* This key will be used to encrypt temporary passwords and authorization codes that Amazon Cognito generates.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-sender-triggers.html
* @default - no key ID configured
*/
readonly customSenderKmsKey?: IKey;
}
/**
* Represents a Cognito UserPool
*/
export interface IUserPool extends IResource {
/**
* The physical ID of this user pool resource
* @attribute
*/
readonly userPoolId: string;
/**
* The ARN of this user pool resource
* @attribute
*/
readonly userPoolArn: string;
/**
* Get all identity providers registered with this user pool.
*/
readonly identityProviders: IUserPoolIdentityProvider[];
/**
* Add a new app client to this user pool.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html
*/
addClient(id: string, options?: UserPoolClientOptions): UserPoolClient;
/**
* Associate a domain to this user pool.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain.html
*/
addDomain(id: string, options: UserPoolDomainOptions): UserPoolDomain;
/**
* Add a new resource server to this user pool.
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-resource-servers.html
*/
addResourceServer(id: string, options: UserPoolResourceServerOptions): UserPoolResourceServer;
/**
* Register an identity provider with this user pool.
*/
registerIdentityProvider(provider: IUserPoolIdentityProvider): void;
}
abstract class UserPoolBase extends Resource implements IUserPool {
public abstract readonly userPoolId: string;
public abstract readonly userPoolArn: string;
public readonly identityProviders: IUserPoolIdentityProvider[] = [];
public addClient(id: string, options?: UserPoolClientOptions): UserPoolClient {
return new UserPoolClient(this, id, {
userPool: this,
...options,
});
}
public addDomain(id: string, options: UserPoolDomainOptions): UserPoolDomain {
return new UserPoolDomain(this, id, {
userPool: this,
...options,
});
}
public addResourceServer(id: string, options: UserPoolResourceServerOptions): UserPoolResourceServer {
return new UserPoolResourceServer(this, id, {
userPool: this,
...options,
});
}
public registerIdentityProvider(provider: IUserPoolIdentityProvider) {
this.identityProviders.push(provider);
}
}
/**
* Define a Cognito User Pool
*/
export class UserPool extends UserPoolBase {
/**
* Import an existing user pool based on its id.
*/
public static fromUserPoolId(scope: Construct, id: string, userPoolId: string): IUserPool {
let userPoolArn = Stack.of(scope).formatArn({
service: 'cognito-idp',
resource: 'userpool',
resourceName: userPoolId,
});
return UserPool.fromUserPoolArn(scope, id, userPoolArn);
}
/**
* Import an existing user pool based on its ARN.
*/
public static fromUserPoolArn(scope: Construct, id: string, userPoolArn: string): IUserPool {
const arnParts = Stack.of(scope).splitArn(userPoolArn, ArnFormat.SLASH_RESOURCE_NAME);
if (!arnParts.resourceName) {
throw new Error('invalid user pool ARN');
}
const userPoolId = arnParts.resourceName;
class ImportedUserPool extends UserPoolBase {
public readonly userPoolArn = userPoolArn;
public readonly userPoolId = userPoolId;
constructor() {
super(scope, id, {
account: arnParts.account,
region: arnParts.region,
});
}
}
return new ImportedUserPool();
}
/**
* The physical ID of this user pool resource
*/
public readonly userPoolId: string;
/**
* The ARN of the user pool
*/
public readonly userPoolArn: string;
/**
* User pool provider name
* @attribute
*/
public readonly userPoolProviderName: string;
/**
* User pool provider URL
* @attribute
*/
public readonly userPoolProviderUrl: string;
private triggers: CfnUserPool.LambdaConfigProperty = {};
constructor(scope: Construct, id: string, props: UserPoolProps = {}) {
super(scope, id);
const signIn = this.signInConfiguration(props);
if (props.customSenderKmsKey) {
const kmsKey = props.customSenderKmsKey;
(this.triggers as any).kmsKeyId = kmsKey.keyArn;
}
if (props.lambdaTriggers) {
for (const t of Object.keys(props.lambdaTriggers)) {
let trigger: lambda.IFunction | undefined;
switch (t) {
case 'customSmsSender':
case 'customEmailSender':
if (!this.triggers.kmsKeyId) {
throw new Error('you must specify a KMS key if you are using customSmsSender or customEmailSender.');
}
trigger = props.lambdaTriggers[t];
const version = 'V1_0';
if (trigger !== undefined) {
this.addLambdaPermission(trigger as lambda.IFunction, t);
(this.triggers as any)[t] = {
lambdaArn: trigger.functionArn,
lambdaVersion: version,
};
}
break;
default:
trigger = props.lambdaTriggers[t] as lambda.IFunction | undefined;
if (trigger !== undefined) {
this.addLambdaPermission(trigger as lambda.IFunction, t);
(this.triggers as any)[t] = (trigger as lambda.IFunction).functionArn;
}
break;
}
}
}
const verificationMessageTemplate = this.verificationMessageConfiguration(props);
let emailVerificationMessage;
let emailVerificationSubject;
if (verificationMessageTemplate.defaultEmailOption === VerificationEmailStyle.CODE) {
emailVerificationMessage = verificationMessageTemplate.emailMessage;
emailVerificationSubject = verificationMessageTemplate.emailSubject;
}
const smsVerificationMessage = verificationMessageTemplate.smsMessage;
const inviteMessageTemplate: CfnUserPool.InviteMessageTemplateProperty = {
emailMessage: props.userInvitation?.emailBody,
emailSubject: props.userInvitation?.emailSubject,
smsMessage: props.userInvitation?.smsMessage,
};
const selfSignUpEnabled = props.selfSignUpEnabled ?? false;
const adminCreateUserConfig: CfnUserPool.AdminCreateUserConfigProperty = {
allowAdminCreateUserOnly: !selfSignUpEnabled,
inviteMessageTemplate: props.userInvitation !== undefined ? inviteMessageTemplate : undefined,
};
const passwordPolicy = this.configurePasswordPolicy(props);
if (props.email && props.emailSettings) {
throw new Error('you must either provide "email" or "emailSettings", but not both');
}
const emailConfiguration = props.email ? props.email._bind(this) : undefinedIfNoKeys({
from: encodePuny(props.emailSettings?.from),
replyToEmailAddress: encodePuny(props.emailSettings?.replyTo),
});
const userPool = new CfnUserPool(this, 'Resource', {
userPoolName: props.userPoolName,
usernameAttributes: signIn.usernameAttrs,
aliasAttributes: signIn.aliasAttrs,
autoVerifiedAttributes: signIn.autoVerifyAttrs,
lambdaConfig: Lazy.any({ produce: () => undefinedIfNoKeys(this.triggers) }),
smsAuthenticationMessage: this.mfaMessage(props),
smsConfiguration: this.smsConfiguration(props),
adminCreateUserConfig,
emailVerificationMessage,
emailVerificationSubject,
smsVerificationMessage,
verificationMessageTemplate,
schema: this.schemaConfiguration(props),
mfaConfiguration: props.mfa,
enabledMfas: this.mfaConfiguration(props),
policies: passwordPolicy !== undefined ? { passwordPolicy } : undefined,
emailConfiguration,
usernameConfiguration: undefinedIfNoKeys({
caseSensitive: props.signInCaseSensitive,
}),
accountRecoverySetting: this.accountRecovery(props),
deviceConfiguration: props.deviceTracking,
});
userPool.applyRemovalPolicy(props.removalPolicy);
this.userPoolId = userPool.ref;
this.userPoolArn = userPool.attrArn;
this.userPoolProviderName = userPool.attrProviderName;
this.userPoolProviderUrl = userPool.attrProviderUrl;
}
/**
* Add a lambda trigger to a user pool operation
* @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html
*/
public addTrigger(operation: UserPoolOperation, fn: lambda.IFunction): void {
if (operation.operationName in this.triggers) {
throw new Error(`A trigger for the operation ${operation.operationName} already exists.`);
}
this.addLambdaPermission(fn, operation.operationName);
switch (operation.operationName) {
case 'customEmailSender':
case 'customSmsSender':
if (!this.triggers.kmsKeyId) {
throw new Error('you must specify a KMS key if you are using customSmsSender or customEmailSender.');
}
(this.triggers as any)[operation.operationName] = {
lambdaArn: fn.functionArn,
lambdaVersion: 'V1_0',
};
break;
default:
(this.triggers as any)[operation.operationName] = fn.functionArn;
}
}
private addLambdaPermission(fn: lambda.IFunction, name: string): void {
const capitalize = name.charAt(0).toUpperCase() + name.slice(1);
fn.addPermission(`${capitalize}Cognito`, {
principal: new ServicePrincipal('cognito-idp.amazonaws.com'),
sourceArn: this.userPoolArn,
});
}
private mfaMessage(props: UserPoolProps): string | undefined {
const CODE_TEMPLATE = '{####}';
const MAX_LENGTH = 140;
const message = props.mfaMessage;
if (message && !Token.isUnresolved(message)) {
if (!message.includes(CODE_TEMPLATE)) {
throw new Error(`MFA message must contain the template string '${CODE_TEMPLATE}'`);
}
if (message.length > MAX_LENGTH) {
throw new Error(`MFA message must be between ${CODE_TEMPLATE.length} and ${MAX_LENGTH} characters`);
}
}
return message;
}
private verificationMessageConfiguration(props: UserPoolProps): CfnUserPool.VerificationMessageTemplateProperty {
const CODE_TEMPLATE = '{####}';
const VERIFY_EMAIL_TEMPLATE = '{##Verify Email##}';
const emailStyle = props.userVerification?.emailStyle ?? VerificationEmailStyle.CODE;
const emailSubject = props.userVerification?.emailSubject ?? 'Verify your new account';
const smsMessage = props.userVerification?.smsMessage ?? `The verification code to your new account is ${CODE_TEMPLATE}`;
if (emailStyle === VerificationEmailStyle.CODE) {
const emailMessage = props.userVerification?.emailBody ?? `The verification code to your new account is ${CODE_TEMPLATE}`;
if (!Token.isUnresolved(emailMessage) && emailMessage.indexOf(CODE_TEMPLATE) < 0) {
throw new Error(`Verification email body must contain the template string '${CODE_TEMPLATE}'`);
}
if (!Token.isUnresolved(smsMessage) && smsMessage.indexOf(CODE_TEMPLATE) < 0) {
throw new Error(`SMS message must contain the template string '${CODE_TEMPLATE}'`);
}
return {
defaultEmailOption: VerificationEmailStyle.CODE,
emailMessage,
emailSubject,
smsMessage,
};
} else {
const emailMessage = props.userVerification?.emailBody ??
`Verify your account by clicking on ${VERIFY_EMAIL_TEMPLATE}`;
if (!Token.isUnresolved(emailMessage) && emailMessage.indexOf(VERIFY_EMAIL_TEMPLATE) < 0) {
throw new Error(`Verification email body must contain the template string '${VERIFY_EMAIL_TEMPLATE}'`);
}
return {
defaultEmailOption: VerificationEmailStyle.LINK,
emailMessageByLink: emailMessage,
emailSubjectByLink: emailSubject,
smsMessage,
};
}
}
private signInConfiguration(props: UserPoolProps) {
let aliasAttrs: string[] | undefined;
let usernameAttrs: string[] | undefined;
let autoVerifyAttrs: string[] | undefined;
const signIn: SignInAliases = props.signInAliases ?? { username: true };
if (signIn.preferredUsername && !signIn.username) {
throw new Error('username signIn must be enabled if preferredUsername is enabled');
}