forked from auth0-extensions/auth0-account-link-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodifyRule.js
48 lines (37 loc) · 1.33 KB
/
modifyRule.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
const generateTemplate = require('./rules/link');
const RULE_STAGE = 'login_success';
const RULE_NAME = 'auth0-account-link-extension';
const findIn = rules => rules.find(rule => rule.name === RULE_NAME);
// Allowing partial application to make usage with promises nicer
const persistRule = (api, generatedRule) => (rules = []) => {
const existingRule = rules.find(rule => rule.name === RULE_NAME);
if (existingRule) {
return api.rules.update({ id: existingRule.id }, generatedRule);
}
return api.rules.create({ stage: RULE_STAGE, ...generatedRule });
};
const persistConfigRule = (api, config) => (configs = []) =>
Promise.all(
Object.keys(config)
.filter(key => !configs.some(c => c.key === key))
.map(key => api.rulesConfigs.set({ key }, { value: config[key] }))
);
const destroyRule = api => (rules = []) => {
const existingRule = findIn(rules);
if (existingRule) {
api.rules.delete({ id: existingRule.id });
}
};
const install = (api, config) => {
const rule = {
name: RULE_NAME,
script: generateTemplate(config),
enabled: true
};
return Promise.all([
api.rules.getAll().then(persistRule(api, rule)),
api.rulesConfigs.getAll().then(persistConfigRule(api, config))
]);
};
const uninstall = api => api.getAll().then(destroyRule(api));
module.exports = { install, uninstall };