-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth0_setup.js
398 lines (337 loc) · 11.3 KB
/
auth0_setup.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
const fs = require("fs");
const util = require("util");
const _ = require("lodash");
const path = require("path");
const ManagementClient = require("auth0").ManagementClient;
const PromptsManager = require("auth0/src/management/PromptsManager.js");
const prompt = require("prompt-sync")();
let management;
function setup() {
if (process.argv.length <= 2) {
console.log("Missing required arguments: [config file]");
process.exit(-1);
}
const [_nodePath, _scriptPath, configFile] = process.argv;
const clientSecret = prompt(
"Enter client secret for 'Auth0 Management' access: ",
{ echo: "*" }
);
const config = require(path.resolve(configFile));
management = new ManagementClient({
domain: config.domain,
clientId: config.clientId,
clientSecret: clientSecret,
});
const prompts = new PromptsManager({
baseUrl: util.format("https://%s/api/v2", config.domain),
headers: {
"User-agent": "node.js/" + process.version.replace("v", ""),
"Content-Type": "application/json",
},
tokenProvider: management.tokenProvider,
});
const componentDefinitions = getComponentDefinitions(config);
return {
prompts: prompts,
config: config,
componentDefinitions: componentDefinitions,
};
}
async function main() {
const { prompts, config, componentDefinitions } = setup();
await management.updateTenantSettings(componentDefinitions.tenantSettings);
logMessage("Success updating tenant settings");
await prompts.updateSettings({}, componentDefinitions.universalLogin);
logMessage("Success updating universal login");
const oldApis = await management.getResourceServers();
const nonSystemOldApis = oldApis.filter((api) => !api.is_system);
const apiParams = {
type: "API",
idFieldName: "id",
fieldToMatchOn: "name",
createFn: management.createResourceServer,
updateFn: updateResourceServer,
};
await updateComponents(
nonSystemOldApis,
componentDefinitions.apis,
apiParams
);
const oldClients = await management.getClients();
const clientParams = {
type: "Client",
idFieldName: "client_id",
fieldToMatchOn: "name",
createFn: management.createClient,
updateFn: management.updateClient,
};
await updateComponents(
oldClients,
componentDefinitions.clients,
clientParams
);
const oldGrants = await management.getClientGrants();
const clients = await management.getClients();
componentDefinitions.clientGrants.forEach((grant) => {
grant.client_id = findMatchingClientId(grant.name, clients);
delete grant.name;
});
const grantParams = {
type: "Client Grant",
idFieldName: "id",
fieldToMatchOn: "client_id",
createFn: management.createClientGrant,
updateFn: management.updateClientGrant
}
await updateComponents(oldGrants, componentDefinitions.clientGrants, grantParams);
const oldConnections = await management.getConnections();
const newConnections = await fillInConnectionConfigurations(
componentDefinitions.connections,
config
);
const connectionParams = {
type: "Connection",
idFieldName: "id",
fieldToMatchOn: "name",
createFn: management.createConnection,
updateFn: management.updateConnection,
};
await updateComponents(oldConnections, newConnections, connectionParams);
const oldRules = await management.getRules();
const ruleParams = {
type: "Rule",
idFieldName: "id",
fieldToMatchOn: "name",
createFn: management.createRule,
updateFn: management.updateRule,
};
await updateComponents(oldRules, componentDefinitions.rules, ruleParams);
const oldRoles = await management.getRoles();
const roleParams = {
type: "Role",
idFieldName: "id",
fieldToMatchOn: "name",
createFn: management.createRole,
updateFn: management.updateRole,
};
await updateComponents(oldRoles, componentDefinitions.roles, roleParams);
const oldFactors = await management.guardian.getFactors();
const factorParams = {
type: "Factor",
idFieldName: "name",
fieldToMatchOn: "name",
createFn: management.guardian.updateFactor,
updateFn: management.guardian.updateFactor,
};
await updateComponents(
oldFactors,
componentDefinitions.guardian.factors,
factorParams
);
const oldActions = await management.actions.getAll();
const actionParams = {
type: "Action",
idFieldName: "id",
fieldToMatchOn: "name",
};
await updateActions(
oldActions.actions,
componentDefinitions.actions,
actionParams
);
await updatePostLoginBindings(componentDefinitions.postLoginFlow);
}
async function fillInConnectionConfigurations(connections, config) {
const clientEnabledInConfig = ({ name }) => {
return config.enabledClients.includes(name);
};
const extractClientId = ({ client_id }) => {
return client_id;
};
const updateEnabledClients = (clients, connection) => {
connection["enabled_clients"] = clients;
return connection;
};
const connectionsUserWantsToCreate = connections.filter(
userWantsToCreateConnection
);
const connectionsWithSecrets = connectionsUserWantsToCreate
.filter(connectionHasSecrets)
.map(promptForConnectionSecrets);
const connectionsWithoutSecrets = connectionsUserWantsToCreate.filter(
connectionWithoutSecrets
);
const currentClients = await management.getClients();
const enabledClientIds = currentClients
.filter(clientEnabledInConfig)
.map(extractClientId);
const connectionsToCreate = connectionsWithSecrets.concat(
connectionsWithoutSecrets
);
return connectionsToCreate.map(
_.partial(updateEnabledClients, enabledClientIds)
);
}
function getComponentDefinitions(config) {
const customLoginPage = getCustomLoginPage();
const rawComponents = fs.readFileSync("components.json", "utf8");
const templatedComponents = _.template(rawComponents)(
Object.assign({}, config, { customLoginPage: customLoginPage })
);
return JSON.parse(templatedComponents);
}
function getCustomLoginPage() {
return fs
.readFileSync("custom-login-page.html", "utf8")
.trim()
.replace(new RegExp('"', "g"), "'")
.replace(new RegExp("\n", "g"), "\\n");
}
function updateResourceServer(params, resourceApi) {
updatedResourceApi = Object.assign({}, resourceApi);
delete updatedResourceApi.identifier;
return management.updateResourceServer(params, updatedResourceApi);
}
async function updateComponents(
oldComponents,
newComponents,
{ type, idFieldName, fieldToMatchOn, createFn, updateFn }
) {
const components = createListOfChanges(oldComponents, newComponents, fieldToMatchOn);
const componentUpdatePromises = components.map(
async ({ newComponent, oldComponent }) => {
if (newComponent && oldComponent) {
const params = createIdParam(oldComponent, idFieldName);
const name = newComponent.name;
delete newComponent.name;
delete newComponent.strategy;
delete newComponent.client_id;
delete newComponent.audience;
await updateFn(params, newComponent);
logMessage(`Success updating ${name} ${type}`);
} else if (newComponent) {
await createFn(newComponent);
logMessage(`Success creating ${newComponent.name} ${type}`);
} else {
logMessage(
`Not touching uninvolved component ${oldComponent.name} ${type}`
);
}
}
);
return Promise.all(componentUpdatePromises);
}
async function updateActions(oldActions, newActions, { type, idFieldName, fieldToMatchOn }) {
const actions = createListOfChanges(oldActions, newActions, fieldToMatchOn);
const componentUpdatePromises = actions.map(
async ({ newComponent, oldComponent }) => {
if (newComponent && oldComponent) {
await updateAction(oldComponent, idFieldName, newComponent, type);
} else if (newComponent) {
await createAction(newComponent, idFieldName, type);
} else {
logMessage(
`Not touching uninvolved component ${oldComponent.name} ${type}`
);
}
}
);
return Promise.all(componentUpdatePromises);
}
async function updatePostLoginBindings(postLoginFlow) {
const triggerParams = { trigger_id: "post-login" };
await management.actions.updateTriggerBindings(triggerParams, {
bindings: postLoginFlow,
});
}
async function createAction(newAction, idFieldName, type) {
newAction.code = fs.readFileSync(newAction.codePath).toString();
delete newAction.codePath;
const createdAction = await management.actions.create(newAction);
await management.actions.deploy(createIdParam(createdAction, idFieldName));
logMessage(`Success creating ${newAction.name} ${type}`);
}
async function updateAction(oldAction, idFieldName, newAction, type) {
const params = createIdParam(oldAction, idFieldName);
const name = newAction.name;
newAction.code = fs.readFileSync(newAction.codePath).toString();
delete newAction.codePath;
await management.actions.update(params, newAction);
await management.actions.deploy(params);
logMessage(`Success updating ${name} ${type}`);
}
function createListOfChanges(oldComponents, newComponents, matchingField) {
const components = [];
newComponents.forEach((newComponent) => {
const oldComponent =
oldComponents.find((component) => component[matchingField] === newComponent[matchingField]) ||
null;
components.push({
newComponent: newComponent,
oldComponent: oldComponent,
});
});
oldComponents.forEach((component) => {
const doesNotExist =
components.find(
({ oldComponent }) =>
oldComponent !== null && component[matchingField] === oldComponent[matchingField]
) === undefined;
if (doesNotExist) {
components.push({
newComponent: null,
oldComponent: component,
});
}
});
return components;
}
function createIdParam(component, idFieldName) {
const params = {};
params[idFieldName] = component[idFieldName];
return params;
}
function findMatchingClientId(name, clients) {
return clients.filter((client) => client.name === name)?.[0]?.client_id;
}
function userWantsToCreateConnection({ name }) {
const createConnection = prompt(
`Do you want to create or update connection for ${name}? (y/n) [default: n]: `,
"n"
);
return createConnection === "y";
}
function connectionHasSecrets({ name }) {
return ["google-oauth2"].indexOf(name) >= 0;
}
function connectionWithoutSecrets(connection) {
return !connectionHasSecrets(connection);
}
function promptForConnectionSecrets(connectionConfiguration) {
const { name } = connectionConfiguration;
connectionConfiguration["options"]["client_id"] = prompt(
`Enter client id for ${name}: `,
{ echo: "*" }
);
if (!connectionConfiguration.options.client_id)
throw "Error: client_id cannot be empty!";
connectionConfiguration["options"]["client_secret"] = prompt(
`Enter client secret for ${name}: `,
{ echo: "*" }
);
if (!connectionConfiguration.options.client_secret)
throw "Error: client_secret cannot be empty!";
return connectionConfiguration;
}
function logMessage(message) {
console.log(` * ${message}`);
}
async function logConnections() {
const { prompts, config, componentDefinitions } = setup();
management.getConnections().then((a) => {
console.log(a);
console.log(a[0].options);
console.log(a[0].options.mfa);
});
}
main();