Skip to content

Commit 504614a

Browse files
authored
Merge pull request #1965 from contentstack/feat/DX-3078
feat: Integrated Logger and cliErrorHandler in auth plugin
2 parents ad7489b + 9f39fc0 commit 504614a

12 files changed

Lines changed: 87 additions & 76 deletions

File tree

.talismanrc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,10 @@ fileignoreconfig:
144144
checksum: 941c6a8d59ba58e2004030202ee6282cdd2a424cf8b089aef70a85198553fefe
145145
- filename: packages/contentstack-utilities/src/logger/logger.ts
146146
checksum: b56504c1e4fb31b676cc1931eb30afc7b9466f03890fe3c76977309e1fd066a6
147+
- filename: packages/contentstack-auth/src/base-command.ts
148+
checksum: b7b6b94676f8413bf49cbe591b4242eef7936b9b4660b04cf8c8bcd2e96ce0ec
149+
- filename: packages/contentstack-auth/src/commands/auth/tokens/add.ts
150+
checksum: 40f7a6bdfb4c1d5c19d213feffdf9c76eb2fca451567a2fb1cc26338b2163b26
151+
- filename: packages/contentstack-auth/src/utils/tokens-validation.ts
152+
checksum: fd7c4ebb6d6d955647012454357c360a292d122227a0d130b39dfd56c41f7529
147153
version: "1.0"

packages/contentstack-auth/messages/index.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
"CLI_AUTH_LOGOUT_ALREADY": "You're already logged out",
2121
"CLI_AUTH_LOGOUT_NO_AUTHORIZATIONS": "No authorizations found",
2222
"CLI_AUTH_LOGOUT_NO_AUTHORIZATIONS_USER": "No authorizations found for current user",
23-
"CLI_AUTH_WHOAMI_LOGGED_IN_AS": "You are currently logged in with email",
23+
"CLI_AUTH_WHOAMI_LOGGED_IN_AS": "You are currently logged in with email '%s'",
2424
"CLI_AUTH_WHOAMI_FAILED": "Failed to get the current user details",
2525
"CLI_AUTH_WHOAMI_DESCRIPTION": "Display current users email address",
2626
"CLI_AUTH_TOKENS_ADD_ASK_TOKEN_ALIAS": "Provide alias to store token",

packages/contentstack-auth/src/base-command.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Command } from '@contentstack/cli-command';
2-
import { FlagInput, Flags, Interfaces, LoggerService } from '@contentstack/cli-utilities';
2+
import { configHandler, FlagInput, Flags, Interfaces, LoggerService } from '@contentstack/cli-utilities';
3+
import { Context } from './interfaces';
34

45
export type Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>;
56
export type Flags<T extends typeof Command> = Interfaces.InferredFlags<(typeof BaseCommand)['baseFlags'] & T['flags']>;
@@ -8,7 +9,7 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
89
public logger!: LoggerService;
910
protected args!: Args<T>;
1011
protected flags!: Flags<T>;
11-
12+
public contextDetails!: Context;
1213

