@contentstack/cli-auth 0.1.1-beta.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
4
+ const interactive_1 = require("./interactive");
5
+ /**
6
+ * @class
7
+ * Auth handler
8
+ */
9
+ class AuthHandler {
10
+ set client(contentStackClient) {
11
+ this._client = contentStackClient;
12
+ }
13
+ /**
14
+ *
15
+ *
16
+ * Login into Contentstack
17
+ * @param {string} email Contentstack email address
18
+ * @param {string} password User's password for contentstack account
19
+ * @returns {Promise} Promise object returns authtoken on success
20
+ * TBD: take out the otp implementation from login and create a new method/function to handle otp
21
+ */
22
+ async login(email, password, tfaToken) {
23
+ return new Promise((resolve, reject) => {
24
+ if (email && password) {
25
+ const loginPayload = { email, password };
26
+ if (tfaToken) {
27
+ loginPayload.tfa_token = tfaToken;
28
+ }
29
+ this._client
30
+ .login(loginPayload)
31
+ .then(async (result) => {
32
+ cli_utilities_1.logger.debug('login result', result);
33
+ if (result.user) {
34
+ resolve(result.user);
35
+ }
36
+ else if (result.error_code === 294) {
37
+ const otpChannel = await (0, interactive_1.askOTPChannel)();
38
+ // need to send sms to the mobile
39
+ if (otpChannel === 'sms') {
40
+ try {
41
+ await this._client.axiosInstance.post('/user/request_token_sms', { user: loginPayload });
42
+ cli_utilities_1.cliux.print('CLI_AUTH_LOGIN_SECURITY_CODE_SEND_SUCCESS');
43
+ }
44
+ catch (error) {
45
+ cli_utilities_1.logger.error('Failed to send the security code', error);
46
+ reject(new cli_utilities_1.CLIError({ message: 'Failed to login - failed to send the security code' }));
47
+ return;
48
+ }
49
+ }
50
+ const tfToken = await (0, interactive_1.askOTP)();
51
+ try {
52
+ resolve(await this.login(email, password, tfToken));
53
+ }
54
+ catch (error) {
55
+ cli_utilities_1.logger.error('Failed to login with tfa token', error);
56
+ reject(new cli_utilities_1.CLIError({ message: 'Failed to login with the tf token' }));
57
+ }
58
+ }
59
+ else {
60
+ reject(new cli_utilities_1.CLIError({ message: 'No user found with the credentials' }));
61
+ }
62
+ })
63
+ .catch((error) => {
64
+ cli_utilities_1.logger.error('Failed to login', error);
65
+ reject(new cli_utilities_1.CLIError({ message: error.errorMessage }));
66
+ });
67
+ }
68
+ else {
69
+ reject(new cli_utilities_1.CLIError({ message: 'No credential found to login' }));
70
+ }
71
+ });
72
+ }
73
+ /**
74
+ * Logout from Contentstack
75
+ * @param {string} authtoken authtoken that needs to invalidated when logging out
76
+ * @returns {Promise} Promise object returns response object from Contentstack
77
+ */
78
+ async logout(authtoken) {
79
+ return new Promise((resolve, reject) => {
80
+ if (authtoken) {
81
+ this._client
82
+ .logout(authtoken)
83
+ .then(function (response) {
84
+ return resolve(response);
85
+ })
86
+ .catch((error) => {
87
+ cli_utilities_1.logger.error('Failed to logout', error);
88
+ return reject(new cli_utilities_1.CLIError({ message: 'Failed to logout - ' + error.message }));
89
+ });
90
+ }
91
+ else {
92
+ reject(new cli_utilities_1.CLIError({ message: 'No auth token found to logout' }));
93
+ }
94
+ });
95
+ }
96
+ /**
97
+ * Validate token
98
+ * @param {string} authtoken
99
+ * @returns {Promise} Promise object returns response object from Contentstack
100
+ */
101
+ async validateAuthtoken(authtoken) {
102
+ return new Promise((resolve, reject) => {
103
+ if (authtoken) {
104
+ this._client
105
+ .getUser()
106
+ .then((user) => resolve(user))
107
+ .catch((error) => {
108
+ cli_utilities_1.logger.error('Failed to validate token', error);
109
+ reject(new cli_utilities_1.CLIError({ message: 'Failed to validate token - ' + error.message }));
110
+ });
111
+ }
112
+ else {
113
+ reject(new cli_utilities_1.CLIError({ message: 'No auth token found to validate' }));
114
+ }
115
+ });
116
+ }
117
+ }
118
+ exports.default = new AuthHandler();
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tokenValidation = exports.interactive = exports.authHandler = void 0;
4
+ var auth_handler_1 = require("./auth-handler");
5
+ Object.defineProperty(exports, "authHandler", { enumerable: true, get: function () { return auth_handler_1.default; } });
6
+ exports.interactive = require("./interactive");
7
+ exports.tokenValidation = require("./tokens-validation");
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.askTokenType = exports.askUsername = exports.askOTP = exports.askOTPChannel = exports.askPassword = void 0;
4
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
5
+ const askPassword = async () => {
6
+ return cli_utilities_1.cliux.inquire({
7
+ type: 'input',
8
+ message: 'CLI_AUTH_LOGIN_ENTER_PASSWORD',
9
+ name: 'password',
10
+ transformer: (pswd) => {
11
+ return '*'.repeat(pswd.length);
12
+ },
13
+ });
14
+ };
15
+ exports.askPassword = askPassword;
16
+ const askOTPChannel = async () => {
17
+ return cli_utilities_1.cliux.inquire({
18
+ type: 'list',
19
+ name: 'otpChannel',
20
+ message: 'CLI_AUTH_LOGIN_ASK_CHANNEL_FOR_OTP',
21
+ choices: [
22
+ { name: 'Authy App', value: 'authy' },
23
+ { name: 'SMS', value: 'sms' },
24
+ ],
25
+ });
26
+ };
27
+ exports.askOTPChannel = askOTPChannel;
28
+ const askOTP = async () => {
29
+ return cli_utilities_1.cliux.inquire({
30
+ type: 'input',
31
+ message: 'CLI_AUTH_LOGIN_ENTER_SECURITY_CODE',
32
+ name: 'tfaToken',
33
+ });
34
+ };
35
+ exports.askOTP = askOTP;
36
+ const askUsername = async () => {
37
+ return cli_utilities_1.cliux.inquire({
38
+ type: 'input',
39
+ message: 'CLI_AUTH_LOGIN_ENTER_EMAIL_ADDRESS',
40
+ name: 'username',
41
+ });
42
+ };
43
+ exports.askUsername = askUsername;
44
+ const askTokenType = async () => {
45
+ return cli_utilities_1.cliux.inquire({
46
+ type: 'list',
47
+ name: 'tokenType',
48
+ message: 'CLI_SELECT_TOKEN_TYPE',
49
+ choices: [
50
+ { name: 'Management Token', value: 'management' },
51
+ { name: 'Delivery Token', value: 'delivery' },
52
+ ]
53
+ });
54
+ };
55
+ exports.askTokenType = askTokenType;
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateAPIKey = exports.validateManagementToken = exports.validateEnvironment = exports.validateDeliveryToken = void 0;
4
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
5
+ /**
6
+ * Validate delivery token
7
+ * @param contentStackClient
8
+ * @param apiKey
9
+ * @param deliveryToken
10
+ * @returns
11
+ */
12
+ const validateDeliveryToken = async (contentStackClient, apiKey, deliveryToken) => {
13
+ let result;
14
+ try {
15
+ const deliveryTokenResult = await contentStackClient
16
+ .stack({ api_key: apiKey })
17
+ .deliveryToken()
18
+ .query({ query: { token: deliveryToken } })
19
+ .find();
20
+ cli_utilities_1.logger.debug('delivery token validation result', deliveryTokenResult);
21
+ if (Array.isArray(deliveryTokenResult.items) && deliveryTokenResult.items.length > 0) {
22
+ result = { valid: true, message: deliveryTokenResult };
23
+ }
24
+ else {
25
+ result = { valid: false, message: cli_utilities_1.messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_DELIVERY_TOKEN') };
26
+ }
27
+ }
28
+ catch (error) {
29
+ cli_utilities_1.logger.debug('validate delivery token error', error);
30
+ result = { valid: false, message: cli_utilities_1.messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_DELIVERY_TOKEN') };
31
+ }
32
+ return result;
33
+ };
34
+ exports.validateDeliveryToken = validateDeliveryToken;
35
+ /**
36
+ * Validate environment
37
+ * @param contentStackClient
38
+ * @param apiKey
39
+ * @param environment
40
+ * @returns
41
+ */
42
+ const validateEnvironment = async (contentStackClient, apiKey, environment) => {
43
+ let result;
44
+ try {
45
+ const validationResult = await contentStackClient.stack({ api_key: apiKey }).environment(environment).fetch();
46
+ cli_utilities_1.logger.debug('environment validation result', validationResult);
47
+ if (validationResult.name === environment) {
48
+ result = { valid: true, message: validationResult };
49
+ }
50
+ else {
51
+ result = { valid: false, message: cli_utilities_1.messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_ENVIRONMENT_NAME') };
52
+ }
53
+ }
54
+ catch (error) {
55
+ cli_utilities_1.logger.error('validate environment error', error);
56
+ result = { valid: false, message: 'CLI_AUTH_TOKENS_VALIDATION_INVALID_ENVIRONMENT_NAME' };
57
+ }
58
+ return result;
59
+ };
60
+ exports.validateEnvironment = validateEnvironment;
61
+ /**
62
+ * Validate management token
63
+ * @param contentStackClient
64
+ * @param apiKey
65
+ * @param managementToken
66
+ * @returns { valid: boolean; message: any }
67
+ * Note: Fetching one content type using the management token to check whether it is valid or not
68
+ */
69
+ const validateManagementToken = async (contentStackClient, apiKey, managementToken) => {
70
+ let result;
71
+ try {
72
+ const validationResuslt = await contentStackClient.axiosInstance.get('/content_types?limit=1', {
73
+ headers: { api_key: apiKey, authorization: managementToken },
74
+ });
75
+ cli_utilities_1.logger.debug('Management validation result', validationResuslt);
76
+ if (validationResuslt.status === 200) {
77
+ result = { valid: true, message: validationResuslt };
78
+ }
79
+ else {
80
+ result = { valid: false, message: cli_utilities_1.messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_MANAGEMENT_TOKEN') };
81
+ }
82
+ }
83
+ catch (error) {
84
+ cli_utilities_1.logger.error('Failed to validate management token', error);
85
+ result = { valid: false, message: cli_utilities_1.messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_MANAGEMENT_TOKEN') };
86
+ }
87
+ return result;
88
+ };
89
+ exports.validateManagementToken = validateManagementToken;
90
+ /**
91
+ * Validate API key
92
+ * @param contentStackClient
93
+ * @param apiKey
94
+ * @returns
95
+ */
96
+ const validateAPIKey = async (contentStackClient, apiKey) => {
97
+ let result;
98
+ try {
99
+ const validateAPIKeyResult = await contentStackClient.stack({ api_key: apiKey }).fetch();
100
+ cli_utilities_1.logger.debug('api key validation result', validateAPIKeyResult);
101
+ if (validateAPIKeyResult.api_key === apiKey) {
102
+ result = { valid: true, message: validateAPIKeyResult };
103
+ }
104
+ else {
105
+ result = { valid: false, message: cli_utilities_1.messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_API_KEY') };
106
+ }
107
+ }
108
+ catch (error) {
109
+ cli_utilities_1.logger.error('validate api key error', error);
110
+ result = { valid: false, message: cli_utilities_1.messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_API_KEY') };
111
+ }
112
+ return result;
113
+ };
114
+ exports.validateAPIKey = validateAPIKey;
@@ -1 +1 @@
1
- {"version":"0.1.1-beta.1","commands":{"auth:login":{"id":"auth:login","description":"Login to Contentstack and save the session for further use","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["login"],"flags":{"username":{"name":"username","type":"option","char":"u","description":"Email address of your Contentstack account"}},"args":[]},"auth:logout":{"id":"auth:logout","description":"Log out from Contentstack and clear the session","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["logout"],"flags":{"force":{"name":"force","type":"boolean","char":"f","description":"Exclude confirmation to logout","allowNo":false}},"args":[]},"auth:whoami":{"id":"auth:whoami","description":"Display current users email address\n","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["whoami"],"flags":{},"args":[]},"auth:tokens:add":{"id":"auth:tokens:add","description":"Adds management/delivery tokens to your session to use it with further CLI command\nby default it adds management token if either of management or delivery flags are not set","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["tokens:add"],"flags":{"alias":{"name":"alias","type":"option","char":"a"},"delivery":{"name":"delivery","type":"boolean","char":"d","description":"Set this while saving delivery token","allowNo":false},"management":{"name":"management","type":"boolean","char":"m","description":"Set this while saving management token","allowNo":false},"environment":{"name":"environment","type":"option","char":"e","description":"Environment name for delivery token"},"api-key":{"name":"api-key","type":"option","char":"k","description":"Stack API key for the token"},"force":{"name":"force","type":"boolean","char":"f","description":"Exclude confirmation to replace existing alias","allowNo":false},"token":{"name":"token","type":"option","char":"t","description":"Sets token. Can be set via environment variable 'TOKEN'. We recommend to use env variable"}},"args":[]},"auth:tokens":{"id":"auth:tokens","description":"Lists all existing tokens added to the session \n","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["tokens"],"flags":{"columns":{"name":"columns","type":"option","description":"only show provided columns (comma-separated)"},"sort":{"name":"sort","type":"option","description":"property to sort by (prepend '-' for descending)"},"filter":{"name":"filter","type":"option","description":"filter property by partial string matching, ex: name=foo"},"csv":{"name":"csv","type":"boolean","description":"output is csv format [alias: --output=csv]","allowNo":false},"output":{"name":"output","type":"option","description":"output in a more machine friendly format","options":["csv","json","yaml"]},"extended":{"name":"extended","type":"boolean","char":"x","description":"show extra columns","allowNo":false},"no-truncate":{"name":"no-truncate","type":"boolean","description":"do not truncate output to fit screen","allowNo":false},"no-header":{"name":"no-header","type":"boolean","description":"hide table header from output","allowNo":false}},"args":[]},"auth:tokens:remove":{"id":"auth:tokens:remove","description":"Removes stored tokens","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["tokens:remove"],"flags":{"alias":{"name":"alias","type":"option","char":"a","description":"Alias (name) of the token to remove"},"ignore":{"name":"ignore","type":"boolean","char":"i","description":"Ignores if token not present. Command shows show list of available aliases with multi select option to delete tokens from that list.","allowNo":false}},"args":[]}}}
1
+ {"version":"1.0.0","commands":{"auth:login":{"id":"auth:login","description":"User sessions login","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["login"],"examples":["$ csdx auth:login","$ csdx auth:login -u <username>","$ csdx auth:login -u <username> -p <password>","$ csdx auth:login --username <username>","$ csdx auth:login --username <username> --password <password>"],"flags":{"username":{"name":"username","type":"option","char":"u","description":"User name","required":false},"password":{"name":"password","type":"option","char":"p","description":"Password","required":false}},"args":[]},"auth:logout":{"id":"auth:logout","description":"User session logout","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["logout"],"examples":["$ csdx auth:logout","$ csdx auth:logout -y","$ csdx auth:logout --yes"],"flags":{"yes":{"name":"yes","type":"boolean","char":"y","description":"Force log out by skipping the confirmation","required":false,"allowNo":false},"force":{"name":"force","type":"boolean","char":"f","description":"Force log out by skipping the confirmation","hidden":true,"required":false,"allowNo":false}},"args":[]},"auth:whoami":{"id":"auth:whoami","description":"Display current users email address","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["whoami"],"examples":["$ csdx auth:whoami"],"flags":{},"args":[]},"auth:tokens:add":{"id":"auth:tokens:add","description":"Adds management/delivery tokens to your session to use it with other CLI commands","usage":"auth:tokens:add [-a <value>] [--delivery] [--management] [-e <value>] [-k <value>] [-y] [--token <value>]","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":[],"examples":["$ csdx auth:tokens:add","$ csdx auth:tokens:add -a <alias>","$ csdx auth:tokens:add -k <stack api key>","$ csdx auth:tokens:add --delivery","$ csdx auth:tokens:add --management","$ csdx auth:tokens:add -e <environment>","$ csdx auth:tokens:add --token <token>","$ csdx auth:tokens:add -a <alias> -k <stack api key> --management --token <management token>","$ csdx auth:tokens:add -a <alias> -k <stack api key> --delivery -e <environment> --token <delivery token>","$ csdx auth:tokens:add --alias <alias> --stack-api-key <stack api key> --management --token <management token>","$ csdx auth:tokens:add --alias <alias> --stack-api-key <stack api key> --delivery -e <environment> --token <delivery token>"],"flags":{"alias":{"name":"alias","type":"option","char":"a","description":"Name of the token alias"},"delivery":{"name":"delivery","type":"boolean","char":"d","description":"Set this flag to save delivery token","allowNo":false},"management":{"name":"management","type":"boolean","char":"m","description":"Set this flag to save management token","allowNo":false},"environment":{"name":"environment","type":"option","char":"e","description":"Environment name for delivery token"},"stack-api-key":{"name":"stack-api-key","type":"option","char":"k","description":"Stack API Key"},"yes":{"name":"yes","type":"boolean","char":"y","description":"Use this flag to skip confirmation","allowNo":false},"token":{"name":"token","type":"option","char":"t","description":"Add the token name"},"api-key":{"name":"api-key","type":"option","description":"API Key","hidden":true},"force":{"name":"force","type":"boolean","char":"f","description":"Force adding","hidden":true,"allowNo":false}},"args":[]},"auth:tokens":{"id":"auth:tokens","description":"Lists all existing tokens added to the session","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":["tokens"],"examples":["$ csdx auth:tokens"],"flags":{"columns":{"name":"columns","type":"option","description":"only show provided columns (comma-separated)"},"sort":{"name":"sort","type":"option","description":"property to sort by (prepend '-' for descending)"},"filter":{"name":"filter","type":"option","description":"filter property by partial string matching, ex: name=foo"},"csv":{"name":"csv","type":"boolean","description":"output is csv format [alias: --output=csv]","allowNo":false},"output":{"name":"output","type":"option","description":"output in a more machine friendly format","options":["csv","json","yaml"]},"extended":{"name":"extended","type":"boolean","char":"x","description":"show extra columns","allowNo":false},"no-truncate":{"name":"no-truncate","type":"boolean","description":"do not truncate output to fit screen","allowNo":false},"no-header":{"name":"no-header","type":"boolean","description":"hide table header from output","allowNo":false}},"args":[]},"auth:tokens:remove":{"id":"auth:tokens:remove","description":"Removes selected tokens","pluginName":"@contentstack/cli-auth","pluginType":"core","aliases":[],"examples":["$ csdx auth:tokens:remove","$ csdx auth:tokens:remove -a <alias>"],"flags":{"alias":{"name":"alias","type":"option","char":"a","description":"Token alias"},"ignore":{"name":"ignore","type":"boolean","char":"i","description":"Ignore","allowNo":false}},"args":[]}}}
package/package.json CHANGED
@@ -1,61 +1,84 @@
1
1
  {
2
2
  "name": "@contentstack/cli-auth",
3
3
  "description": "Contentstack CLI plugin for authentication activities",
4
- "version": "0.1.1-beta.1",
4
+ "version": "1.0.0",
5
5
  "author": "Contentstack",
6
6
  "bugs": "https://github.com/contentstack/cli/issues",
7
+ "scripts": {
8
+ "build": "npm run clean && npm run compile",
9
+ "clean": "rm -rf ./lib && rm -rf tsconfig.build.tsbuildinfo",
10
+ "compile": "tsc -b tsconfig.json",
11
+ "postpack": "rm -f oclif.manifest.json",
12
+ "prepack": "npm run build && oclif-dev manifest && oclif-dev readme",
13
+ "version": "oclif-dev readme && git add README.md",
14
+ "test:report": "tsc -p test && nyc --reporter=lcov --extension .ts mocha --forbid-only \"test/**/*.test.ts\"",
15
+ "pretest": "tsc -p test",
16
+ "test": "nyc --extension .ts mocha --forbid-only \"test/**/*.test.ts\"",
17
+ "posttest": "npm run lint",
18
+ "lint": "eslint src/**/*.ts",
19
+ "format": "eslint src/**/*.ts --fix"
20
+ },
7
21
  "dependencies": {
8
- "@contentstack/cli-command": "0.1.1-beta.1",
9
- "@oclif/command": "^1.6.1",
10
- "@oclif/config": "^1.15.1",
22
+ "@contentstack/cli-command": "^1.0.0",
23
+ "@contentstack/cli-utilities": "^1.0.0",
24
+ "@oclif/command": "^1.8.16",
25
+ "@oclif/config": "^1.18.3",
11
26
  "chalk": "^4.0.0",
12
- "cli-ux": "^5.4.6",
13
- "configstore": "^5.0.1",
14
27
  "debug": "^4.1.1",
15
- "inquirer": "^7.1.0"
28
+ "inquirer": "^7.1.0",
29
+ "winston": "^3.7.2"
16
30
  },
17
31
  "devDependencies": {
18
32
  "@oclif/dev-cli": "^1.22.2",
19
- "@oclif/plugin-help": "^2.2.3",
20
- "@oclif/test": "^1.2.5",
21
- "chai": "^4.2.0",
22
- "eslint": "^5.16.0",
33
+ "@oclif/plugin-help": "^5.1.12",
34
+ "@oclif/test": "^1.2.8",
35
+ "@types/chai": "^4.2.18",
36
+ "@types/inquirer": "^7.3.1",
37
+ "@types/mkdirp": "^1.0.1",
38
+ "@types/mocha": "^8.2.2",
39
+ "@types/node": "^14.14.32",
40
+ "@types/sinon": "^10.0.2",
41
+ "@types/tar": "^4.0.3",
42
+ "@types/winston": "^2.4.4",
43
+ "chai": "^4.3.4",
44
+ "eslint": "^8.18.0",
23
45
  "eslint-config-oclif": "^3.1.0",
46
+ "eslint-config-oclif-typescript": "^0.1.0",
24
47
  "globby": "^10.0.2",
25
- "mocha": "^8.0.1",
26
- "nyc": "^14.1.1",
27
- "sinon": "^9.1.0"
48
+ "mocha": "^9.2.2",
49
+ "nyc": "^15.1.0",
50
+ "rimraf": "^2.7.1",
51
+ "sinon": "^11.1.1",
52
+ "tmp": "^0.2.1",
53
+ "ts-node": "^8.10.2",
54
+ "typescript": "^4.7.4"
28
55
  },
29
56
  "engines": {
30
57
  "node": ">=8.0.0"
31
58
  },
32
59
  "files": [
60
+ "/lib",
33
61
  "/npm-shrinkwrap.json",
34
- "/oclif.manifest.json",
35
- "/src",
36
- "/messages"
62
+ "/oclif.manifest.json"
37
63
  ],
38
64
  "homepage": "https://github.com/contentstack/cli",
39
65
  "keywords": [
40
- "contentstack","cli", "plugin"
66
+ "contentstack",
67
+ "cli",
68
+ "plugin"
41
69
  ],
42
70
  "license": "MIT",
43
71
  "oclif": {
44
- "commands": "./src/commands",
72
+ "commands": "./lib/commands",
45
73
  "bin": "csdx",
46
74
  "devPlugins": [
47
75
  "@oclif/plugin-help"
48
- ],
49
- "repositoryPrefix": "<%- repo %>/blob/v<%- version %>/packages/auth/<%- commandPath %>"
76
+ ]
50
77
  },
51
- "repository": "https://github.com/contentstack/cli",
52
- "scripts": {
53
- "pack": "npm pack && mv *.tgz ../../build/",
54
- "postpack": "rm -f oclif.manifest.json",
55
- "posttest": "npx eslint .",
56
- "prepack": "oclif-dev manifest && oclif-dev readme",
57
- "test": "nyc mocha \"test/**/*.test.js\"",
58
- "test-report": "nyc --reporter=html mocha \"test/**/*.test.js\"",
59
- "version": "oclif-dev readme && git add README.md"
60
- }
61
- }
78
+ "husky": {
79
+ "hooks": {
80
+ "pre-commit": "npm run lint"
81
+ }
82
+ },
83
+ "repository": "contentstack/cli"
84
+ }
@@ -1,43 +0,0 @@
1
- {
2
- "login": {
3
- "msgLoginSuccess": "Contentstack account authenticated successfully!",
4
- "promptEmailAddress": "Enter your email address",
5
- "promptPassword": "Enter your password",
6
- "errorAuthFailure": "Failed to authenticate: %s",
7
- "commandDescription": "Login to Contentstack and save the session for further use",
8
- "flagUsernameDescription": "Email address of your Contentstack account"
9
- },
10
- "add": {
11
- "msgAddTokenSuccess": "\"%s\" token added successfully!",
12
- "msgReplacedTokenSuccess": "\"%s\" token replaced successfully!",
13
- "promptTokenAlias": "Provide alias to store token",
14
- "promptEnv": "Provide an environment for delivery token",
15
- "promptToken": "Paste your %s token",
16
- "promptAPIKey": "Paste your stack API Key",
17
- "promptConfirmReplaceToken": "Alias with \"%s\" is already exists, do you want to replace?",
18
- "commandDescription": "Adds management/delivery tokens to your session to use it with further CLI command",
19
- "flagAliasDesc": "Alias to the token for referring it with other commands.",
20
- "apiAliasDesc": "Stack API key for the token you are going to store",
21
- "flagForceDescription": "Exclude confirmation to replace existing alias",
22
- "flagAPIKeyDescription": "Stack API key for the token",
23
- "flagTypeDescription": "Type of token adding, delivery/management or d/m",
24
- "flagTokenDescription": "Sets token. Can be set via environment variable 'TOKEN'. We recommend to use env variable"
25
- },
26
- "remove": {
27
- "msgAliasNotFound": "No token found with alias %s. Select from following list.",
28
- "errorNoTokensAdded": "No tokens are added.",
29
- "msgRemoveTokenSuccess": "\"%s\" token removed successfully!",
30
- "commandDescription": "Removes stored tokens",
31
- "flagAliasDescription": "Alias (name) of the token to remove",
32
- "flagIgnoreDescription": "Ignores if token not present. Command shows show list of available aliases with multi select option to delete tokens from that list."
33
- },
34
- "logout": {
35
- "promptConfirmLogout": "Are you sure you want to log out? (Y/N)",
36
- "msgLoggingOut": "Logging out from Contentstack...",
37
- "msgLogOutSuccess": "You have logged out from Contentstack successfully!",
38
- "errorFailedLogout": "Failed to logout due to following error: ",
39
- "errFailedLogoutUnkwn": "Failed to logout due to unknown error",
40
- "commandDesc": "Log out from Contentstack and clear the session",
41
- "flagForceDesc": "Exclude confirmation to logout"
42
- }
43
- }
@@ -1,50 +0,0 @@
1
- const chalk = require('chalk')
2
- const {Command, flags} = require('@contentstack/cli-command')
3
- const {cli} = require('cli-ux')
4
- const {AuthHandler} = require('../../util/auth-handler')
5
- const Configstore = require('configstore')
6
- const config = new Configstore('contentstack_cli')
7
- const Messages = require('../../util/messages')
8
- const messages = new Messages('login').msgs
9
- const debug = require('debug')('csdx:auth:login')
10
-
11
- class LoginCommand extends Command {
12
- async run() {
13
- const opts = {
14
- contentstackClient: this.managementAPIClient, // get client added in 'this' context via cli plugin init hook
15
- }
16
-
17
- const authHandler = new AuthHandler(opts)
18
- const {flags} = this.parse(LoginCommand)
19
- let username = flags.username ? flags.username : await cli.prompt(messages.promptEmailAddress)
20
-
21
- const password = await cli.prompt(messages.promptPassword, {type: 'hide'})
22
- try {
23
- const user = await authHandler.login(username, password)
24
- debug('User object ', user)
25
- config.set('authtoken', user.authtoken)
26
- config.set('email', user.email)
27
- cli.log(chalk.green(messages.msgLoginSuccess))
28
- } catch (error) {
29
- debug('Error occurred: ', error)
30
- if (error.message) {
31
- try {
32
- let res = JSON.parse(error.message)
33
- cli.log(chalk.red(res.errorMessage))
34
- } catch (e) {
35
- cli.log(chalk.red(error.message))
36
- }
37
- }
38
- }
39
- }
40
- }
41
-
42
- LoginCommand.description = messages.commandDescription
43
-
44
- LoginCommand.flags = {
45
- username: flags.string({char: 'u', description: messages.flagUsernameDescription}),
46
- }
47
-
48
- LoginCommand.aliases = ['login']
49
-
50
- module.exports = LoginCommand
@@ -1,44 +0,0 @@
1
- const {Command, flags} = require('@contentstack/cli-command')
2
- const {cli} = require('cli-ux')
3
- const chalk = require('chalk')
4
- const {AuthHandler} = require('../../util/auth-handler')
5
- const Configstore = require('configstore')
6
- const Messages = require('../../util/messages')
7
- const messages = new Messages('logout').msgs
8
-
9
- class LogoutCommand extends Command {
10
- async run() {
11
- const {flags} = this.parse(LogoutCommand)
12
- let confirm = false
13
- confirm = flags.force ? true : await cli.confirm(messages.promptConfirmLogout)
14
- const opts = {
15
- contentstackClient: this.managementAPIClient,
16
- }
17
- const authHandler = new AuthHandler(opts)
18
- const config = new Configstore('contentstack_cli')
19
- try {
20
- if (confirm) {
21
- cli.log(messages.msgLoggingOut)
22
- let authtoken = this.authToken
23
- await authHandler.logout(authtoken)
24
- config.delete('authtoken')
25
- config.delete('email')
26
- cli.log(chalk.green(messages.msgLogOutSuccess))
27
- }
28
- } catch (error) {
29
- config.delete('authtoken')
30
- config.delete('email')
31
- cli.log(chalk.green(messages.msgLogOutSuccess))
32
- }
33
- }
34
- }
35
-
36
- LogoutCommand.description = messages.commandDesc
37
-
38
- LogoutCommand.flags = {
39
- force: flags.boolean({char: 'f', description: messages.flagForceDesc}),
40
- }
41
-
42
- LogoutCommand.aliases = ['logout']
43
-
44
- module.exports = LogoutCommand