Skip to content

feat: Integrated Logger and cliErrorHandler in auth plugin #1965

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/contentstack-auth/messages/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"CLI_AUTH_LOGOUT_ALREADY": "You're already logged out",
"CLI_AUTH_LOGOUT_NO_AUTHORIZATIONS": "No authorizations found",
"CLI_AUTH_LOGOUT_NO_AUTHORIZATIONS_USER": "No authorizations found for current user",
"CLI_AUTH_WHOAMI_LOGGED_IN_AS": "You are currently logged in with email",
"CLI_AUTH_WHOAMI_LOGGED_IN_AS": "You are currently logged in with email '%s'",
"CLI_AUTH_WHOAMI_FAILED": "Failed to get the current user details",
"CLI_AUTH_WHOAMI_DESCRIPTION": "Display current users email address",
"CLI_AUTH_TOKENS_ADD_ASK_TOKEN_ALIAS": "Provide alias to store token",
Expand Down
22 changes: 19 additions & 3 deletions packages/contentstack-auth/src/base-command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Command } from '@contentstack/cli-command';
import { FlagInput, Flags, Interfaces, LoggerService } from '@contentstack/cli-utilities';
import { configHandler, FlagInput, Flags, Interfaces, LoggerService } from '@contentstack/cli-utilities';
import { Context } from './interfaces';

export type Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>;
export type Flags<T extends typeof Command> = Interfaces.InferredFlags<(typeof BaseCommand)['baseFlags'] & T['flags']>;
Expand All @@ -8,7 +9,7 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
public logger!: LoggerService;
protected args!: Args<T>;
protected flags!: Flags<T>;

public contextDetails!: Context;

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