1314
/**
1415
* The `init` function initializes the command by parsing arguments and flags, registering search
@@ -18,6 +19,7 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
1819
await super.init();
1920
// Init logger
2021
this.logger = new LoggerService(process.cwd(), 'cli-log');
22+
this.contextDetails = this.createExportContext();
2123
}
2224

2325
/**
@@ -45,4 +47,18 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
4547
// called after run and catch regardless of whether or not the command errored
4648
return super.finally(_);
4749
}
48-
}
50+
51+
// Create export context object
52+
protected createExportContext(apiKey?: string): Context {
53+
return {
54+
command: this.context.info.command,
55+
module: '',
56+
userId: configHandler.get('userId'),
57+
email: configHandler.get('email'),
58+
sessionId: this.context.sessionId,
59+
clientId: this.context.clientId,
60+
apiKey: apiKey || '',
61+
orgId: configHandler.get('organization_uid') || '',
62+
};
63+
}
64+
}

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

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
import { Command } from '@contentstack/cli-command';
21
import {
32
cliux,
43
CLIError,
54
authHandler as oauthHandler,
65
flags,
76
managementSDKClient,
87
FlagInput,
9-
formatError
8+
log,
9+
handleAndLogError,
10+
messageHandler
1011
} from '@contentstack/cli-utilities';
1112
import { User } from '../../interfaces';
1213
import { authHandler, interactive } from '../../utils';
@@ -61,17 +62,12 @@ export default class LoginCommand extends BaseCommand<typeof LoginCommand> {
6162
} else {
6263
const username = loginFlags?.username || (await interactive.askUsername());
6364
const password = loginFlags?.password || (await interactive.askPassword());
64-
this.logger.debug('username', username);
65+
log.debug('login flags', loginFlags);
6566
await this.login(username, password);
6667
}
6768
} catch (error) {
68-
let errorMessage = formatError(error) || 'Something went wrong while logging. Please try again.';
69-
if (typeof errorMessage === 'object' && Object.keys(errorMessage)?.length === 0) {
70-
console.log(error);
71-
}
72-
this.logger.error('login failed', errorMessage);
7369
cliux.error('CLI_AUTH_LOGIN_FAILED');
74-
cliux.error(errorMessage);
70+
handleAndLogError(error, {...this.contextDetails})
7571
process.exit();
7672
}
7773
}
@@ -83,8 +79,7 @@ export default class LoginCommand extends BaseCommand<typeof LoginCommand> {
8379
throw new CLIError('Failed to login - invalid response');
8480
}
8581
await oauthHandler.setConfigData('basicAuth', user);
86-
this.logger.info('successfully logged in');
87-
cliux.success('CLI_AUTH_LOGIN_SUCCESS');
82+
log.success(messageHandler.parse('CLI_AUTH_LOGIN_SUCCESS'), this.contextDetails);
8883
} catch (error) {
8984
throw error;
9085
}

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

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { Command } from '@contentstack/cli-command';
21
import {
32
cliux,
43
configHandler,
@@ -7,7 +6,9 @@ import {
76
authHandler as oauthHandler,
87
managementSDKClient,
98
FlagInput,
10-
formatError,
9+
log,
10+
handleAndLogError,
11+
messageHandler
1112
} from '@contentstack/cli-utilities';
1213

1314
import { authHandler } from '../../utils';
@@ -50,25 +51,21 @@ export default class LogoutCommand extends BaseCommand<typeof LogoutCommand> {
5051
try {
5152
const managementAPIClient = await managementSDKClient({ host: this.cmaHost, skipTokenValidity: true });
5253
authHandler.client = managementAPIClient;
53-
if (confirm === true && (await oauthHandler.isAuthenticated())) {
54+
if (confirm === true && (oauthHandler.isAuthenticated())) {
5455
cliux.loader('CLI_AUTH_LOGOUT_LOADER_START');
5556
if (await oauthHandler.isAuthorisationTypeBasic()) {
5657
await authHandler.logout(configHandler.get('authtoken'));
5758
} else if (await oauthHandler.isAuthorisationTypeOAuth()) {
5859
await oauthHandler.oauthLogout();
5960
}
6061
cliux.loader('');
61-
this.logger.info('successfully logged out');
62-
cliux.success('CLI_AUTH_LOGOUT_SUCCESS');
62+
log.success(messageHandler.parse('CLI_AUTH_LOGOUT_SUCCESS'), this.contextDetails);
6363
} else {
64-
cliux.success('CLI_AUTH_LOGOUT_ALREADY');
64+
log.success(messageHandler.parse('CLI_AUTH_LOGOUT_ALREADY'), this.contextDetails);
6565
}
6666
} catch (error) {
67-
let errorMessage = formatError(error) || 'Something went wrong while logging out. Please try again.';
68-
69-
this.logger.error('Logout failed', errorMessage);
7067
cliux.print('CLI_AUTH_LOGOUT_FAILED', { color: 'yellow' });
71-
cliux.print(errorMessage, { color: 'red' });
68+
handleAndLogError(error, { ...this.contextDetails });
7269
} finally {
7370
if (confirm === true) {
7471
await oauthHandler.setConfigData('logout');

packages/contentstack-auth/src/commands/auth/tokens/add.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { Command } from '@contentstack/cli-command';
21
import {
32
cliux,
43
configHandler,
@@ -8,10 +7,12 @@ import {
87
HttpClient,
98
messageHandler,
109
Flags,
11-
formatError,
10+
log,
11+
handleAndLogError,
1212
} from '@contentstack/cli-utilities';
13-
import { askTokenType } from '../../../utils/interactive';
1413
import { BaseCommand } from '../../../base-command';
14+
import { askTokenType } from '../../../utils/interactive';
15+
1516
export default class TokensAddCommand extends BaseCommand<typeof TokensAddCommand> {
1617
static description = 'Adds management/delivery tokens to your session to use it with other CLI commands';
1718

@@ -100,7 +101,7 @@ export default class TokensAddCommand extends BaseCommand<typeof TokensAddComman
100101

101102
const type = isDelivery || Boolean(environment) ? 'delivery' : 'management';
102103

103-
this.logger.info(`adding ${type} token`);
104+
log.info(`Adding ${type} token with alias: ${alias}, apiKey: ${apiKey}, environment: ${environment}`);
104105

105106
try {
106107
if (!alias) {
@@ -114,7 +115,7 @@ export default class TokensAddCommand extends BaseCommand<typeof TokensAddComman
114115
name: 'confirm',
115116
});
116117
if (!shouldAliasReplace) {
117-
this.logger.info('Exiting from the process of replacing the token');
118+
log.info('Exiting from the process of replacing the token');
118119
cliux.print('CLI_AUTH_EXIT_PROCESS');
119120
return;
120121
}
@@ -160,10 +161,8 @@ export default class TokensAddCommand extends BaseCommand<typeof TokensAddComman
160161
cliux.success('CLI_AUTH_TOKENS_ADD_SUCCESS');
161162
}
162163
} catch (error) {
163-
let errorMessage = formatError(error) || 'Something went wrong while adding token. Please try again.';
164-
this.logger.error('token add error', errorMessage);
165164
cliux.print('CLI_AUTH_TOKENS_ADD_FAILED', { color: 'yellow' });
166-
cliux.error(errorMessage);
165+
handleAndLogError(error, {...this.contextDetails});
167166
}
168167
}
169168
}

packages/contentstack-auth/src/commands/auth/tokens/index.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1-
import { Command } from '@contentstack/cli-command';
2-
import { cliux, configHandler, formatError, CLITable, TableFlags, FlagInput } from '@contentstack/cli-utilities';
1+
import {
2+
cliux,
3+
configHandler,
4+
CLITable,
5+
TableFlags,
6+
FlagInput,
7+
handleAndLogError,
8+
} from '@contentstack/cli-utilities';
39
import { BaseCommand } from '../../../base-command';
410
export default class TokensListCommand extends BaseCommand<typeof TokensListCommand> {
511
static aliases = ['tokens'];
@@ -55,10 +61,8 @@ export default class TokensListCommand extends BaseCommand<typeof TokensListComm
5561
cliux.print('CLI_AUTH_TOKENS_LIST_NO_TOKENS');
5662
}
5763
} catch (error) {
58-
let errorMessage = formatError(error) || 'Something went wrong while fetching tokens. Please try again.';
59-
this.logger.error('Token list error', errorMessage);
6064
cliux.print('CLI_AUTH_TOKENS_LIST_FAILED', { color: 'yellow' });
61-
cliux.print(errorMessage, { color: 'red' });
65+
handleAndLogError(error, { ...this.contextDetails });
6266
}
6367
}
6468
}

packages/contentstack-auth/src/commands/auth/tokens/remove.ts

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { Command } from '@contentstack/cli-command';
2-
import { cliux, configHandler, flags, FlagInput, formatError } from '@contentstack/cli-utilities';
1+
import { cliux, configHandler, flags, FlagInput, log, handleAndLogError } from '@contentstack/cli-utilities';
32
import { BaseCommand } from '../../../base-command';
43

54
export default class TokensRemoveCommand extends BaseCommand<typeof TokensRemoveCommand> {
@@ -14,7 +13,6 @@ export default class TokensRemoveCommand extends BaseCommand<typeof TokensRemove
1413
const { flags: removeTokenFlags } = await this.parse(TokensRemoveCommand);
1514
const alias = removeTokenFlags.alias;
1615
const ignore = removeTokenFlags.ignore;
17-
1816
try {
1917
const token = configHandler.get(`tokens.${alias}`);
2018
const tokens = configHandler.get('tokens');
@@ -48,20 +46,18 @@ export default class TokensRemoveCommand extends BaseCommand<typeof TokensRemove
4846
}
4947

5048
selectedTokens.forEach((ele)=>{
51-
this.logger.info('selected tokens',ele);
49+
log.info(`Selected token: ${ele}`, this.contextDetails);
5250
})
5351

5452
selectedTokens.forEach((element) => {
5553
const selectedToken = element.split(':')[0];
5654
configHandler.delete(`tokens.${selectedToken}`);
5755
cliux.success('CLI_AUTH_TOKENS_REMOVE_SUCCESS');
58-
this.logger.info('Token removed successfully !!', element);
56+
log.info(`Token removed: ${selectedToken}`, this.contextDetails);
5957
});
6058
} catch (error) {
61-
let errorMessage = formatError(error) || 'Something went wrong while removing token. Please try again.';
62-
this.logger.error('Token remove error', errorMessage);
6359
cliux.print('CLI_AUTH_TOKENS_REMOVE_FAILED', { color: 'yellow' });
64-
cliux.print(errorMessage, { color: 'red' });
60+
handleAndLogError(error, {...this.contextDetails} )
6561
}
6662
}
6763
}
Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { Command } from '@contentstack/cli-command';
2-
import { cliux, formatError } from '@contentstack/cli-utilities';
1+
import { cliux, log, handleAndLogError, messageHandler } from '@contentstack/cli-utilities';
32
import { BaseCommand } from '../../base-command';
43

54
export default class WhoamiCommand extends BaseCommand<typeof WhoamiCommand> {
@@ -14,15 +13,13 @@ export default class WhoamiCommand extends BaseCommand<typeof WhoamiCommand> {
1413
if (this.email) {
1514
cliux.print('CLI_AUTH_WHOAMI_LOGGED_IN_AS', { color: 'white' });
1615
cliux.print(this.email, { color: 'green' });
17-
this.logger.info('Currently logged in user', this.email);
16+
log.info(messageHandler.parse('CLI_AUTH_WHOAMI_LOGGED_IN_AS', this.email), this.contextDetails);
1817
} else {
19-
cliux.error('CLI_AUTH_WHOAMI_FAILED');
18+
log.error(messageHandler.parse('CLI_AUTH_WHOAMI_FAILED'), this.contextDetails);
2019
}
2120
} catch (error) {
22-
let errorMessage = formatError(error) || 'Something went wrong. Please try again.';
23-
this.logger.error('whoami error', errorMessage);
2421
cliux.print('CLI_AUTH_WHOAMI_FAILED', { color: 'yellow' });
25-
cliux.print(errorMessage, { color: 'red' });
22+
handleAndLogError(error, { ...this.contextDetails });
2623
}
2724
}
2825
}

packages/contentstack-auth/src/interfaces/index.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,14 @@ export interface User {
2323
email: string;
2424
authtoken: string;
2525
}
26+
27+
export interface Context {
28+
command: string;
29+
module: string;
30+
userId: string | undefined;
31+
email: string | undefined;
32+
sessionId: string | undefined;
33+
clientId: string | undefined;
34+
apiKey: string;
35+
orgId: string;
36+
}

0 commit comments

Comments
 (0)