Skip to content

Commit 4561be4

Browse files
authored
Merge pull request #735 from contentstack/fix/cs-37794
Fix/cs 37794
2 parents 1977ce0 + 4ba68c8 commit 4561be4

9 files changed

Lines changed: 91 additions & 68 deletions

File tree

packages/contentstack-auth/README.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ $ npm install -g @contentstack/cli-auth
1818
$ csdx COMMAND
1919
running command...
2020
$ csdx (--version)
21-
@contentstack/cli-auth/1.3.1 darwin-arm64 node-v18.15.0
21+
@contentstack/cli-auth/1.3.1 darwin-x64 node-v18.12.1
2222
$ csdx --help [COMMAND]
2323
USAGE
2424
$ csdx COMMAND
@@ -46,11 +46,12 @@ User sessions login
4646

4747
```
4848
USAGE
49-
$ csdx auth:login [-u <value> | ] [-p <value> | ]
49+
$ csdx auth:login [-u <value> | --oauth] [-p <value> | ]
5050
5151
FLAGS
5252
-p, --password=<value> Password
5353
-u, --username=<value> User name
54+
--oauth Enables single sign-on (SSO) in Contentstack CLI
5455
5556
DESCRIPTION
5657
User sessions login
@@ -226,11 +227,12 @@ User sessions login
226227

227228
```
228229
USAGE
229-
$ csdx login [-u <value> | ] [-p <value> | ]
230+
$ csdx login [-u <value> | --oauth] [-p <value> | ]
230231
231232
FLAGS
232233
-p, --password=<value> Password
233234
-u, --username=<value> User name
235+
--oauth Enables single sign-on (SSO) in Contentstack CLI
234236
235237
DESCRIPTION
236238
User sessions login

packages/contentstack-auth/src/commands/auth/logout.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import {
77
flags,
88
authHandler as oauthHandler,
99
managementSDKClient,
10-
isAuthenticated,
1110
} from '@contentstack/cli-utilities';
1211

