-
Notifications
You must be signed in to change notification settings - Fork 816
/
auth-questions.js
754 lines (689 loc) · 26.2 KB
/
auth-questions.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
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
const inquirer = require('inquirer');
const chalk = require('chalk');
const _ = require('lodash');
const { uniq, pullAll } = require('lodash');
const path = require('path');
const { Sort } = require('enquirer');
// const { parseTriggerSelections } = require('../utils/trigger-flow-auth-helper');
const { extractApplePrivateKey } = require('../utils/extract-apple-private-key');
const { authProviders, attributeProviderMap, capabilities } = require('../assets/string-maps');
const category = 'auth';
async function serviceWalkthrough(context, defaultValuesFilename, stringMapsFilename, serviceMetadata, coreAnswers = {}) {
const { inputs } = serviceMetadata;
const { amplify } = context;
const { parseInputs } = require(`${__dirname}/../question-factories/core-questions.js`);
const projectType = amplify.getProjectConfig().frontend;
const defaultValuesSrc = `${__dirname}/../assets/${defaultValuesFilename}`;
const { getAllDefaults } = require(defaultValuesSrc);
let userPoolGroupList = context.amplify.getUserPoolGroupList(context);
let adminQueryGroup;
handleUpdates(context, coreAnswers);
// QUESTION LOOP
let j = 0;
while (j < inputs.length) {
const questionObj = inputs[j];
// CREATE QUESTION OBJECT
const q = await parseInputs(questionObj, amplify, defaultValuesFilename, stringMapsFilename, coreAnswers, context);
// ASK QUESTION
const answer = await inquirer.prompt(q);
if ('signinwithapplePrivateKeyUserPool' in answer) {
answer.signinwithapplePrivateKeyUserPool = extractApplePrivateKey(answer.signinwithapplePrivateKeyUserPool);
}
if (answer.userPoolGroups === true) {
userPoolGroupList = await updateUserPoolGroups(context);
}
if (answer.adminQueries === true) {
adminQueryGroup = await updateAdminQuery(context, userPoolGroupList);
}
if (answer.triggers && answer.triggers !== '{}') {
const tempTriggers = context.updatingAuth && context.updatingAuth.triggers ? JSON.parse(context.updatingAuth.triggers) : {};
const selectionMetadata = capabilities;
/* eslint-disable no-loop-func */
selectionMetadata.forEach(s => {
Object.keys(s.triggers).forEach(t => {
if (!tempTriggers[t] && answer.triggers.includes(s.value)) {
tempTriggers[t] = s.triggers[t];
} else if (tempTriggers[t] && answer.triggers.includes(s.value)) {
tempTriggers[t] = uniq(tempTriggers[t].concat(s.triggers[t]));
} else if (tempTriggers[t] && !answer.triggers.includes(s.value)) {
const tempForDiff = Object.assign([], tempTriggers[t]);
const remainder = pullAll(tempForDiff, s.triggers[t]);
if (remainder && remainder.length > 0) {
tempTriggers[t] = remainder;
} else {
delete tempTriggers[t];
}
}
});
});
answer.triggers = tempTriggers;
}
// LEARN MORE BLOCK
if (new RegExp(/learn/i).test(answer[questionObj.key]) && questionObj.learnMore) {
const helpText = `\n${questionObj.learnMore.replace(new RegExp('[\\n]', 'g'), '\n\n')}\n\n`;
questionObj.prefix = chalk.green(helpText);
// ITERATOR BLOCK
} else if (
/*
if the input has an 'iterator' value, we generate a loop which uses the iterator value as a
key to find the array of values it should splice into.
*/
questionObj.iterator &&
answer[questionObj.key] &&
answer[questionObj.key].length > 0
) {
const replacementArray = context.updatingAuth[questionObj.iterator];
for (let t = 0; t < answer[questionObj.key].length; t += 1) {
questionObj.validation = questionObj.iteratorValidation;
const newValue = await inquirer.prompt({
name: 'updated',
message: `Update ${answer[questionObj.key][t]}`,
validate: amplify.inputValidation(questionObj),
});
replacementArray.splice(replacementArray.indexOf(answer[questionObj.key][t]), 1, newValue.updated);
}
j += 1;
// ADD-ANOTHER BLOCK
} else if (questionObj.addAnotherLoop && Object.keys(answer).length > 0) {
/*
if the input has an 'addAnotherLoop' value, we first make sure that the answer
will be recorded as an array index, and if it is already an array we push the new value.
We then ask the user if they want to add another url. If not, we increment our counter (j)
so that the next question is appears in the prompt. If the counter isn't incremented,
the same question is reapated.
*/
if (!coreAnswers[questionObj.key]) {
answer[questionObj.key] = [answer[questionObj.key]];
coreAnswers = { ...coreAnswers, ...answer };
} else {
coreAnswers[questionObj.key].push(answer[questionObj.key]);
}
const addAnother = await inquirer.prompt({
name: 'repeater',
type: 'confirm',
default: false,
message: `Do you want to add another ${questionObj.addAnotherLoop}`,
});
if (!addAnother.repeater) {
j += 1;
}
} else if (questionObj.key === 'updateFlow') {
/*
if the user selects a default or fully manual config option during an update,
we set the useDefault value so that the appropriate questions are displayed
*/
if (answer.updateFlow === 'updateUserPoolGroups') {
userPoolGroupList = await updateUserPoolGroups(context);
} else if (answer.updateFlow === 'updateAdminQueries') {
adminQueryGroup = await updateAdminQuery(context, userPoolGroupList);
} else if (['manual', 'defaultSocial', 'default'].includes(answer.updateFlow)) {
answer.useDefault = answer.updateFlow;
if (answer.useDefault === 'defaultSocial') {
coreAnswers.hostedUI = true;
}
if (answer.useDefault === 'default') {
coreAnswers.hostedUI = false;
}
delete answer.updateFlow;
}
coreAnswers = { ...coreAnswers, ...answer };
j += 1;
} else if (!context.updatingAuth && answer.useDefault && ['default', 'defaultSocial'].includes(answer.useDefault)) {
// if the user selects defaultSocial, we set hostedUI to true to avoid reasking this question
coreAnswers = { ...coreAnswers, ...answer };
coreAnswers.authSelections = 'identityPoolAndUserPool';
if (coreAnswers.useDefault === 'defaultSocial') {
coreAnswers.hostedUI = true;
}
j += 1;
} else {
coreAnswers = { ...coreAnswers, ...answer };
j += 1;
}
}
// POST-QUESTION LOOP PARSING
// if user selects user pool only, ensure that we clean id pool options
if (coreAnswers.authSelections === 'userPoolOnly' && context.updatingAuth) {
context.print.warning(
`Warning! Your existing IdentityPool: ${context.updatingAuth.identityPoolName} will be deleted upon the next “amplify push”!`,
);
delete context.updatingAuth.identityPoolName;
delete context.updatingAuth.allowUnauthenticatedIdentities;
delete context.updatingAuth.thirdPartyAuth;
delete context.updatingAuth.authProviders;
delete context.updatingAuth.facebookAppId;
delete context.updatingAuth.googleClientId;
delete context.updatingAuth.googleIos;
delete context.updatingAuth.googleAndroid;
delete context.updatingAuth.amazonAppId;
delete context.updatingAuth.appleAppId;
}
// formatting data for identity pool providers
if (coreAnswers.thirdPartyAuth) {
identityPoolProviders(coreAnswers, projectType);
}
const isPullOrEnvCommand = context.input.command === 'pull' || context.input.command === 'env';
if (coreAnswers.authSelections !== 'identityPoolOnly' && context.input.command != 'init' && !isPullOrEnvCommand) {
if (coreAnswers.useDefault === 'manual') {
coreAnswers.triggers = await lambdaFlow(context, coreAnswers.triggers);
}
}
// formatting data for user pool providers / hosted UI
if (coreAnswers.authProvidersUserPool) {
/* eslint-disable */
coreAnswers = Object.assign(coreAnswers, userPoolProviders(coreAnswers.authProvidersUserPool, coreAnswers, context.updatingAuth));
/* eslint-enable */
}
// formatting oAuthMetaData
structureOAuthMetadata(coreAnswers, context, getAllDefaults, amplify);
if (coreAnswers.usernameAttributes && !Array.isArray(coreAnswers.usernameAttributes)) {
if (coreAnswers.usernameAttributes === 'username') {
delete coreAnswers.usernameAttributes;
} else {
coreAnswers.usernameAttributes = coreAnswers.usernameAttributes.split();
}
}
return {
...coreAnswers,
userPoolGroupList,
adminQueryGroup,
serviceName: 'Cognito',
};
}
async function updateUserPoolGroups(context) {
let userPoolGroupList = [];
let existingGroups;
const userGroupParamsPath = path.join(
context.amplify.pathManager.getBackendDirPath(),
'auth',
'userPoolGroups',
'user-pool-group-precedence.json',
);
try {
existingGroups = context.amplify.readJsonFile(userGroupParamsPath);
userPoolGroupList = existingGroups.map(e => e.groupName);
} catch (e) {
existingGroups = null;
}
if (existingGroups) {
// eslint-disable-next-line
const deletionChoices = existingGroups.map(e => {
return { name: e.groupName, value: e.groupName };
});
const deletionAnswer = await inquirer.prompt([
{
name: 'groups2BeDeleted',
type: 'checkbox',
message: 'Select any user pool groups you want to delete:',
choices: deletionChoices,
},
]);
userPoolGroupList = userPoolGroupList.filter(i => !deletionAnswer.groups2BeDeleted.includes(i));
}
let answer;
/* Must be sure to ask this question in the event that it is the
first time in the user pool group flow, or it is an update but
the user has deleted all existing groups. If they want to delete
all groups they should just delete the resource */
if (userPoolGroupList.length < 1) {
answer = await inquirer.prompt([
{
name: 'userPoolGroupName',
type: 'input',
message: 'Provide a name for your user pool group:',
validate: context.amplify.inputValidation({
validation: {
operator: 'regex',
value: '^[a-zA-Z0-9]+$',
onErrorMsg: 'Resource name should be alphanumeric',
},
required: true,
}),
},
]);
userPoolGroupList.push(answer.userPoolGroupName);
}
let addAnother = await inquirer.prompt({
name: 'repeater',
type: 'confirm',
default: false,
message: 'Do you want to add another User Pool Group',
});
while (addAnother.repeater === true) {
answer = await inquirer.prompt([
{
name: 'userPoolGroupName',
type: 'input',
message: 'Provide a name for your user pool group:',
validate: context.amplify.inputValidation({
validation: {
operator: 'regex',
value: '^[a-zA-Z0-9]+$',
onErrorMsg: 'Resource name should be alphanumeric',
},
required: true,
}),
},
]);
userPoolGroupList.push(answer.userPoolGroupName);
addAnother = await inquirer.prompt({
name: 'repeater',
type: 'confirm',
default: false,
message: 'Do you want to add another User Pool Group',
});
}
// Get distinct list
const distinctSet = new Set(userPoolGroupList);
userPoolGroupList = Array.from(distinctSet);
// Sort the Array to get precedence
let sortedUserPoolGroupList = [];
if (userPoolGroupList && userPoolGroupList.length > 0) {
const sortPrompt = new Sort({
name: 'sortUserPools',
hint: `(Use ${chalk.green.bold('<shift>+<right/left>')} to change the order)`,
message: 'Sort the user pool groups in order of preference',
choices: userPoolGroupList,
shiftLeft(...args) {
return this.shiftUp(...args);
},
shiftRight(...args) {
return this.shiftDown(...args);
},
});
sortedUserPoolGroupList = await sortPrompt.run();
}
return sortedUserPoolGroupList;
}
async function updateAdminQuery(context, userPoolGroupList) {
let adminGroup;
// Clone user pool group list
const userPoolGroupListClone = userPoolGroupList.slice(0);
if (await context.amplify.confirmPrompt('Do you want to restrict access to the admin queries API to a specific Group')) {
userPoolGroupListClone.push('Enter a custom group');
const adminGroupAnswer = await inquirer.prompt([
{
name: 'adminGroup',
type: 'list',
message: 'Select the group to restrict access with:',
choices: userPoolGroupListClone,
},
]);
if (adminGroupAnswer.adminGroup === 'Enter a custom group') {
const temp = await inquirer.prompt([
{
name: 'userPoolGroupName',
type: 'input',
message: 'Provide a group name:',
validate: context.amplify.inputValidation({
validation: {
operator: 'regex',
value: '^[a-zA-Z0-9]+$',
onErrorMsg: 'Resource name should be alphanumeric',
},
required: true,
}),
},
]);
adminGroup = temp.userPoolGroupName;
} else {
({ adminGroup } = adminGroupAnswer);
}
}
return adminGroup;
}
/*
Create key/value pairs of third party auth providers,
where key = name accepted by updateIdentityPool API call and value = id entered by user
*/
function identityPoolProviders(coreAnswers, projectType) {
coreAnswers.selectedParties = {};
authProviders.forEach(e => {
// don't send google value in cf if native project, since we need to make an openid provider
if (projectType === 'javascript' || e.answerHashKey !== 'googleClientId') {
if (coreAnswers[e.answerHashKey]) {
coreAnswers.selectedParties[e.value] = coreAnswers[e.answerHashKey];
}
/*
certain third party providers require multiple values,
which Cognito requires to be a concatenated string -
so here we build the string using 'concatKeys' defined in the thirdPartyMap
*/
if (coreAnswers[e.answerHashKey] && e.concatKeys) {
e.concatKeys.forEach(i => {
coreAnswers.selectedParties[e.value] = coreAnswers.selectedParties[e.value].concat(';', coreAnswers[i]);
});
}
}
});
if (projectType !== 'javascript' && coreAnswers.authProviders.includes('accounts.google.com')) {
coreAnswers.audiences = [coreAnswers.googleClientId];
if (projectType === 'ios') {
coreAnswers.audiences.push(coreAnswers.googleIos);
} else if (projectType === 'android') {
coreAnswers.audiences.push(coreAnswers.googleAndroid);
}
}
coreAnswers.selectedParties = JSON.stringify(coreAnswers.selectedParties);
}
/*
Format hosted UI providers data per lambda spec
hostedUIProviderMeta is saved in parameters.json.
hostedUIproviderCreds is saved in deployment-secrets.
*/
function userPoolProviders(oAuthProviders, coreAnswers, prevAnswers) {
if (coreAnswers.useDefault === 'default') {
return null;
}
const answers = Object.assign(prevAnswers || {}, coreAnswers);
const attributesForMapping = answers.requiredAttributes
? JSON.parse(JSON.stringify(answers.requiredAttributes)).concat('username')
: ['email', 'username'];
const res = {};
if (answers.hostedUI) {
res.hostedUIProviderMeta = JSON.stringify(
oAuthProviders.map(el => {
const lowerCaseEl = el.toLowerCase();
const delimmiter = el === 'Facebook' ? ',' : ' ';
const scopes = [];
const maps = {};
attributesForMapping.forEach(a => {
const attributeKey = attributeProviderMap[a];
if (attributeKey && attributeKey[`${lowerCaseEl}`] && attributeKey[`${lowerCaseEl}`].scope) {
if (scopes.indexOf(attributeKey[`${lowerCaseEl}`].scope) === -1) {
scopes.push(attributeKey[`${lowerCaseEl}`].scope);
}
}
if (el === 'Google' && !scopes.includes('openid')) {
scopes.unshift('openid');
}
if (attributeKey && attributeKey[`${lowerCaseEl}`] && attributeKey[`${lowerCaseEl}`].attr) {
maps[a] = attributeKey[`${lowerCaseEl}`].attr;
}
});
return {
ProviderName: el,
authorize_scopes: scopes.join(delimmiter),
AttributeMapping: maps,
};
}),
);
res.hostedUIProviderCreds = JSON.stringify(
oAuthProviders.map(el => {
const lowerCaseEl = el.toLowerCase();
if (el === 'SignInWithApple') {
return {
ProviderName: el,
client_id: coreAnswers[`${lowerCaseEl}ClientIdUserPool`],
team_id: coreAnswers[`${lowerCaseEl}TeamIdUserPool`],
key_id: coreAnswers[`${lowerCaseEl}KeyIdUserPool`],
private_key: coreAnswers[`${lowerCaseEl}PrivateKeyUserPool`],
};
} else {
return {
ProviderName: el,
client_id: coreAnswers[`${lowerCaseEl}AppIdUserPool`],
client_secret: coreAnswers[`${lowerCaseEl}AppSecretUserPool`],
};
}
}),
);
}
return res;
}
/*
Format hosted UI oAuth data per lambda spec
*/
function structureOAuthMetadata(coreAnswers, context, defaults, amplify) {
if (coreAnswers.useDefault === 'default' && context.updatingAuth) {
delete context.updatingAuth.oAuthMetadata;
return null;
}
const answers = Object.assign({}, context.updatingAuth, coreAnswers);
let { AllowedOAuthFlows, AllowedOAuthScopes, CallbackURLs, LogoutURLs } = answers;
if (CallbackURLs && coreAnswers.newCallbackURLs) {
CallbackURLs = CallbackURLs.concat(coreAnswers.newCallbackURLs);
} else if (coreAnswers.newCallbackURLs) {
CallbackURLs = coreAnswers.newCallbackURLs;
}
if (LogoutURLs && coreAnswers.newLogoutURLs) {
LogoutURLs = LogoutURLs.concat(coreAnswers.newLogoutURLs);
} else if (coreAnswers.newLogoutURLs) {
LogoutURLs = coreAnswers.newLogoutURLs;
}
if (CallbackURLs && LogoutURLs) {
if (!answers.AllowedOAuthScopes) {
/* eslint-disable */
AllowedOAuthScopes = defaults(amplify.getProjectDetails(amplify)).AllowedOAuthScopes;
}
if (!answers.AllowedOAuthFlows) {
AllowedOAuthFlows = defaults(amplify.getProjectDetails(amplify)).AllowedOAuthFlows;
/* eslint-enable */
} else {
AllowedOAuthFlows = Array.isArray(AllowedOAuthFlows) ? AllowedOAuthFlows : [AllowedOAuthFlows];
}
}
if (AllowedOAuthFlows && AllowedOAuthScopes && CallbackURLs && LogoutURLs) {
coreAnswers.oAuthMetadata = JSON.stringify({
AllowedOAuthFlows,
AllowedOAuthScopes,
CallbackURLs,
LogoutURLs,
});
}
return coreAnswers;
}
/*
Deserialize oAuthData for CLI update flow
*/
function parseOAuthMetaData(previousAnswers) {
if (previousAnswers && previousAnswers.oAuthMetadata) {
previousAnswers = Object.assign(previousAnswers, JSON.parse(previousAnswers.oAuthMetadata));
delete previousAnswers.oAuthMetadata;
}
}
/*
Deserialize oAuthCredentials for CLI update flow
*/
function parseOAuthCreds(providers, metadata, envCreds) {
const providerKeys = {};
try {
const parsedMetaData = JSON.parse(metadata);
const parsedCreds = JSON.parse(envCreds);
providers.forEach(el => {
const lowerCaseEl = el.toLowerCase();
try {
const provider = parsedMetaData.find(i => i.ProviderName === el);
const creds = parsedCreds.find(i => i.ProviderName === el);
if (el === 'SignInWithApple') {
providerKeys[`${lowerCaseEl}ClientIdUserPool`] = creds.client_id;
providerKeys[`${lowerCaseEl}TeamIdUserPool`] = creds.team_id;
providerKeys[`${lowerCaseEl}KeyIdUserPool`] = creds.key_id;
providerKeys[`${lowerCaseEl}PrivateKeyUserPool`] = creds.private_key;
} else {
providerKeys[`${lowerCaseEl}AppIdUserPool`] = creds.client_id;
providerKeys[`${lowerCaseEl}AppSecretUserPool`] = creds.client_secret;
}
providerKeys[`${lowerCaseEl}AuthorizeScopes`] = provider.authorize_scopes.split(',');
} catch (e) {
return null;
}
});
} catch (e) {
return {};
}
return providerKeys;
}
/*
Handle updates
*/
function handleUpdates(context, coreAnswers) {
if (context.updatingAuth && context.updatingAuth.triggers) {
coreAnswers.triggers = {};
coreAnswers.triggers = context.updatingAuth.triggers;
}
if (context.updatingAuth && context.updatingAuth.oAuthMetadata) {
parseOAuthMetaData(context.updatingAuth);
}
if (context.updatingAuth && context.updatingAuth.authProvidersUserPool) {
const { resourceName, authProvidersUserPool, hostedUIProviderMeta } = context.updatingAuth;
const { hostedUIProviderCreds } = context.amplify.loadEnvResourceParameters(context, 'auth', resourceName);
/* eslint-disable */
const oAuthCreds = parseOAuthCreds(authProvidersUserPool, hostedUIProviderMeta, hostedUIProviderCreds);
/* eslint-enable */
context.updatingAuth = Object.assign(context.updatingAuth, oAuthCreds);
}
if (context.updatingAuth && context.updatingAuth.authSelections === 'identityPoolOnly') {
coreAnswers.authSelections = 'identityPoolAndUserPool';
}
}
/*
Adding lambda triggers
*/
async function lambdaFlow(context, answers) {
const triggers = await context.amplify.triggerFlow(context, 'cognito', 'auth', answers);
return triggers || answers;
}
function getIAMPolicies(context, resourceName, crudOptions) {
let policy = {};
const actions = [];
crudOptions.forEach(crudOption => {
switch (crudOption) {
case 'create':
actions.push(
'cognito-idp:ConfirmSignUp',
'cognito-idp:AdminCreateUser',
'cognito-idp:CreateUserImportJob',
'cognito-idp:AdminSetUserSettings',
'cognito-idp:AdminLinkProviderForUser',
'cognito-idp:CreateIdentityProvider',
'cognito-idp:AdminConfirmSignUp',
'cognito-idp:AdminDisableUser',
'cognito-idp:AdminRemoveUserFromGroup',
'cognito-idp:SetUserMFAPreference',
'cognito-idp:SetUICustomization',
'cognito-idp:SignUp',
'cognito-idp:VerifyUserAttribute',
'cognito-idp:SetRiskConfiguration',
'cognito-idp:StartUserImportJob',
'cognito-idp:AdminSetUserPassword',
'cognito-idp:AssociateSoftwareToken',
'cognito-idp:CreateResourceServer',
'cognito-idp:RespondToAuthChallenge',
'cognito-idp:CreateUserPoolClient',
'cognito-idp:AdminUserGlobalSignOut',
'cognito-idp:GlobalSignOut',
'cognito-idp:AddCustomAttributes',
'cognito-idp:CreateGroup',
'cognito-idp:CreateUserPool',
'cognito-idp:AdminForgetDevice',
'cognito-idp:AdminAddUserToGroup',
'cognito-idp:AdminRespondToAuthChallenge',
'cognito-idp:ForgetDevice',
'cognito-idp:CreateUserPoolDomain',
'cognito-idp:AdminEnableUser',
'cognito-idp:AdminUpdateDeviceStatus',
'cognito-idp:StopUserImportJob',
'cognito-idp:InitiateAuth',
'cognito-idp:AdminInitiateAuth',
'cognito-idp:AdminSetUserMFAPreference',
'cognito-idp:ConfirmForgotPassword',
'cognito-idp:SetUserSettings',
'cognito-idp:VerifySoftwareToken',
'cognito-idp:AdminDisableProviderForUser',
'cognito-idp:SetUserPoolMfaConfig',
'cognito-idp:ChangePassword',
'cognito-idp:ConfirmDevice',
'cognito-idp:AdminResetUserPassword',
'cognito-idp:ResendConfirmationCode',
);
break;
case 'update':
actions.push(
'cognito-idp:ForgotPassword',
'cognito-idp:UpdateAuthEventFeedback',
'cognito-idp:UpdateResourceServer',
'cognito-idp:UpdateUserPoolClient',
'cognito-idp:AdminUpdateUserAttributes',
'cognito-idp:UpdateUserAttributes',
'cognito-idp:UpdateUserPoolDomain',
'cognito-idp:UpdateIdentityProvider',
'cognito-idp:UpdateGroup',
'cognito-idp:AdminUpdateAuthEventFeedback',
'cognito-idp:UpdateDeviceStatus',
'cognito-idp:UpdateUserPool',
);
break;
case 'read':
actions.push(
'cognito-identity:Describe*',
'cognito-identity:Get*',
'cognito-identity:List*',
'cognito-idp:Describe*',
'cognito-idp:AdminGetDevice',
'cognito-idp:AdminGetUser',
'cognito-idp:AdminList*',
'cognito-idp:List*',
'cognito-sync:Describe*',
'cognito-sync:Get*',
'cognito-sync:List*',
'iam:ListOpenIdConnectProviders',
'iam:ListRoles',
'sns:ListPlatformApplications',
);
break;
case 'delete':
actions.push(
'cognito-idp:DeleteUserPoolDomain',
'cognito-idp:DeleteResourceServer',
'cognito-idp:DeleteGroup',
'cognito-idp:AdminDeleteUserAttributes',
'cognito-idp:DeleteUserPoolClient',
'cognito-idp:DeleteUserAttributes',
'cognito-idp:DeleteUserPool',
'cognito-idp:AdminDeleteUser',
'cognito-idp:DeleteIdentityProvider',
'cognito-idp:DeleteUser',
);
break;
default:
console.log(`${crudOption} not supported`);
}
});
let userPoolReference;
const { amplifyMeta } = context.amplify.getProjectDetails();
const authResource = _.get(amplifyMeta, [category, resourceName], undefined);
if (!authResource) {
throw new Error(`Cannot get resource: ${resourceName} from '${category}' category.`);
}
if (authResource.serviceType === 'imported') {
const userPoolId = _.get(authResource, ['output', 'UserPoolId'], undefined);
if (!userPoolId) {
throw new Error(`Cannot read the UserPoolId attribute value from the output section of resource: '${resourceName}'.`);
}
userPoolReference = userPoolId;
} else {
userPoolReference = {
Ref: `${category}${resourceName}UserPoolId`,
};
}
policy = {
Effect: 'Allow',
Action: actions,
Resource: [
{
'Fn::Join': ['', ['arn:aws:cognito-idp:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':userpool/', userPoolReference]],
},
],
};
const attributes = ['UserPoolId'];
return { policy, attributes };
}
module.exports = {
serviceWalkthrough,
userPoolProviders,
parseOAuthCreds,
structureOAuthMetadata,
getIAMPolicies,
identityPoolProviders,
};