@copado/copado-cli
Version:
Copado Developer CLI
110 lines • 6.12 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@salesforce/core");
const restConnections_1 = require("../../../service/restConnections");
const filesystem_1 = require("../../../copado_commons/filesystem");
const core_2 = require("@oclif/core");
const sf_plugins_core_1 = require("@salesforce/sf-plugins-core");
const kit_1 = require("@salesforce/kit");
core_1.Messages.importMessagesDirectory(__dirname);
const messages = core_1.Messages.loadMessages('@copado/copado-cli', 'copado_auth');
const logSymbols = require('log-symbols');
class AuthGrant extends sf_plugins_core_1.SfCommand {
async run() {
core_2.ux.action.start('Creating ScratchOrg information in Copado');
let authUrl;
const copadoUser = await filesystem_1.CopadoFiles.getCurrentUser();
const { flags } = await this.parse(AuthGrant);
const targetScratchOrgUserName = flags.targetusername ? flags.targetusername : await this.getDefaultUserName();
const scratchOrgAuthInfo = await this.getUserName(targetScratchOrgUserName).then(targetName => this.getUserInfo(targetName).then(authInfo => {
authUrl = authInfo.getSfdxAuthUrl();
return authInfo.getFields();
}));
await this.isScratchOrg(scratchOrgAuthInfo.devHubUsername).then(() => this.isExpired(scratchOrgAuthInfo.expirationDate));
const devHubInfo = await this.getUserInfo(scratchOrgAuthInfo.devHubUsername).then(authInfo => authInfo.getFields());
const pushResult = await restConnections_1.RestConnections.restServiceCall('auth', 'grant', '', {
environmentName: flags.environmentname,
scratchOrgUserName: scratchOrgAuthInfo.username,
scratchOrgId: scratchOrgAuthInfo.orgId,
scratchOrgExpirationDate: scratchOrgAuthInfo.expirationDate,
devHubUserName: scratchOrgAuthInfo.devHubUsername,
devHubOrgId: devHubInfo.orgId,
authInfo: authUrl
}, copadoUser);
if (flags.wait)
await this.polling(pushResult.orgCredentialId, copadoUser);
core_2.ux.action.stop(logSymbols.success);
core_2.ux.log(messages.getMessage('grant.scratchOrgCreated'), `\nCredential Id: ${pushResult.orgCredentialId}`, `\nEnvironment Id: ${pushResult.environmentId}`);
return { success: true, message: pushResult.message, environmentId: pushResult.environmentId, orgCredentialId: pushResult.orgCredentialId };
}
async getUserName(targetUsName) {
const userNames = await core_1.AuthInfo.listAllAuthorizations().then(auth => {
return auth === null || auth === void 0 ? void 0 : auth.map(authfile => authfile.username);
});
const stateAggregator = await core_1.StateAggregator.getInstance();
let userName;
const allAlias = stateAggregator.aliases.getAll();
if (allAlias.hasOwnProperty(targetUsName)) {
userName = stateAggregator.aliases.resolveUsername(targetUsName);
}
if (!userName && !userNames.includes(targetUsName)) {
throw new core_1.SfError(messages.getMessage('grant.noUserNameFound'));
}
return userName ? userName : targetUsName;
}
async getUserInfo(targetUser) {
return await core_1.AuthInfo.create({
username: targetUser
});
}
async getDefaultUserName() {
return await core_1.ConfigAggregator.create().then(defaultConfig => { var _a; return (_a = defaultConfig.getPropertyValue('target-org')) === null || _a === void 0 ? void 0 : _a.toString(); }) || await core_1.ConfigAggregator.create().then(defaultConfig => { var _a; return (_a = defaultConfig.getPropertyValue('defaultusername')) === null || _a === void 0 ? void 0 : _a.toString(); });
}
async isScratchOrg(devHubUsername) {
// Note: If authinfo does not contain "devHubUsername" it is not a ScratchOrg
if (!devHubUsername) {
core_2.ux.action.stop(logSymbols.error);
throw new core_1.SfError(messages.getMessage('grant.noScratchOrg'));
}
}
async isExpired(expDate) {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDay());
if (today > new Date(expDate))
throw new core_1.SfError(messages.getMessage('grant.scratchOrgExpired'));
}
async polling(orgId, user) {
core_2.ux.action.stop(logSymbols.success);
core_2.ux.action.start(`Authorizing scratch org in Copado`);
const query = `SELECT Id, isFinished__c, isSuccess__c FROM Copado_Notification__c WHERE ParentId__c = '${orgId}' LIMIT 1`;
const conn = await core_1.Connection.create({
authInfo: await this.getUserInfo(user)
});
// polling
const options = {
async poll() {
const queryResult = await conn.query(query);
return Promise.resolve({ completed: queryResult.totalSize > 0 && queryResult.records[0].isSuccess__c, payload: 'Job done' });
},
frequency: kit_1.Duration.milliseconds(2000),
timeout: kit_1.Duration.minutes(5),
timeoutErrorName: 'Unable to retrieve authentication status, operation timed out.'
};
const client = await core_1.PollingClient.create(options);
await client.subscribe();
}
}
AuthGrant.description = messages.getMessage('grant.commandDescription');
AuthGrant.examples = [messages.getMessage('grant.exampleDescription')];
AuthGrant.supportsUsername = true;
AuthGrant.flags = {
environmentname: sf_plugins_core_1.Flags.string({
char: 'e',
description: messages.getMessage('grant.environmentNameFlagDescription'),
required: true
}),
wait: sf_plugins_core_1.Flags.boolean({ char: 'w', description: messages.getMessage('grant.waitFlagDescription'), default: false }),
targetusername: sf_plugins_core_1.Flags.string({ char: 'u', description: messages.getMessage('set.flags.targetusername') })
};
exports.default = AuthGrant;
//# sourceMappingURL=grant.js.map