-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
314 lines (273 loc) · 7.94 KB
/
index.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
const _ = require('lodash');
const helperMethods = require('./helperMethods');
const Name = 'CognitoAddCustomAttributesPlugin';
const loadCustom = helperMethods.loadCustom;
const Params = helperMethods.Params;
const describeStack = helperMethods.describeStack;
class CognitoAddCustomAttributesPluginError extends Error {
constructor(error, innerMessage) {
super(error.message);
this.name = 'CognitoAddCustomAttributesPluginError';
this.innerMessage = innerMessage;
Error.captureStackTrace(error, CognitoAddCustomAttributesPluginError);
}
}
const findOutputId = (custom, stack, outputKey) => {
if (stack) {
const output = _.find(
stack.Outputs,
(output) => output.OutputKey === custom[outputKey]
);
if (output) {
const outputId = _.get(output, 'OutputValue');
return outputId;
} else {
throw new Error(`Could not find ${outputKey} in Outputs for stack.`);
}
}
};
const describeCognitoUserPool = async (AWS, userPoolId) => {
try {
const describeParams = {
UserPoolId: userPoolId
};
const response = await AWS.request(
'CognitoIdentityServiceProvider',
'describeUserPool',
describeParams
);
return response.UserPool;
} catch (error) {
throw new CognitoAddCustomAttributesPluginError(
error,
'Error occurred when fetching UserPool'
);
}
};
const describeCognitoUserPoolClient = async (
AWS,
userPoolId,
userPoolClientId
) => {
try {
const describeParams = {
ClientId: userPoolClientId,
UserPoolId: userPoolId
};
const response = await AWS.request(
'CognitoIdentityServiceProvider',
'describeUserPoolClient',
describeParams
);
return response.UserPoolClient;
} catch (error) {
throw new CognitoAddCustomAttributesPluginError(
error,
'Error occurred when fetching UserPoolClient'
);
}
};
const transformAttributeName = (name) => {
let customName = name;
if (!_.startsWith(customName, 'custom:')) {
customName = `custom:${customName}`;
}
return customName;
};
const getMissingAttributes = (newAttributes, existingAttributeNames) => {
return _.filter(newAttributes, (newAttribute) => {
let customName = transformAttributeName(newAttribute.Name);
const exists = _.some(
existingAttributeNames,
(existingName) => existingName == customName
);
return !exists;
});
};
const addNewCustomAttributesToUserPool = async (
AWS,
log,
userPoolId,
newAttributes
) => {
if (!_.isEmpty(newAttributes)) {
try {
const addCustomAttributesParams = {
UserPoolId: userPoolId,
CustomAttributes: newAttributes
};
log(
`Adding ${newAttributes.length} attribute(s) to pool: ${_.join(
_.map(newAttributes, (x) => x.Name)
)}`
);
await AWS.request(
'CognitoIdentityServiceProvider',
'addCustomAttributes',
addCustomAttributesParams
);
log('Successfully added attributes to pool');
} catch (error) {
throw new CognitoAddCustomAttributesPluginError(
error,
'Error occurred when adding attributes to pool'
);
}
} else {
return log('Supplied attributes already exist in pool');
}
};
const updateUserPoolClient = async (
AWS,
log,
userPoolClient,
readAttributes,
writeAttributes
) => {
if (readAttributes.length + writeAttributes.length > 0) {
const readAttributeNames = _.map(readAttributes, (x) =>
transformAttributeName(x.Name)
);
const writeAttributeNames = _.map(writeAttributes, (x) =>
transformAttributeName(x.Name)
);
try {
let sanitisedUserPoolClient = _.omit(userPoolClient, ['ClientSecret', 'CreationDate', 'LastModifiedDate']);
let params = Object.assign({}, sanitisedUserPoolClient, {
ReadAttributes: _.concat(
userPoolClient.ReadAttributes,
readAttributeNames
),
WriteAttributes: _.concat(
userPoolClient.WriteAttributes,
writeAttributeNames
)
})
if (readAttributeNames.length > 0) {
log(
`Enabling client to read from ${
readAttributeNames.length
} new attribute(s): ${_.join(readAttributeNames)}`
);
}
if (writeAttributeNames.length > 0) {
log(
`Enabling client to write to ${
writeAttributeNames.length
} new attribute(s): ${_.join(writeAttributeNames)}`
);
}
await AWS.request(
'CognitoIdentityServiceProvider',
'updateUserPoolClient',
params
);
log('Successfully updated client');
} catch (error) {
throw new CognitoAddCustomAttributesPluginError(
error,
'Error occurred when updating client'
);
}
} else {
return log('No update required to UserPoolClient');
}
};
class CognitoAddCustomAttributesPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.provider = serverless.getProvider('aws');
this.hooks = {
'after:deploy:deploy': this.postDeploy.bind(this)
};
this.log = this.log.bind(this);
this.run = this.run.bind(this);
}
async postDeploy() {
this.custom = loadCustom(this.log, this.serverless.service.custom);
await this.run();
}
async run() {
const { provider: AWS, custom, log } = this;
try {
log('Start');
const stack = await describeStack(AWS);
if (Array.isArray(custom)) {
await Promise.all(
custom.map((mappingItem) =>
(async () => {
// skip empty mapping items
if (_.isEmpty(mappingItem)) {
return;
}
// if we run more than one at a time, there is a chance for a race condition on creating
// the customAttribute on the userPool the first time
await this.processCognitoCustomAttributeMapping(
stack,
mappingItem
);
})()
)
);
} else {
await this.processCognitoCustomAttributeMapping(stack, custom);
}
log('End');
} catch (error) {
log(`run Error [Message: ${error.message}]`);
if (error.innerMessage) log(`${error.innerMessage}. ${error}`);
throw error;
}
}
async processCognitoCustomAttributeMapping(stack, mappingItem) {
const { log, provider: AWS } = this;
const userPoolId = findOutputId(
mappingItem,
stack,
Params.CognitoUserPoolIdOutputKey
);
log(`Found userPoolId: ${userPoolId}`);
const userPool = await describeCognitoUserPool(AWS, userPoolId);
const newAttributes = getMissingAttributes(
mappingItem.CustomAttributes,
_.map(userPool.SchemaAttributes, 'Name')
);
await addNewCustomAttributesToUserPool(AWS, log, userPoolId, newAttributes);
if ( typeof _.get(mappingItem, Params.CognitoUserPoolClientIdOutputKey) !== 'undefined' ) {
const userPoolClientId = await findOutputId(
mappingItem,
stack,
Params.CognitoUserPoolClientIdOutputKey
);
log(`Found userPoolClientId: ${userPoolClientId}`);
const userPoolClient = await describeCognitoUserPoolClient(
AWS,
userPoolId,
userPoolClientId
);
const newReadAttributes = getMissingAttributes(
mappingItem.CustomAttributes,
userPoolClient.ReadAttributes
);
const newWriteAttributes = getMissingAttributes(
mappingItem.CustomAttributes,
userPoolClient.WriteAttributes
);
await updateUserPoolClient(
AWS,
log,
userPoolClient,
newReadAttributes,
newWriteAttributes
);
}
else {
log('No param for UserPoolClient found. Will not update any UserPoolClient permissions!');
}
}
log(message) {
this.serverless.cli.log(`${Name}: ${message}`);
}
}
module.exports = CognitoAddCustomAttributesPlugin;