Created
April 26, 2018 09:36
-
-
Save mathieuancelin/6b760ec4bb98b3d9fc6a1d76b107c575 to your computer and use it in GitHub Desktop.
Copy Otoroshi apikeys from one group to another
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetch = require('node-fetch'); | |
const base64 = require('base-64'); | |
const argv = require('minimist')(process.argv.slice(2)); | |
const OTOROSHI_URL = argv['otoroshi-url'] || 'http://otoroshi-api.foo.bar' | |
const APIKEY_ID = argv['otoroshi-apikey-id'] || 'admin-api-apikey-id' | |
const APIKEY_SECRET = argv['otoroshi-apikey-secret'] || 'admin-api-apikey-secret' | |
const SERVICE_FROM = argv['service-from'] || '--'; | |
const SERVICE_TO = argv['service-to'] || '--'; | |
const authorization = base64.encode(`${APIKEY_ID}:${APIKEY_SECRET}`); | |
function fetchService(id) { | |
return fetch(`${OTOROSHI_URL}/api/services/${id}`, { | |
method: 'GET', | |
headers: { | |
'Authorization': `Basic ${authorization}` | |
} | |
}).then(r => r.json()); | |
} | |
function fetchApiKeys(group) { | |
return fetch(`${OTOROSHI_URL}/api/groups/${group}/apikeys`, { | |
method: 'GET', | |
headers: { | |
'Authorization': `Basic ${authorization}` | |
} | |
}).then(r => r.json()); | |
} | |
function fetchApiKeyTemplate() { | |
return fetch(`${OTOROSHI_URL}/api/new/apikey`, { | |
method: 'GET', | |
headers: { | |
'Authorization': `Basic ${authorization}` | |
} | |
}).then(r => r.json()); | |
} | |
function createApiKey(key) { | |
return fetch(`${OTOROSHI_URL}/api/groups/${key.authorizedGroup}/apikeys`, { | |
method: 'POST', | |
headers: { | |
'Authorization': `Basic ${authorization}`, | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify(key) | |
}).then(r => r.json()); | |
} | |
fetchService(SERVICE_FROM).then(serviceFrom => { | |
fetchService(SERVICE_TO).then(serviceTo => { | |
const fromGroupId = serviceFrom.groupId; | |
const toGroupId = serviceTo.groupId; | |
fetchApiKeys(fromGroupId).then(apikeys => { | |
const newApiKeys = apikeys.map(_key => { | |
const key = { ..._key }; | |
delete key.clientId; | |
delete key.clientSecret; | |
key.authorizedGroup = toGroupId; | |
return key; | |
}); | |
Promise.all(newApiKeys.map(key => { | |
return fetchApiKeyTemplate().then(tmpl => { | |
return createApiKey({ ...tmpl, ...key }); | |
}); | |
})).then(res => { | |
console.log(`${res.length} apikeys copied from ${fromGroupId} to ${toGroupId}`) | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment