This repository was archived by the owner on Mar 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathcognito.js
715 lines (680 loc) · 20.2 KB
/
cognito.js
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
'use strict';
var rfr = require('rfr');
var logger = rfr('util/logger');
var config = rfr('config');
var AWS = config.AWS;
var cf = rfr('/util/cloudFormation');
let identityPools = new AWS.CognitoIdentity();
let userPools = new AWS.CognitoIdentityServiceProvider();
let identityPoolName = config.getName('identityPool').replace(/-/g, '_');
let userPoolName = config.getName('userPool');
let userPoolAdminClientName = userPoolName + '-admin-client';
let userPoolAppClientName = userPoolName + '-app-client';
let newUserTempPassword = 'Temp123!';
function createUserPool() {
let params = {
PoolName: userPoolName,
AutoVerifiedAttributes: [
'email'
],
Schema: [
{
AttributeDataType: 'String',
Name: 'email',
Required: true
},
{
AttributeDataType: 'String',
Name: 'family_name',
Required: true
},
{
AttributeDataType: 'String',
Name: 'given_name',
Required: true
}
]
};
return new Promise((resolve, reject) => {
userPools.createUserPool(params, function (err, data) {
if (err) {
if (err.code === 'ResourceConflictException') {
resolve('User pool already exists');
return;
} else {
reject(err);
return;
}
}
logger.info('Created Cognito User Pool', params.PoolName);
resolve(data);
});
}).then(createUserPoolClients);
}
function safeCreateUserPool() {
let listUserPoolsParams = {
MaxResults: 60
};
return new Promise((resolve, reject) => {
userPools.listUserPools(listUserPoolsParams, (err, data) => {
if (err) {
reject(err);
}
for (let i = 0; i < data.UserPools.length; i++) {
// Check if existing user pool matches desired user pool name
if (data.UserPools[i].Name === config.getName('userPool')) {
// Name match found. Return and resolve
logger.info('User pool already exists');
resolve('User pool already exists');
return;
}
}
// No name match found. Create new user pool
resolve(createUserPool());
});
});
}
function createUserPoolClient(params) {
return new Promise((resolve, reject) => {
userPools.createUserPoolClient(params, (err, data) => {
if (err) {
if (err.code === 'ResourceConflictException') {
resolve('User pool client ' + params.ClientName + ' already exists');
return;
} else {
reject(err);
return;
}
}
logger.info('Created Cognito User Pool Client', params.ClientName);
resolve(data);
});
});
}
function createUserPoolClients(data) {
return new Promise((resolve, reject) => {
let userPoolId = data.UserPool.Id;
let adminClientParams = {
ClientName: userPoolAdminClientName,
UserPoolId: userPoolId,
ExplicitAuthFlows: [
'ADMIN_NO_SRP_AUTH'
],
GenerateSecret: false,
ReadAttributes: [
'address',
'birthdate',
'email',
'email_verified',
'family_name',
'gender',
'given_name',
'locale',
'middle_name',
'name',
'nickname',
'phone_number',
'phone_number_verified',
'picture',
'preferred_username',
'profile',
'zoneinfo',
'updated_at',
'website'
],
RefreshTokenValidity: 1,
WriteAttributes: [
'address',
'birthdate',
'email',
'family_name',
'gender',
'given_name',
'locale',
'middle_name',
'name',
'nickname',
'phone_number',
'picture',
'preferred_username',
'profile',
'zoneinfo',
'updated_at',
'website'
]
};
// Localhost callback below is only included for demo and development purposes
// For production use, only HTTPS (or custom URI scheme for mobile) callbacks should be used
// Best practice is to have separate app clients for admin operations (adding to groups, no SRP, etc.) vs. regular client interactions, as well as development vs. production.
let appClientParams = {
ClientName: userPoolAppClientName,
UserPoolId: userPoolId,
AllowedOAuthFlows: [
'code'
],
AllowedOAuthFlowsUserPoolClient: true,
AllowedOAuthScopes: [
'email',
'openid',
'profile'
],
CallbackURLs: [
'http://localhost:8100',
'spacefinder://callback'
],
DefaultRedirectURI: 'http://localhost:8100',
GenerateSecret: false,
LogoutURLs: [],
ReadAttributes: [
'email',
'email_verified',
'family_name',
'given_name',
'name',
'preferred_username',
'updated_at',
],
RefreshTokenValidity: 30,
SupportedIdentityProviders: [
'COGNITO'
],
WriteAttributes: [
'email',
'family_name',
'given_name',
'name',
'preferred_username',
'updated_at'
]
};
createUserPoolClient(appClientParams).then(() => {
// Create admin client after app client successfully created
createUserPoolClient(adminClientParams).then(() => {
resolve(createUserPoolDomain(userPoolId));
}).catch((err) => {
reject(err);
});
}).catch((err) => {
reject(err);
});
});
}
function getUserPoolId() {
let listUserPoolsParams = {
MaxResults: 60
};
return new Promise((resolve, reject) => {
userPools.listUserPools(listUserPoolsParams, function (err, data) {
if (err) {
reject(err);
return;
}
let found = false;
for (let i = 0; i < data.UserPools.length; i++) {
// Loop through user pools to find desired user pool and return Id
if (data.UserPools[i].Name === userPoolName) {
resolve(data.UserPools[i].Id);
found = true;
}
}
if (!found) {
reject(new Error(`Could not find userPool ${userPoolName}`));
}
});
});
}
function getUserPoolClientId(userPoolClientName, userPoolId) {
let listUserPoolClientsParams = {
MaxResults: 60,
UserPoolId: userPoolId
};
return new Promise((resolve, reject) => {
userPools.listUserPoolClients(listUserPoolClientsParams, function (err, data) {
if (err) {
reject(err);
return;
}
let found = false;
for (let i = 0; i < data.UserPoolClients.length; i++) {
// Loop through user pools to find desired user pool and return Id
if (data.UserPoolClients[i].ClientName === userPoolClientName) {
resolve(data.UserPoolClients[i].ClientId);
found = true;
}
}
if (!found) {
reject(new Error(`Could not find userPool ${userPoolClientName}`));
}
});
});
}
function createIdentityPool() {
return new Promise((resolve, reject) => {
getUserPoolId().then((userPoolId) => {
let listUserPoolClientParams = {
UserPoolId: userPoolId,
MaxResults: 60
};
userPools.listUserPoolClients(listUserPoolClientParams, function (err, data) {
if (err) {
reject(err);
return;
}
let userPoolClientIds = [];
for (let i = 0; i < data.UserPoolClients.length; i++) {
// Loop through user pool clients to find desired user pool client and return Id
if (data.UserPoolClients[i].ClientName === userPoolAppClientName || data.UserPoolClients[i].ClientName === userPoolAdminClientName) {
userPoolClientIds.push(data.UserPoolClients[i].ClientId);
}
}
if (userPoolClientIds.length !== 0) {
resolve(createIdentityPoolImpl(userPoolId, userPoolClientIds));
} else {
// Reject promise if no match is found
reject(new Error('No user pool client was defined in user pool'));
}
});
});
});
}
function createIdentityPoolImpl(userPoolId, userPoolClientIds) {
let cognitoIdentityProviders = [];
for (var i = 0; i < userPoolClientIds.length; i++) {
let provider = {
ClientId: userPoolClientIds[i],
ProviderName: 'cognito-idp.' + config.AWS_REGION + '.amazonaws.com/' + userPoolId
};
cognitoIdentityProviders.push(provider);
}
let params = {
AllowUnauthenticatedIdentities: false,
IdentityPoolName: identityPoolName,
CognitoIdentityProviders: cognitoIdentityProviders
};
return new Promise((resolve, reject) => {
identityPools.createIdentityPool(params, function (err) {
if (err) {
if (err.code === 'ResourceConflictException') {
resolve('Identity pool already exists');
return;
} else {
reject(err);
return;
}
}
logger.info('Created Cognito Identity Pool', params.IdentityPoolName);
resolve(setIdentityPoolRoles(userPoolId, userPoolClientIds));
});
});
}
function safeCreateIdentityPool() {
let listIdentityPoolsParams = {
MaxResults: 60
};
return new Promise((resolve, reject) => {
identityPools.listIdentityPools(listIdentityPoolsParams, function (err, data) {
if (err) {
reject(err);
return;
}
for (let i = 0; i < data.IdentityPools.length; i++) {
// Check if existing user pool matches desired user pool name
if (data.IdentityPools[i].IdentityPoolName === identityPoolName) {
// Name match found. Return and resolve
logger.info('Identity pool already exists');
resolve('Identity pool already exists');
return;
}
}
// No name match found. Create new user pool
resolve(createIdentityPool());
});
});
}
function getIdentityPoolId() {
let listIdentityPoolsParams = {
MaxResults: 60
};
return new Promise((resolve, reject) => {
identityPools.listIdentityPools(listIdentityPoolsParams, function (err, data) {
if (err) {
reject(err);
return;
}
for (let i = 0; i < data.IdentityPools.length; i++) {
// Loop through user pools to find desired user pool and return Id
if (data.IdentityPools[i].IdentityPoolName === identityPoolName) {
resolve(data.IdentityPools[i].IdentityPoolId);
break;
}
}
reject(new Error('No matching identity pool ID found'));
});
});
}
function setIdentityPoolRoles(userPoolId, userPoolClientIds) {
return cf.getStackOutputs().then((cfOutputs) => {
let cognitoAuthStandardRoleArn = cfOutputs.CognitoIdentityPoolAuthStandardRoleArn;
let cognitoUnAuthRoleArn = cfOutputs.CognitoIdentityPoolUnAuthRoleArn;
return getIdentityPoolId().then((identityPoolId) => {
let userPoolRoleMappings = {};
for (let i = 0; i < userPoolClientIds.length; i++) {
userPoolRoleMappings['cognito-idp.' + config.AWS_REGION + '.amazonaws.com/' + userPoolId + ':' + userPoolClientIds[i]] = {
Type: 'Token',
AmbiguousRoleResolution: 'AuthenticatedRole'
};
}
let params = {
IdentityPoolId: identityPoolId,
Roles: {
authenticated: cognitoAuthStandardRoleArn,
unauthenticated: cognitoUnAuthRoleArn
},
RoleMappings: userPoolRoleMappings
};
return new Promise((resolve, reject) => {
identityPools.setIdentityPoolRoles(params, function (err) {
if (err) {
reject(err);
return;
}
logger.info('Setup Cognito Identity Pools user roles');
resolve('Setup Cognito Identity Pools user roles');
});
});
});
});
}
function deleteIdentityPool() {
return getIdentityPoolId().then((identityPoolId) => {
let params = {
IdentityPoolId: identityPoolId
};
identityPools.deleteIdentityPool(params, function (err, data) {
if (err) {
throw (new Error(err));
}
return (data);
});
});
}
function deleteUserPool() {
return getUserPoolId().then((userPoolId) => {
let params = {
UserPoolId: userPoolId
};
return deleteUserPoolDomain(userPoolId).then(() => {
userPools.deleteUserPool(params, function (err, data) {
if (err) {
throw (new Error(err));
}
return (data);
});
});
});
}
/**
* The function creates a Cognito UserGroup based on the input argument.
* If the group already exists, then it ignores the request.
* @param group The group we want to create
* @returns {Promise.<TResult>|*}
*/
function adminCreateGroup(group) {
return getUserPoolId().then((userPoolId) => {
return cf.getStackOutputs().then((cfOutputs) => {
let roleArns = {};
roleArns.cognitoAuthAdminRoleArn = cfOutputs.CognitoIdentityPoolAuthAdminRoleArn;
roleArns.cognitoAuthStandardRoleArn = cfOutputs.CognitoIdentityPoolAuthStandardRoleArn;
roleArns.cognitoUnAuthRoleArn = cfOutputs.CognitoIdentityPoolUnAuthRoleArn;
logger.info('Incoming request to crate group %s', group.name);
let listParams = {
UserPoolId: userPoolId
};
let params = {
UserPoolId: userPoolId,
GroupName: group.name,
Description: group.description,
Precedence: group.precedence,
RoleArn: roleArns[group.roleArn]
};
userPools.listGroups(listParams, function (err, listData) {
if (err) {
throw (new Error(err));
}
for (let userGroupIndex in listData.Groups) {
if (listData.Groups[userGroupIndex].GroupName === group.name) {
logger.info('Group %s already exists, ignoring', group.name);
return;
}
}
userPools.createGroup(params, function (err, data) {
if (err) {
throw (new Error(err));
}
return (data);
})
});
});
});
}
function adminCreateUser(userData) {
return getUserPoolId().then((userPoolId) => {
let createUserParams = {
UserPoolId: userPoolId,
Username: userData.username,
MessageAction: 'SUPPRESS',
TemporaryPassword: newUserTempPassword,
UserAttributes: [
{
Name: 'email',
Value: userData.email
},
{
Name: 'given_name',
Value: userData.givenName
},
{
Name: 'family_name',
Value: userData.familyName
}
]
};
let listUserParams = {
UserPoolId: userPoolId
};
userPools.listUsers(listUserParams, function (err, listUsersData) {
if (err) {
throw (new Error(err));
}
for (let poolUserIndex in listUsersData.Users) {
if (listUsersData.Users[poolUserIndex].Username === userData.username) {
logger.info('User %s already exists, ignoring', userData.username);
return;
}
}
userPools.adminCreateUser(createUserParams, function (err) {
if (err) {
throw (new Error(err));
}
return initialChangePassword(userData);
});
});
});
}
function adminAssignUserToGroup(user, group) {
return getUserPoolId().then((userPoolId) => {
let params = {
UserPoolId: userPoolId,
Username: user.username,
GroupName: group.name
};
userPools.adminAddUserToGroup(params, function (err, data) {
if (err) {
throw (new Error(err));
}
return (data);
})
});
}
function initialChangePassword(userData) {
return new Promise((resolve, reject) => {
getUserPoolId().then((userPoolId) => {
getUserPoolClientId(userPoolAdminClientName, userPoolId).then((userPoolClientId) => {
let adminInitiateAuthParams = {
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId: userPoolClientId,
UserPoolId: userPoolId,
AuthParameters: {
USERNAME: userData.username,
PASSWORD: newUserTempPassword
}
};
userPools.adminInitiateAuth(adminInitiateAuthParams, function (err, data) {
if (err) {
logger.error(err);
reject(err);
}
let adminChallengeResponse = {
ChallengeName: 'NEW_PASSWORD_REQUIRED',
ClientId: userPoolClientId,
UserPoolId: userPoolId,
ChallengeResponses: {
USERNAME: userData.username,
NEW_PASSWORD: userData.password
},
Session: data.Session
};
userPools.adminRespondToAuthChallenge(adminChallengeResponse, function (err, data) {
if (err) {
logger.error(err);
reject(err);
}
resolve(data);
});
});
});
})
});
}
function getIdentityPoolUserId(userData) {
return new Promise((resolve, reject) => {
getUserPoolId().then((userPoolId) => {
getUserPoolClientId(userPoolAdminClientName, userPoolId).then((userPoolClientId) => {
let adminInitiateAuthParams = {
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId: userPoolClientId,
UserPoolId: userPoolId,
AuthParameters: {
USERNAME: userData.username,
PASSWORD: userData.password
}
};
userPools.adminInitiateAuth(adminInitiateAuthParams, function (err, data) {
if (err) {
logger.error(err);
reject(err);
}
let cognitoIdToken = data.AuthenticationResult.IdToken;
getIdentityPoolId().then((identityPoolId) => {
let cognitoIdpKey = 'cognito-idp.' + config.AWS_REGION + '.amazonaws.com/' + userPoolId;
let getIdParams = {
IdentityPoolId: identityPoolId,
Logins: {}
};
getIdParams.Logins[cognitoIdpKey] = cognitoIdToken;
logger.info('getIdParams', getIdParams);
identityPools.getId(getIdParams, function (err, data) {
if (err) {
logger.error(err);
reject(err);
}
logger.info('GetID Success', data);
resolve(data);
});
});
});
});
})
})
}
function createUserPoolDomain(userPoolId) {
return getUserPoolDomainPrefix().then((userPoolDomain) => {
let params = {
Domain: userPoolDomain,
UserPoolId: userPoolId
};
return new Promise((resolve, reject) => {
userPools.createUserPoolDomain(params, function (err) {
if (err) {
reject(err);
return;
}
logger.info('Created Cognito User Pool Domain', params.Domain);
resolve('Created user pool successfully');
});
});
});
}
function getUserPoolDomainPrefix() {
return getUserPoolId().then((userPoolId) => {
// Convert user pool ID string suffix to lower case letters, numbers, and hypens only (replacing underscore character)
return config.getName(userPoolId).toLowerCase().replace('_','-');
});
}
function getUserPoolDomainName() {
return getUserPoolDomainPrefix().then((userPoolDomainPrefix) => {
return userPoolDomainPrefix + '.auth.' + config.AWS_REGION + '.amazoncognito.com';
});
}
function deleteUserPoolDomain(userPoolId) {
return getUserPoolDomainPrefix().then((userPoolDomain) => {
let params = {
Domain: userPoolDomain,
UserPoolId: userPoolId
};
return new Promise((resolve, reject) => {
userPools.deleteUserPoolDomain(params, function (err) {
if (err) {
reject(err);
return;
}
resolve('Deleted Cognito User Pool Domain');
});
});
});
}
function deleteUserPool() {
return getUserPoolId().then((userPoolId) => {
let params = {
UserPoolId: userPoolId
};
return deleteUserPoolDomain(userPoolId).then(() => {
userPools.deleteUserPool(params, function (err, data) {
if (err) {
throw (new Error(err));
}
return (data);
});
});
});
}
function createCognitoPools() {
return safeCreateUserPool().then(safeCreateIdentityPool);
}
function deleteCognitoPools() {
return deleteIdentityPool().then(deleteUserPool);
}
module.exports = {
adminAssignUserToGroup,
adminCreateUser,
adminCreateGroup,
createCognitoPools,
deleteCognitoPools,
getIdentityPoolId,
getIdentityPoolUserId,
getUserPoolId,
getUserPoolClientId,
getUserPoolDomainName,
getUserPoolDomainPrefix,
userPoolAppClientName
};