-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
97 lines (88 loc) · 3.25 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
/* eslint-disable no-console */
const path = require("path");
const { ManagementClient } = require("auth0");
require("dotenv").config({
path: path.resolve(process.cwd(), `.env.${process.env.CONTEXT}`),
});
module.exports = {
onPreBuild: ({ utils }) => {
console.log(`🔑 Auth0 Plugin startup`);
const tab = " ";
const requiredEnvVariables = [
"AUTH0_DOMAIN",
"AUTH0_CLIENT_ID",
"AUTH0_MANAGEMENT_CLIENT_ID",
"AUTH0_MANAGEMENT_CLIENT_SECRET",
];
const missingEnvVariables = requiredEnvVariables.filter(
(envVar) => typeof process.env[envVar] === "undefined"
);
if (missingEnvVariables.length > 0) {
utils.build.failPlugin(
`${tab} ☠️ Missing environment variables: ${missingEnvVariables.join(
", "
)}`
);
}
return new Promise((resolve) => {
const deployUrl = process.env.DEPLOY_URL;
console.log(`${tab} 🧭 Deploy Preview URL will be:`, deployUrl);
const deployPrimeUrl = process.env.DEPLOY_PRIME_URL;
if (deployPrimeUrl) {
console.log(
`${tab} 🧭 Deploy Preview Prime URL will be:`,
deployPrimeUrl
);
}
const management = new ManagementClient({
domain: process.env.AUTH0_DOMAIN,
clientId: process.env.AUTH0_MANAGEMENT_CLIENT_ID,
clientSecret: process.env.AUTH0_MANAGEMENT_CLIENT_SECRET,
scope: "read:clients update:clients",
});
management.clients
.get({ client_id: process.env.AUTH0_CLIENT_ID })
.then((client) => {
console.log(`${tab} 🗝 Retrieved Auth0 client: ${client.name}`);
// Handles empty value https://github.com/romainbessugesmeusy/netlify-plugin-auth0-patch-urls/issues/9
const clientWebOrigins = client.web_origins || [];
// If a PRIME URL is given by Netlify, we want to add it.
// Will be made optional in future release
const urlOrigins = deployPrimeUrl
? [deployUrl, deployPrimeUrl]
: [deployUrl];
// Urls that need to be added are the ones that are not already in the Client WebOrigins array.
const urlsToAdd = urlOrigins.filter(
(url) => !clientWebOrigins.includes(url)
);
if (urlsToAdd.length > 0) {
console.log(
`${tab} Adding URLs to the Auth0 Application Web Origins:`
);
urlsToAdd.forEach((url) => console.log(`${tab} • ${url}`));
management.clients.update(
{ client_id: process.env.AUTH0_CLIENT_ID },
{ web_origins: clientWebOrigins.concat(urlsToAdd) },
(updateError) => {
if (updateError) {
utils.build.failPlugin(
`${tab} ☠️ Something wrong happened while trying to patch Auth0 Application`
);
} else {
console.log(
`${tab} 🍾 Successfully patched Auth0 Application.`
);
}
resolve();
}
);
} else {
console.log(
`${tab} 👍 URL has already been added to Auth0 Application`
);
resolve();
}
});
});
},
};