1312
import { authHandler } from '../../utils';
@@ -50,14 +49,19 @@ export default class LogoutCommand extends Command {
5049
try {
5150
const managementAPIClient = await managementSDKClient({ host: this.cmaHost, skipTokenValidity: true });
5251
authHandler.client = managementAPIClient;
53-
if (isAuthenticated()) {
52+
if ((await oauthHandler.isAuthenticated()) && (await oauthHandler.isAuthorisationTypeBasic())) {
5453
if (confirm === true) {
5554
cliux.loader('CLI_AUTH_LOGOUT_LOADER_START');
5655
await authHandler.logout(configHandler.get('authtoken'));
5756
cliux.loader('');
5857
logger.info('successfully logged out');
5958
cliux.success('CLI_AUTH_LOGOUT_SUCCESS');
6059
}
60+
} else {
61+
cliux.loader('CLI_AUTH_LOGOUT_LOADER_START');
62+
cliux.loader('');
63+
logger.info('successfully logged out');
64+
cliux.success('CLI_AUTH_LOGOUT_SUCCESS');
6165
}
6266
} catch (error) {
6367
let errorMessage = '';

packages/contentstack-import/src/lib/import/content-types.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ class ContentTypesImport {
127127
try {
128128
await this.stackAPIClient.contentType().create(requestObject.json);
129129
} catch (error) {
130-
if (error.error_code === 115 && (error.errors.uid || error.errors.title)) {
130+
if (error.errorCode === 115 && (error.errors.uid || error.errors.title)) {
131131
// content type uid already exists
132132
// _.remove(self.contentTypes, { uid: uid });
133133
return true;

packages/contentstack-import/src/lib/import/entries.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,7 @@ module.exports = class ImportEntries {
10071007
addlogs(this.config, 'field_rules is not available', 'error');
10081008
}
10091009

1010-
self.stackAPIClient
1010+
this.stackAPIClient
10111011
.contentType(schema.uid)
10121012
.fetch()
10131013
.then((contentTypeResponse) => {

packages/contentstack-migration/src/commands/cm/stacks/migration.js

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ class MigrationCommand extends Command {
8181
set('config', mapInstance, configObj);
8282
}
8383

84-
const APIClient = await managementSDKClient({ host: this.cmaHost })
84+
const APIClient = await managementSDKClient({ host: this.cmaHost });
8585
let stackSDKInstance;
8686
if (branch) {
8787
set(BRANCH, mapInstance, branch);
@@ -235,13 +235,11 @@ MigrationCommand.flags = {
235235
'stack-api-key': flags.string({
236236
char: 'k',
237237
description: 'With this flag add the API key of your stack.',
238-
dependsOn: ['authtoken'],
239238
exclusive: ['alias'],
240239
}),
241240
alias: flags.string({
242241
char: 'a',
243242
description: 'Use this flag to add the management token alias.',
244-
exclusive: ['authtoken'],
245243
}),
246244
'file-path': flags.string({
247245
description: 'Use this flag to provide the path of the file of the migration script provided by the user.',
@@ -258,7 +256,6 @@ MigrationCommand.flags = {
258256
description: '[optional] inline configuration, <key1>:<value1>',
259257
multiple: true,
260258
}),
261-
262259
multiple: flags.boolean({
263260
description: 'This flag helps you to migrate multiple content files in a single instance.',
264261
}),

packages/contentstack-utilities/src/auth-handler.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,10 +119,16 @@ class AuthHandler {
119119
if (queryObject.code) {
120120
cliux.print('Auth code successfully fetched.');
121121
this.getAccessToken(queryObject.code)
122-
.then(() => {
122+
.then(async () => {
123+
await this.setOAuthBaseURL();
123124
cliux.print('Access token fetched using auth code successfully.');
125+
cliux.print(
126+
`You can review the access permissions on the page - ${this.OAuthBaseURL}/#!/marketplace/authorized-apps`,
127+
);
124128
res.writeHead(200, { 'Content-Type': 'text/html' });
125-
res.end(`<h1>Successfully authorized!</h1><h2>You can close this window now.</h2>`);
129+
res.end(
130+
`<h1>Successfully authorized!</h1><h2>You can close this window now.</h2><p>You can review the access permissions on - <a href="${this.OAuthBaseURL}/#!/marketplace/authorized-apps" target="_blank">Authorized Apps page</a></p>`,
131+
);
126132
stopServer();
127133
})
128134
.catch((error) => {
@@ -378,6 +384,18 @@ class AuthHandler {
378384
);
379385
}
380386

387+
async getAuthorisationType(): Promise<any> {
388+
return configHandler.get(this.authorisationTypeKeyName) ? configHandler.get(this.authorisationTypeKeyName) : false;
389+
}
390+
391+
async isAuthorisationTypeBasic(): Promise<boolean> {
392+
return configHandler.get(this.authorisationTypeKeyName) === this.authorisationTypeAUTHValue ? true : false;
393+
}
394+
395+
async isAuthorisationTypeOAuth(): Promise<boolean> {
396+
return configHandler.get(this.authorisationTypeKeyName) === this.authorisationTypeOAUTHValue ? true : false;
397+
}
398+
381399
checkExpiryAndRefresh = (force: boolean = false) => this.compareOAuthExpiry(force);
382400

383401
async compareOAuthExpiry(force: boolean = false) {

packages/contentstack-utilities/src/config-handler.ts

Lines changed: 50 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import { v4 as uuid } from 'uuid';
33
import { existsSync, unlinkSync, readFileSync } from 'fs';
44

55
const ENC_KEY = process.env.ENC_KEY || 'encryptionKey';
6-
const ENCRYPT_CONF: boolean = process.env.ENCRYPT_CONF === 'true' || false;
6+
const ENCRYPT_CONF: boolean = process.env.ENCRYPT_CONF === 'true' || true;
77
const CONFIG_NAME = process.env.CONFIG_NAME || 'contentstack_cli';
88
const ENC_CONFIG_NAME = process.env.ENC_CONFIG_NAME || 'contentstack_cli_obfuscate';
9-
const OLD_CONFIG_BACKUP_FLAG = 'isOldConfigBackup'
9+
const OLD_CONFIG_BACKUP_FLAG = 'isOldConfigBackup';
1010

1111
const xdgBasedir = require('xdg-basedir');
1212
const path = require('path');
@@ -20,50 +20,47 @@ class Config {
2020
private config: Conf;
2121

2222
constructor() {
23-
this.init()
24-
this.importOldConfig()
23+
this.init();
24+
this.importOldConfig();
2525
}
2626

2727
init() {
28-
return ENCRYPT_CONF === true
29-
? this.getEncryptedConfig()
30-
: this.getDecryptedConfig()
31-
28+
return ENCRYPT_CONF === true ? this.getEncryptedConfig() : this.getDecryptedConfig();
3229
}
3330

3431
importOldConfig() {
3532
if (!this.get(OLD_CONFIG_BACKUP_FLAG)) {
3633
try {
37-
const oldConfigStoreData = this.getOldConfig()
34+
const oldConfigStoreData = this.getOldConfig();
3835
if (oldConfigStoreData) {
39-
this.setOldConfigStoreData(oldConfigStoreData, '')
40-
this.removeOldConfigStoreFile()
36+
this.setOldConfigStoreData(oldConfigStoreData, '');
37+
this.removeOldConfigStoreFile();
4138
}
4239
} catch (error) {
43-
console.log("No data to be imported from Old config file");
40+
console.log('No data to be imported from Old config file');
4441
}
4542

46-
this.set(OLD_CONFIG_BACKUP_FLAG, true)
43+
this.set(OLD_CONFIG_BACKUP_FLAG, true);
4744
}
4845
}
4946

5047
// Recursive function to migrate from the old config
5148
setOldConfigStoreData(data, _path = '') {
5249
for (const key in data) {
5350
const value = data[key];
54-
const setPath = _path ? _path + '.' + key : key
51+
const setPath = _path ? _path + '.' + key : key;
5552

56-
if (typeof (value) == "object") {
57-
this.setOldConfigStoreData(value, setPath)
53+
if (typeof value == 'object') {
54+
this.setOldConfigStoreData(value, setPath);
5855
} else {
59-
this.set(setPath, value)
56+
this.set(setPath, value);
6057
}
6158
}
6259
}
6360

6461
removeOldConfigStoreFile() {
6562
if (existsSync(oldConfigPath)) {
66-
unlinkSync(oldConfigPath) // NOTE remove old configstore file
63+
unlinkSync(oldConfigPath); // NOTE remove old configstore file
6764
}
6865
}
6966

@@ -76,103 +73,103 @@ class Config {
7673
}
7774

7875
private fallbackInit(): Conf {
79-
return new Conf({ configName: CONFIG_NAME, encryptionKey: ENC_KEY })
76+
return new Conf({ configName: CONFIG_NAME, encryptionKey: ENC_KEY });
8077
}
8178

8279
private getObfuscationKey() {
83-
const obfuscationKeyName = 'obfuscation_key'
84-
const encConfig = new Conf({ configName: ENC_CONFIG_NAME })
85-
let obfuscationKey: any = encConfig.get(obfuscationKeyName)
80+
const obfuscationKeyName = 'obfuscation_key';
81+
const encConfig = new Conf({ configName: ENC_CONFIG_NAME });
82+
let obfuscationKey: any = encConfig.get(obfuscationKeyName);
8683

8784
if (!obfuscationKey) {
88-
encConfig.set(obfuscationKeyName, uuid())
89-
obfuscationKey = encConfig.get(obfuscationKeyName)
85+
encConfig.set(obfuscationKeyName, uuid());
86+
obfuscationKey = encConfig.get(obfuscationKeyName);
9087
}
9188

92-
return obfuscationKey
89+
return obfuscationKey;
9390
}
9491

9592
private getConfigDataAndUnlinkConfigFile(config: Conf) {
96-
let configData
93+
let configData;
9794

9895
if (config?.path) {
9996
if (existsSync(config.path)) {
100-
configData = JSON.parse(JSON.stringify(config?.store || {})) // NOTE convert prototype object to plain object
101-
unlinkSync(config.path) // NOTE remove old config file
97+
configData = JSON.parse(JSON.stringify(config?.store || {})); // NOTE convert prototype object to plain object
98+
unlinkSync(config.path); // NOTE remove old config file
10299
}
103100
}
104101

105-
return configData
102+
return configData;
106103
}
107104

108105
private getEncryptedConfig(configData?: Record<string, unknown>, skip = false) {
109106
const getEncryptedDataElseFallBack = () => {
110107
try {
111108
// NOTE reading current code base encrypted file if exist
112-
const encryptionKey: any = this.getObfuscationKey()
113-
this.config = new Conf({ configName: CONFIG_NAME, encryptionKey })
109+
const encryptionKey: any = this.getObfuscationKey();
110+
this.config = new Conf({ configName: CONFIG_NAME, encryptionKey });
114111

115112
if (Object.keys(configData || {})?.length) {
116-
this.config.set(configData) // NOTE set config data if passed any
113+
this.config.set(configData); // NOTE set config data if passed any
117114
}
118115
} catch (error) {
119116
// NOTE reading old code base encrypted file if exist
120117
try {
121-
const config = this.fallbackInit()
122-
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config)
123-
this.getEncryptedConfig(oldConfigData, true)
118+
const config = this.fallbackInit();
119+
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config);
120+
this.getEncryptedConfig(oldConfigData, true);
124121
} catch (_error) {
125122
// console.trace(error.message)
126123
}
127124
}
128-
}
125+
};
129126

130127
try {
131128
if (skip === false) {
132-
const config = new Conf({ configName: CONFIG_NAME })
133-
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config)
134-
this.getEncryptedConfig(oldConfigData, true)
129+
const config = new Conf({ configName: CONFIG_NAME });
130+
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config);
131+
this.getEncryptedConfig(oldConfigData, true);
135132
} else {
136-
getEncryptedDataElseFallBack()
133+
getEncryptedDataElseFallBack();
137134
}
138135
} catch (error) {
139136
// console.trace(error.message)
140137
// NOTE reading current code base encrypted file if exist
141-
getEncryptedDataElseFallBack()
138+
getEncryptedDataElseFallBack();
142139
}
143140

144-
return this.config
141+
return this.config;
145142
}
146143

147144
private getDecryptedConfig(configData?: Record<string, unknown>) {
148145
try {
149-
this.config = new Conf({ configName: CONFIG_NAME })
146+
this.config = new Conf({ configName: CONFIG_NAME });
150147

151148
if (Object.keys(configData || {})?.length) {
152-
this.config.set(configData) // NOTE set config data if passed any
149+
this.config.set(configData); // NOTE set config data if passed any
153150
}
154151
} catch (error) {
155152
// console.trace(error.message)
156153

157154
try {
158-
const encryptionKey: any = this.getObfuscationKey()
159-
let config = new Conf({ configName: CONFIG_NAME, encryptionKey })
160-
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config)
161-
this.getDecryptedConfig(oldConfigData) // NOTE NOTE reinitialize the config with old data and new decrypted file
155+
const encryptionKey: any = this.getObfuscationKey();
156+
let config = new Conf({ configName: CONFIG_NAME, encryptionKey });
157+
const oldConfigData = this.getConfigDataAndUnlinkConfigFile(config);
158+
this.getDecryptedConfig(oldConfigData); // NOTE NOTE reinitialize the config with old data and new decrypted file
162159
} catch (_error) {
163160
// console.trace(error.message)
164161

165162
try {
166-
const config = this.fallbackInit()
167-
const _configData = this.getConfigDataAndUnlinkConfigFile(config)
168-
this.getDecryptedConfig(_configData) // NOTE reinitialize the config with old data and new decrypted file
163+
const config = this.fallbackInit();
164+
const _configData = this.getConfigDataAndUnlinkConfigFile(config);
165+
this.getDecryptedConfig(_configData); // NOTE reinitialize the config with old data and new decrypted file
169166
} catch (__error) {
170167
// console.trace(error.message)
171168
}
172169
}
173170
}
174171

175-
return this.config
172+
return this.config;
176173
}
177174

178175
get(key): string | any {
@@ -190,7 +187,7 @@ class Config {
190187
}
191188

192189
clear() {
193-
this.config.clear()
190+
this.config.clear();
194191
}
195192
}
196193

packages/contentstack-utilities/types/auth-handler.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ declare class AuthHandler {
3737
isAuthenticated(): Promise<boolean>;
3838
checkExpiryAndRefresh: (force?: boolean) => Promise<void | object>;
3939
compareOAuthExpiry(force?: boolean): Promise<void | object>;
40+
getAuthorisationType(): Promise<boolean>;
41+
isAuthorisationTypeBasic(): Promise<boolean>;
42+
isAuthorisationTypeOAuth(): Promise<boolean>;
4043
}
4144
declare const _default: AuthHandler;
4245
export default _default;

0 commit comments

Comments
 (0)