Skip to content

Commit bdec750

Browse files
saas-1569 rework auth (#305)
* return auth changes * update version * lower node version + add custom sdk logic coverage * fix build-cli on executing "upload executables" * docs generation test + lower node versions + handle showing contexts when created from env
1 parent f234c2b commit bdec750

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+352
-1095
lines changed

codefresh-release.yml

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ steps:
55

66
fail_if_not_master:
77
title: "Validate running on master branch"
8-
image: codefresh/cli-build
8+
image: codefresh/build-cli
99
commands:
1010
- 'echo This pipeline should be run only on master'
1111
- 'exit 1'
@@ -15,7 +15,7 @@ steps:
1515

1616
extract_version:
1717
title: "Exporting package.json version"
18-
image: codefresh/cli-build
18+
image: codefresh/build-cli
1919
commands:
2020
- 'export PACKAGE_VERSION=$(jq -r ".version" package.json)'
2121
- "echo Current version: $PACKAGE_VERSION"
@@ -40,7 +40,7 @@ steps:
4040

4141
generate_comletion:
4242
title: "Generating commands completion tree"
43-
image: codefresh/cli-build
43+
image: codefresh/build-cli
4444
commands:
4545
- "yarn install"
4646
- "yarn generate-completion"
@@ -53,21 +53,21 @@ steps:
5353

5454
compile_executables:
5555
title: "Compiling executables"
56-
image: codefresh/cli-build
56+
image: codefresh/build-cli
5757
commands:
5858
- "rm -rf dist"
5959
- "yarn pkg"
6060

6161
create_release:
6262
title: "Create github release"
63-
image: codefresh/cli-build
63+
image: codefresh/build-cli
6464
fail_fast: false
6565
commands:
6666
- 'curl --fail -X POST -d ''{"tag_name":"v${{PACKAGE_VERSION}}","target_commitish":"${{CF_REVISION}}","name":"Codefresh V${{PACKAGE_VERSION}}"}'' -H "Content-Type: application/json" -H "Authorization: token ${{GITHUB_TOKEN}}" https://api.github.com/repos/codefresh-io/cli/releases'
6767

6868
get_release:
6969
title: "Get github release"
70-
image: codefresh/cli-build
70+
image: codefresh/build-cli
7171
commands:
7272
- "curl --fail https://api.github.com/repos/codefresh-io/cli/releases/tags/v${{PACKAGE_VERSION}}"
7373
- "export GITHUB_RELEASE_ID=$(curl --fail https://api.github.com/repos/codefresh-io/cli/releases/tags/v${{PACKAGE_VERSION}} | jq -r '.id')"
@@ -76,11 +76,12 @@ steps:
7676

7777
upload_executables:
7878
title: "Upload executables to github release"
79-
image: codefresh/cli-build
79+
image: codefresh/build-cli
8080
commands:
81-
# delete all previous .zip/.gz created files
81+
# delete all previous .zip/.gz created files and copy readme and license to ./dist
8282
- "rm -rf *.gz"
8383
- "rm -rf *.zip"
84+
- "cp README.md LICENSE ./dist --force"
8485
# upload linux-x64 asset
8586
- "mv ./dist/codefresh-linux ./dist/codefresh"
8687
- "tar -cf codefresh-v${{PACKAGE_VERSION}}-linux-x64.tar README.md LICENSE -C ./dist ./codefresh "
@@ -119,7 +120,7 @@ steps:
119120

120121
update_brew_formula:
121122
title: "Updating homebrew formula"
122-
image: codefresh/cli-build
123+
image: codefresh/build-cli
123124
commands:
124125
- VERSION=v${{PACKAGE_VERSION}}
125126
- curl -L https://github.com/codefresh-io/cli/releases/download/$VERSION/codefresh-$VERSION-macos-x64.tar.gz > $VERSION.tar.gz

docs/docs.spec.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
const docs = require('../docs');
2+
3+
describe('docs generation', () => {
4+
it('should generate docs', async () => {
5+
await docs();
6+
});
7+
});

docs/index.js

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const CFError = require('cf-errors');
1010

1111
const TEMP_DIR = path.resolve(__dirname, '../temp');
1212
const TEMPLATE_DIR = path.resolve(__dirname);
13-
const FILES_TO_IGNORE = ['index.js'];
13+
const FILES_TO_IGNORE = ['index.js', 'docs.spec.js'];
1414
const baseDir = path.resolve(TEMP_DIR, './content');
1515
const ALLOW_BETA_COMMANDS = process.env.ALLOW_BETA_COMMANDS;
1616
const categoriesOrder = {
@@ -384,16 +384,23 @@ const createDownloadPage = async () => {
384384

385385
};
386386

387+
const generateDocs = async () => {
388+
await deleteTempFolder();
389+
await copyTemplateToTmp();
390+
await createAutomatedDocs();
391+
await createDownloadPage();
392+
};
387393

388394
const main = async () => {
389395
try {
390-
await deleteTempFolder();
391-
await copyTemplateToTmp();
392-
await createAutomatedDocs();
393-
await createDownloadPage();
396+
await generateDocs();
394397
} catch (err) {
395398
console.error(err.stack);
396399
}
397400
};
398401

399-
main();
402+
if (require.main === module) {
403+
main();
404+
} else {
405+
module.exports = generateDocs;
406+
}

lib/interface/cli/Command.js

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
const yargs = require('yargs');
22
const CFError = require('cf-errors');
3-
const assert = require('assert');
43
const _ = require('lodash');
54
const { wrapHandler } = require('./helpers/general');
6-
const authManager = require('../../logic').auth.manager;
75
const Output = require('../../output/Output');
6+
const { sdk } = require('../../logic');
87

98

109
class Command {
@@ -75,18 +74,17 @@ class Command {
7574

7675
if (subCommand.isBetaCommand()) {
7776
// load beta commands only if authentication exists and it is beta enabled
78-
const currentContext = authManager.getCurrentContext();
77+
const currentContext = sdk.config && sdk.config.context;
7978
if (currentContext && currentContext.isBetaFeatEnabled()) {
8079
yargs.command(subCommand.toCommand());
8180
}
8281
} else if (subCommand.isOnPremCommand()) {
8382
// load onPrem commands only if authentication exists and it is onPrem enabled
84-
const currentContext = authManager.getCurrentContext();
83+
const currentContext = sdk.config && sdk.config.context;
8584
if (currentContext && currentContext.isOnPremFeatEnabled()) {
8685
yargs.command(subCommand.toCommand());
8786
}
88-
}
89-
else {
87+
} else {
9088
yargs.command(subCommand.toCommand());
9189
}
9290
});

lib/interface/cli/codefresh

Lines changed: 6 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -13,62 +13,13 @@ process.on('unhandledRejection', (err) => {
1313
});
1414

1515
if (process.argv.includes('--get-yargs-completions')) {
16-
const initCompletion = require('./completion');
17-
initCompletion().argv;
16+
const completionInterface = require('./completion');
17+
completionInterface().argv; // eslint-disable-line
1818
} else {
19-
const _ = require('lodash');
20-
const yargs = require('yargs');
21-
const path = require('path');
22-
const recursive = require('recursive-readdir');
23-
const DEFAULTS = require('./defaults');
24-
const authManager = require('../../logic').auth.manager;
25-
26-
recursive(path.resolve(__dirname, 'commands'), (err, files) => {
27-
const rootCommands = [];
28-
yargs
29-
.env('')
30-
.options('cfconfig', {
31-
default: DEFAULTS.CFCONFIG,
32-
global: false,
33-
})
34-
.config('cfconfig', 'Custom path for authentication contexts config file', (configFilePath) => {
35-
try {
36-
authManager.loadContexts(process.env.CF_API_KEY, process.env.CF_URL || DEFAULTS.URL, configFilePath);
37-
_.forEach(files, (file) => {
38-
if (file.endsWith('.cmd.js')) {
39-
const command = require(file);
40-
if (command.isRoot()) {
41-
if (command.isBetaCommand()) {
42-
const currentContext = authManager.getCurrentContext();
43-
if (currentContext && currentContext.isBetaFeatEnabled()) {
44-
rootCommands.push(command);
45-
}
46-
} else {
47-
rootCommands.push(command);
48-
}
49-
}
50-
}
51-
});
52-
_.forEach(rootCommands, (command) => {
53-
yargs.command(command.toCommand());
54-
});
55-
} catch (err) {
56-
Output.printError(err);
57-
process.exit(1);
58-
}
59-
});
60-
61-
62-
yargs // eslint-disable-line
63-
.demandCommand(1, 'You need at least one command before moving on')
64-
.wrap(null)
65-
.version(false)
66-
.help('help')
67-
.epilogue('For more information, find our official documentation at http://cli.codefresh.io')
68-
// .option('help', {
69-
// global: false,
70-
// })
71-
.argv;
19+
const commandLineInterface = require('./commad-line-interface');
20+
commandLineInterface().catch((err) => {
21+
Output.printError(err);
22+
process.exit(1);
7223
});
7324
}
7425

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
const _ = require('lodash');
2+
const yargs = require('yargs');
3+
const path = require('path');
4+
const recursive = require('recursive-readdir');
5+
6+
const DEFAULTS = require('./defaults');
7+
const { Config } = require('codefresh-sdk');
8+
const { version } = require('../../../package.json');
9+
const configManager = require('../../logic/cli-config/Manager');
10+
const openapi = require('../../../openapi');
11+
const sdk = require('../../logic/sdk');
12+
13+
const PROCESS_ARGV = require('yargs-parser')(process.argv);
14+
15+
async function startCommandLine() {
16+
const cliConfig = configManager.config();
17+
18+
let files;
19+
let config;
20+
21+
const configOptions = {
22+
configPath: PROCESS_ARGV.cfconfig,
23+
spec: { json: openapi },
24+
request: _.defaultsDeep({
25+
headers: {
26+
'User-Agent': `codefresh-cli-v${version}`,
27+
'Codefresh-Agent': 'cli',
28+
},
29+
}, cliConfig.request),
30+
};
31+
32+
await Promise.all([
33+
recursive(path.resolve(__dirname, 'commands')).then((result) => {
34+
files = result;
35+
}),
36+
Config.load(configOptions).then((result) => {
37+
config = result;
38+
}),
39+
]);
40+
41+
sdk.configure(config);
42+
43+
const rootCommands = [];
44+
_.forEach(files, (file) => {
45+
if (file.endsWith('.cmd.js')) {
46+
const command = require(file);
47+
if (command.isRoot()) {
48+
if (command.isBetaCommand()) {
49+
if (config && config.context && config.context.isBetaFeatEnabled()) {
50+
rootCommands.push(command);
51+
}
52+
} else {
53+
rootCommands.push(command);
54+
}
55+
}
56+
}
57+
});
58+
_.forEach(rootCommands, (command) => {
59+
yargs.command(command.toCommand());
60+
});
61+
62+
return yargs // eslint-disable-line
63+
.env('')
64+
.option('cfconfig', {
65+
describe: `Custom path for authentication contexts config file (default: ${DEFAULTS.CFCONFIG})`,
66+
global: false,
67+
})
68+
.demandCommand(1, 'You need at least one command before moving on')
69+
.wrap(null)
70+
.version(false)
71+
.help('help')
72+
.epilogue('For more information, find our official documentation at http://cli.codefresh.io')
73+
.argv;
74+
}
75+
76+
module.exports = startCommandLine;

lib/interface/cli/commands/auth/create-context.cmd.js

Lines changed: 12 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,7 @@
1-
const debug = require('debug')('codefresh:auth:login');
21
const Command = require('../../Command');
3-
const _ = require('lodash');
4-
const CFError = require('cf-errors');
52
const DEFAULTS = require('../../defaults');
6-
const { auth } = require('../../../../logic');
7-
const { JWTContext, APIKeyContext } = auth.contexts;
8-
const authManager = auth.manager;
3+
const { Config } = require('codefresh-sdk');
94
const authRoot = require('../root/auth.cmd');
10-
const { createContext } = require('../../../../logic/api/auth');
11-
12-
const _loginWithToken = async (url, token) => {
13-
let authContext;
14-
try {
15-
authContext = JWTContext.createFromToken(token, url);
16-
return authContext;
17-
18-
} catch (err) {
19-
try {
20-
authContext = APIKeyContext.createFromToken(token, url);
21-
return authContext;
22-
23-
} catch (err) {
24-
const error = new CFError({
25-
cause: err,
26-
message: 'Failed to login with api key',
27-
});
28-
throw error;
29-
}
30-
}
31-
};
325

336
const command = new Command({
347
command: 'create-context [name]',
@@ -40,7 +13,7 @@ const command = new Command({
4013
title: 'Create Context',
4114
weight: 20,
4215
},
43-
builder: (yargs) => {
16+
builder: (yargs) => { // eslint-disable-line
4417
return yargs
4518
.option('url', {
4619
describe: 'Codefresh system custom url',
@@ -56,38 +29,25 @@ const command = new Command({
5629
})
5730
.example('codefresh auth create-context --api-key KEY', 'Creating a default context using KEY as the api-key')
5831
.example('codefresh auth create-context my-context --api-key KEY', 'Creating a named context');
59-
6032
},
6133
handler: async (argv) => {
62-
const authContext = await _loginWithToken(argv.url, argv['api-key']);
63-
const userData = await authContext.validate();
64-
const roles = _.get(userData,'roles');
34+
const configManager = Config.manager();
35+
await configManager.loadConfig({ configFilePath: argv.cfconfig });
6536

66-
if (roles.indexOf('Admin') > -1) {
67-
authContext.onPrem = true;
68-
}
69-
70-
if (argv.name) {
71-
authContext.setName(argv.name);
72-
}
73-
74-
let updatedExistingContext = false;
75-
if (authManager.getContextByName(authContext.getName())) {
76-
updatedExistingContext = true;
77-
}
37+
const updatedExistingContext = configManager.getContextByName(argv.name);
7838

79-
await authManager.addContext(authContext);
80-
await authManager.setCurrentContext(authContext);
81-
await authManager.persistContexts(authContext);
82-
await createContext();
39+
const context = await configManager.createContext({ apiKey: argv.apiKey, url: argv.url, name: argv.name });
40+
configManager.addContext(context);
41+
configManager.setCurrentContext(context);
42+
await configManager.persistConfig();
8343

8444
if (updatedExistingContext) {
85-
console.log(`Updated context: ${authContext.name}`);
45+
console.log(`Updated context: ${context.name}`);
8646
} else {
87-
console.log(`Created new context: ${authContext.name}`);
47+
console.log(`Created new context: ${context.name}`);
8848
}
8949

90-
console.log(`Switched to context: ${authContext.name}`);
50+
console.log(`Switched to context: ${context.name}`);
9151
},
9252
});
9353

0 commit comments

Comments
 (0)