/**
Expand Down Expand Up @@ -45,4 +47,18 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
// called after run and catch regardless of whether or not the command errored
return super.finally(_);
}
}

// Create export context object
protected createExportContext(apiKey?: string): Context {
return {
command: this.context.info.command,
module: '',
userId: configHandler.get('userId'),
email: configHandler.get('email'),
sessionId: this.context.sessionId,
clientId: this.context.clientId,
apiKey: apiKey || '',
orgId: configHandler.get('organization_uid') || '',
};
}
}
17 changes: 6 additions & 11 deletions packages/contentstack-auth/src/commands/auth/login.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Command } from '@contentstack/cli-command';
import {
cliux,
CLIError,
authHandler as oauthHandler,
flags,
managementSDKClient,
FlagInput,
formatError
log,
handleAndLogError,
messageHandler
} from '@contentstack/cli-utilities';
import { User } from '../../interfaces';
import { authHandler, interactive } from '../../utils';
Expand Down Expand Up @@ -61,17 +62,12 @@ export default class LoginCommand extends BaseCommand<typeof LoginCommand> {
} else {
const username = loginFlags?.username || (await interactive.askUsername());
const password = loginFlags?.password || (await interactive.askPassword());
this.logger.debug('username', username);
log.debug('login flags', loginFlags);
await this.login(username, password);
}
} catch (error) {
let errorMessage = formatError(error) || 'Something went wrong while logging. Please try again.';
if (typeof errorMessage === 'object' && Object.keys(errorMessage)?.length === 0) {
console.log(error);
}
this.logger.error('login failed', errorMessage);
cliux.error('CLI_AUTH_LOGIN_FAILED');
cliux.error(errorMessage);
handleAndLogError(error, {...this.contextDetails})
process.exit();
}
}
Expand All @@ -83,8 +79,7 @@ export default class LoginCommand extends BaseCommand<typeof LoginCommand> {
throw new CLIError('Failed to login - invalid response');
}
await oauthHandler.setConfigData('basicAuth', user);
this.logger.info('successfully logged in');
cliux.success('CLI_AUTH_LOGIN_SUCCESS');
log.success(messageHandler.parse('CLI_AUTH_LOGIN_SUCCESS'), this.contextDetails);
} catch (error) {
throw error;
}
Expand Down
17 changes: 7 additions & 10 deletions packages/contentstack-auth/src/commands/auth/logout.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Command } from '@contentstack/cli-command';
import {
cliux,
configHandler,
Expand All @@ -7,7 +6,9 @@ import {
authHandler as oauthHandler,
managementSDKClient,
FlagInput,
formatError,
log,
handleAndLogError,
messageHandler
} from '@contentstack/cli-utilities';

import { authHandler } from '../../utils';
Expand Down Expand Up @@ -50,25 +51,21 @@ export default class LogoutCommand extends BaseCommand<typeof LogoutCommand> {
try {
const managementAPIClient = await managementSDKClient({ host: this.cmaHost, skipTokenValidity: true });
authHandler.client = managementAPIClient;
if (confirm === true && (await oauthHandler.isAuthenticated())) {
if (confirm === true && (oauthHandler.isAuthenticated())) {
cliux.loader('CLI_AUTH_LOGOUT_LOADER_START');
if (await oauthHandler.isAuthorisationTypeBasic()) {
await authHandler.logout(configHandler.get('authtoken'));
} else if (await oauthHandler.isAuthorisationTypeOAuth()) {
await oauthHandler.oauthLogout();
}
cliux.loader('');
this.logger.info('successfully logged out');
cliux.success('CLI_AUTH_LOGOUT_SUCCESS');
log.success(messageHandler.parse('CLI_AUTH_LOGOUT_SUCCESS'), this.contextDetails);
} else {
cliux.success('CLI_AUTH_LOGOUT_ALREADY');
log.success(messageHandler.parse('CLI_AUTH_LOGOUT_ALREADY'), this.contextDetails);
}
} catch (error) {
let errorMessage = formatError(error) || 'Something went wrong while logging out. Please try again.';

this.logger.error('Logout failed', errorMessage);
cliux.print('CLI_AUTH_LOGOUT_FAILED', { color: 'yellow' });
cliux.print(errorMessage, { color: 'red' });
handleAndLogError(error, { ...this.contextDetails });
} finally {
if (confirm === true) {
await oauthHandler.setConfigData('logout');
Expand Down
15 changes: 7 additions & 8 deletions packages/contentstack-auth/src/commands/auth/tokens/add.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Command } from '@contentstack/cli-command';
import {
cliux,
configHandler,
Expand All @@ -8,10 +7,12 @@ import {
HttpClient,
messageHandler,
Flags,
formatError,
log,
handleAndLogError,
} from '@contentstack/cli-utilities';
import { askTokenType } from '../../../utils/interactive';
import { BaseCommand } from '../../../base-command';
import { askTokenType } from '../../../utils/interactive';

export default class TokensAddCommand extends BaseCommand<typeof TokensAddCommand> {
static description = 'Adds management/delivery tokens to your session to use it with other CLI commands';

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

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

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

try {
if (!alias) {
Expand All @@ -114,7 +115,7 @@ export default class TokensAddCommand extends BaseCommand<typeof TokensAddComman
name: 'confirm',
});
if (!shouldAliasReplace) {
this.logger.info('Exiting from the process of replacing the token');
log.info('Exiting from the process of replacing the token');
cliux.print('CLI_AUTH_EXIT_PROCESS');
return;
}
Expand Down Expand Up @@ -160,10 +161,8 @@ export default class TokensAddCommand extends BaseCommand<typeof TokensAddComman
cliux.success('CLI_AUTH_TOKENS_ADD_SUCCESS');
}
} catch (error) {
let errorMessage = formatError(error) || 'Something went wrong while adding token. Please try again.';
this.logger.error('token add error', errorMessage);
cliux.print('CLI_AUTH_TOKENS_ADD_FAILED', { color: 'yellow' });
cliux.error(errorMessage);
handleAndLogError(error, {...this.contextDetails});
}
}
}
14 changes: 9 additions & 5 deletions packages/contentstack-auth/src/commands/auth/tokens/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { Command } from '@contentstack/cli-command';
import { cliux, configHandler, formatError, CLITable, TableFlags, FlagInput } from '@contentstack/cli-utilities';
import {
cliux,
configHandler,
CLITable,
TableFlags,
FlagInput,
handleAndLogError,
} from '@contentstack/cli-utilities';
import { BaseCommand } from '../../../base-command';
export default class TokensListCommand extends BaseCommand<typeof TokensListCommand> {
static aliases = ['tokens'];
Expand Down Expand Up @@ -55,10 +61,8 @@ export default class TokensListCommand extends BaseCommand<typeof TokensListComm
cliux.print('CLI_AUTH_TOKENS_LIST_NO_TOKENS');
}
} catch (error) {
let errorMessage = formatError(error) || 'Something went wrong while fetching tokens. Please try again.';
this.logger.error('Token list error', errorMessage);
cliux.print('CLI_AUTH_TOKENS_LIST_FAILED', { color: 'yellow' });
cliux.print(errorMessage, { color: 'red' });
handleAndLogError(error, { ...this.contextDetails });
}
}
}
12 changes: 4 additions & 8 deletions packages/contentstack-auth/src/commands/auth/tokens/remove.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Command } from '@contentstack/cli-command';
import { cliux, configHandler, flags, FlagInput, formatError } from '@contentstack/cli-utilities';
import { cliux, configHandler, flags, FlagInput, log, handleAndLogError } from '@contentstack/cli-utilities';
import { BaseCommand } from '../../../base-command';

export default class TokensRemoveCommand extends BaseCommand<typeof TokensRemoveCommand> {
Expand All @@ -14,7 +13,6 @@ export default class TokensRemoveCommand extends BaseCommand<typeof TokensRemove
const { flags: removeTokenFlags } = await this.parse(TokensRemoveCommand);
const alias = removeTokenFlags.alias;
const ignore = removeTokenFlags.ignore;

try {
const token = configHandler.get(`tokens.${alias}`);
const tokens = configHandler.get('tokens');
Expand Down Expand Up @@ -48,20 +46,18 @@ export default class TokensRemoveCommand extends BaseCommand<typeof TokensRemove
}

selectedTokens.forEach((ele)=>{
this.logger.info('selected tokens',ele);
log.info(`Selected token: ${ele}`, this.contextDetails);
})

selectedTokens.forEach((element) => {
const selectedToken = element.split(':')[0];
configHandler.delete(`tokens.${selectedToken}`);
cliux.success('CLI_AUTH_TOKENS_REMOVE_SUCCESS');
this.logger.info('Token removed successfully !!', element);
log.info(`Token removed: ${selectedToken}`, this.contextDetails);
});
} catch (error) {
let errorMessage = formatError(error) || 'Something went wrong while removing token. Please try again.';
this.logger.error('Token remove error', errorMessage);
cliux.print('CLI_AUTH_TOKENS_REMOVE_FAILED', { color: 'yellow' });
cliux.print(errorMessage, { color: 'red' });
handleAndLogError(error, {...this.contextDetails} )
}
}
}
11 changes: 4 additions & 7 deletions packages/contentstack-auth/src/commands/auth/whoami.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Command } from '@contentstack/cli-command';
import { cliux, formatError } from '@contentstack/cli-utilities';
import { cliux, log, handleAndLogError, messageHandler } from '@contentstack/cli-utilities';
import { BaseCommand } from '../../base-command';

export default class WhoamiCommand extends BaseCommand<typeof WhoamiCommand> {
Expand All @@ -14,15 +13,13 @@ export default class WhoamiCommand extends BaseCommand<typeof WhoamiCommand> {
if (this.email) {
cliux.print('CLI_AUTH_WHOAMI_LOGGED_IN_AS', { color: 'white' });
cliux.print(this.email, { color: 'green' });
this.logger.info('Currently logged in user', this.email);
log.info(messageHandler.parse('CLI_AUTH_WHOAMI_LOGGED_IN_AS', this.email), this.contextDetails);
} else {
cliux.error('CLI_AUTH_WHOAMI_FAILED');
log.error(messageHandler.parse('CLI_AUTH_WHOAMI_FAILED'), this.contextDetails);
}
} catch (error) {
let errorMessage = formatError(error) || 'Something went wrong. Please try again.';
this.logger.error('whoami error', errorMessage);
cliux.print('CLI_AUTH_WHOAMI_FAILED', { color: 'yellow' });
cliux.print(errorMessage, { color: 'red' });
handleAndLogError(error, { ...this.contextDetails });
}
}
}
11 changes: 11 additions & 0 deletions packages/contentstack-auth/src/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,14 @@ export interface User {
email: string;
authtoken: string;
}

export interface Context {
command: string;
module: string;
userId: string | undefined;
email: string | undefined;
sessionId: string | undefined;
clientId: string | undefined;
apiKey: string;
orgId: string;
}
Loading
Loading