Skip to content

Commit

Permalink
depromisify more stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
pirog committed Dec 13, 2024
1 parent 744985c commit 201b562
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 41 deletions.
16 changes: 9 additions & 7 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const utils = require('./lib/utils');
* @param {Object} lando - The Lando config object
* @return {void}
*/
module.exports = (app, lando) => {
module.exports = async (app, lando) => {
// Add additional things to cleanse
app.log.alsoSanitize('pantheon-auth');

Expand All @@ -29,14 +29,16 @@ module.exports = (app, lando) => {
* @param {Object} answers - User provided answers/input
* @return {Promise} Resolves when token validation and caching is complete
*/
app.events.on(`post-${command}`, (config, answers) => {
app.events.on(`post-${command}`, async (config, answers) => {
// get existing token and email
const {token, email} = lando.cache.get(app.metaCache);
// Only run if answer.auth is set, the tokens are different or the email is blank
// this allows these commands to all be overriden without causing a failure here
if (answers.auth && (answers.auth !== token || !email)) {
const api = new PantheonApiClient(answers.auth, app.log);
return api.auth().then(async () => {

try {
await api.auth();
const results = await api.getUser();
const cache = {token: answers.auth, email: results.email, date: _.toInteger(_.now() / 1000)};
// Reset this apps metacache
Expand All @@ -45,12 +47,12 @@ module.exports = (app, lando) => {
lando.cache.set(app.pantheonTokenCache, utils.sortTokens(app.pantheonTokens, [cache]), {persist: true});
// Wipe out the apps tooling cache to reset with the new MT
lando.cache.remove(`${app.name}.tooling.cache`);
})

// Throw some sort of error
// NOTE: this provides some error handling when we are completely non-interactive
.catch(err => {
throw (_.has(err, 'response.data')) ? new Error(err.response.data) : err;
});
} catch (error) {
throw (_.has(error, 'response.data')) ? new Error(error.response.data) : error;
}
}
});
});
Expand Down
2 changes: 2 additions & 0 deletions builders/pantheon.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const setTooling = (options, tokens) => {
const tokenEnv = metaToken !== null ?
{LANDO_TERMINUS_TOKEN: metaToken}
: {};

// Add in push/pull/switch
options.tooling.pull = pull.getPantheonPull(options, tokens);
options.tooling.push = push.getPantheonPush(options, tokens);
Expand Down Expand Up @@ -184,6 +185,7 @@ module.exports = {

// Handle other stuff
const tokens = utils.sortTokens(options._app.pantheonTokens, options._app.terminusTokens);

options = setTooling(options, tokens);
options = setBuildSteps(options);

Expand Down
9 changes: 6 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const clearInvalidTokenFromToolingCache = (lando, cacheKey, meta, data) => {
const errorIs401 = error => error.message.includes('failed with code 401');

const checkTokens = (lando, command) => {
lando.events.on(`cli-${command}-answers`, data => {
lando.events.on(`cli-${command}-answers`, async data => {
if (_.get(data, 'options._app.recipe') === 'pantheon') {
// Gather the things we need
const cacheKey = _.get(data, 'options._app.metaCache');
Expand All @@ -29,7 +29,10 @@ const checkTokens = (lando, command) => {

if (!_.isEmpty(cachedToken)) {
// Make sure our token is good beforehand
return new PantheonApi(cachedToken, lando.log).auth().catch(error => {
const api = new PantheonApi(cachedToken, lando.log);
try {
await api.auth();
} catch (error) {
if (errorIs401(error)) {
// Remove the bad token from the global token cache.
removeInvalidGlobalTokens(lando, cachedToken);
Expand All @@ -39,7 +42,7 @@ const checkTokens = (lando, command) => {
delete data.options.auth;
console.log(lando.cli.makeArt('badToken'));
}
});
}
}
}
});
Expand Down
12 changes: 10 additions & 2 deletions inits/pantheon.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,14 @@ const getAutoCompleteSites = async (answers, lando, input = null) => {
return pantheonSites.filter(site => _.startsWith(site.name, input));
}

// get client
const api = new PantheonApiClient(answers['pantheon-auth'], lando.log);
// auth it
await api.auth();
// get sites
const sites = await api.getSites();

// return them
pantheonSites = sites.map(site => ({name: site.name, value: site.name}));
return pantheonSites;
};
Expand Down Expand Up @@ -117,15 +122,19 @@ module.exports = {
{name: 'wait-for-user', cmd: '/helpers/pantheon-wait-for-user.sh'},
{name: 'generate-key', cmd: `/helpers/generate-key.sh ${pantheonLandoKey} ${pantheonLandoKeyComment}`},
{name: 'post-key', func: async (options, lando) => {
// key and client
const api = new PantheonApiClient(options['pantheon-auth'], lando.log);
const pubKey = path.join(lando.config.userConfRoot, 'keys', `${pantheonLandoKey}.pub`);

await api.auth();
return api.postKey(pubKey);
return await api.postKey(pubKey);
}},
{name: 'get-git-url', func: async (options, lando) => {
const api = new PantheonApiClient(options['pantheon-auth'], lando.log);

await api.auth();
const site = await api.getSite(options['pantheon-site'], false);

options['pantheon-git-url'] = getGitUrl(site);
}},
{name: 'reload-keys', cmd: '/helpers/load-keys.sh --silent', user: 'root'},
Expand Down Expand Up @@ -153,7 +162,6 @@ module.exports = {
// Authenticate and post keys
await api.auth();
await api.postKey(pubKey);
await api.auth();

// Get site and user info
const [site, user] = await Promise.all([
Expand Down
64 changes: 35 additions & 29 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,31 +90,36 @@ module.exports = class PantheonApiClient {
const options = (this.mode === 'node') ? {headers: {'User-Agent': 'Terminus/Lando'}} : {};
const upath = ['authorize', 'machine-token'];

return await pantheonRequest(axios.create({baseURL: this.baseURL}), this.log, 'post', upath, data, options).then(data => {
this.token = token;
this.session = data;
const headers = {'Content-Type': 'application/json'};
// Add header if we are in node mode, otherwise assume its set upstream in the browser
if (this.mode === 'node') headers['X-Pantheon-Session'] = data.session;
this.request = axios.create({baseURL: this.baseURL, headers});
return data;
});
// get the auth
const auth = await pantheonRequest(axios.create({baseURL: this.baseURL}), this.log, 'post', upath, data, options);

// and set stuff with it
this.token = token;
this.session = auth;

// set headers
const headers = {'Content-Type': 'application/json'};
// Add header if we are in node mode, otherwise assume its set upstream in the browser
if (this.mode === 'node') headers['X-Pantheon-Session'] = auth.session;

this.request = axios.create({baseURL: this.baseURL, headers});

return auth;
}

/**
* Get information about a specific Pantheon site
*
* @param {string} site - Site name or ID
* @param {string} id - Site name or ID
* @param {boolean} full - Whether to return full site details
* @return {Promise<Object>} Site information
*/
async getSite(site, full = true) {
return await pantheonRequest(this.request, this.log, 'get', ['site-names', site]).then(site => {
// if not full then just return the lookup
if (!full) return site;
// otherwise return the full site
return pantheonRequest(this.request, this.log, 'get', ['sites', site.id]);
});
async getSite(id, full = true) {
const site = await pantheonRequest(this.request, this.log, 'get', ['site-names', id]);
// if not full then just return the lookup
if (!full) return site;
// otherwise return the full site
return await pantheonRequest(this.request, this.log, 'get', ['sites', site.id]);
}

/**
Expand All @@ -127,20 +132,21 @@ module.exports = class PantheonApiClient {
// Call to get user sites
const pantheonUserSites = async () => {
const getSites = ['users', _.get(this.session, 'user_id'), 'memberships', 'sites'];
return pantheonRequest(this.request, this.log, 'get', getSites, {params: {limit: MAX_SITES}})
.then(sites => _.map(sites, site => _.merge(site, site.site)));
const sites = await pantheonRequest(this.request, this.log, 'get', getSites, {params: {limit: MAX_SITES}});
return _.map(sites, site => _.merge(site, site.site));
};

// Call to get org sites
const pantheonOrgSites = async () => {
const getOrgs = ['users', _.get(this.session, 'user_id'), 'memberships', 'organizations'];
return pantheonRequest(this.request, this.log, 'get', getOrgs).then(orgs => {
return Promise.all(orgs.filter(org => org.role !== 'unprivileged').map(async org => {
const getOrgsSites = ['organizations', org.id, 'memberships', 'sites'];
return pantheonRequest(this.request, this.log, 'get', getOrgsSites, {params: {limit: MAX_SITES}})
.then(sites => sites.map(site => _.merge(site, site.site)));
}))
.then(sites => _.flatten(sites));
});
const orgs = await pantheonRequest(this.request, this.log, 'get', getOrgs);

return await Promise.all(orgs.filter(org => org.role !== 'unprivileged').map(async org => {
const getOrgsSites = ['organizations', org.id, 'memberships', 'sites'];
const sites = await pantheonRequest(this.request, this.log, 'get', getOrgsSites, {params: {limit: MAX_SITES}});
return sites.map(site => _.merge(site, site.site));
}))
.then(sites => _.flatten(sites));
};

// Run both requests
Expand Down Expand Up @@ -177,10 +183,10 @@ module.exports = class PantheonApiClient {
* @param {string} key - Path to SSH public key file
* @return {Promise<Object>} Response from key upload
*/
postKey(key) {
async postKey(key) {
const postKey = ['users', _.get(this.session, 'user_id'), 'keys'];
const options = (this.mode === 'node') ? {headers: {'User-Agent': 'Terminus/Lando'}} : {};
const data = _.trim(fs.readFileSync(key, 'utf8'));
return pantheonRequest(this.request, this.log, 'post', postKey, JSON.stringify(data), options);
return await pantheonRequest(this.request, this.log, 'post', postKey, JSON.stringify(data), options);
}
};

0 comments on commit 201b562

Please sign in to comment.