From 8e3af7de50e117423396dae7dc197bd157c14d5f Mon Sep 17 00:00:00 2001 From: Aman Kumar Date: Wed, 11 Jun 2025 10:40:07 +0530 Subject: [PATCH 1/2] feat: Integrated Logger and cliErrorHanlder in auth plugin --- .../contentstack-auth/messages/index.json | 2 +- .../contentstack-auth/src/base-command.ts | 22 +++++++++++++++--- .../src/commands/auth/login.ts | 17 +++++--------- .../src/commands/auth/logout.ts | 17 ++++++-------- .../src/commands/auth/tokens/add.ts | 15 ++++++------ .../src/commands/auth/tokens/index.ts | 14 +++++++---- .../src/commands/auth/tokens/remove.ts | 12 ++++------ .../src/commands/auth/whoami.ts | 11 ++++----- .../contentstack-auth/src/interfaces/index.ts | 11 +++++++++ .../src/utils/auth-handler.ts | 23 +++++++------------ .../src/utils/tokens-validation.ts | 13 ++++------- 11 files changed, 81 insertions(+), 76 deletions(-) diff --git a/packages/contentstack-auth/messages/index.json b/packages/contentstack-auth/messages/index.json index f4e600e87c..0e9423a2c4 100644 --- a/packages/contentstack-auth/messages/index.json +++ b/packages/contentstack-auth/messages/index.json @@ -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", diff --git a/packages/contentstack-auth/src/base-command.ts b/packages/contentstack-auth/src/base-command.ts index 76188417bb..cf712d4984 100644 --- a/packages/contentstack-auth/src/base-command.ts +++ b/packages/contentstack-auth/src/base-command.ts @@ -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 = Interfaces.InferredArgs; export type Flags = Interfaces.InferredFlags<(typeof BaseCommand)['baseFlags'] & T['flags']>; @@ -8,7 +9,7 @@ export abstract class BaseCommand extends Command { public logger!: LoggerService; protected args!: Args; protected flags!: Flags; - + public contextDetails!: Context; /** * The `init` function initializes the command by parsing arguments and flags, registering search @@ -18,6 +19,7 @@ export abstract class BaseCommand extends Command { await super.init(); // Init logger this.logger = new LoggerService(process.cwd(), 'cli-log'); + this.contextDetails = this.createExportContext(); } /** @@ -45,4 +47,18 @@ export abstract class BaseCommand extends Command { // called after run and catch regardless of whether or not the command errored return super.finally(_); } -} \ No newline at end of file + + // 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') || '', + }; + } +} diff --git a/packages/contentstack-auth/src/commands/auth/login.ts b/packages/contentstack-auth/src/commands/auth/login.ts index aea7a35ed9..43d918d2c6 100644 --- a/packages/contentstack-auth/src/commands/auth/login.ts +++ b/packages/contentstack-auth/src/commands/auth/login.ts @@ -1,4 +1,3 @@ -import { Command } from '@contentstack/cli-command'; import { cliux, CLIError, @@ -6,7 +5,9 @@ import { flags, managementSDKClient, FlagInput, - formatError + log, + handleAndLogError, + messageHandler } from '@contentstack/cli-utilities'; import { User } from '../../interfaces'; import { authHandler, interactive } from '../../utils'; @@ -61,17 +62,12 @@ export default class LoginCommand extends BaseCommand { } 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(); } } @@ -83,8 +79,7 @@ export default class LoginCommand extends BaseCommand { 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; } diff --git a/packages/contentstack-auth/src/commands/auth/logout.ts b/packages/contentstack-auth/src/commands/auth/logout.ts index 7aba5bcfee..f293992ae5 100644 --- a/packages/contentstack-auth/src/commands/auth/logout.ts +++ b/packages/contentstack-auth/src/commands/auth/logout.ts @@ -1,4 +1,3 @@ -import { Command } from '@contentstack/cli-command'; import { cliux, configHandler, @@ -7,7 +6,9 @@ import { authHandler as oauthHandler, managementSDKClient, FlagInput, - formatError, + log, + handleAndLogError, + messageHandler } from '@contentstack/cli-utilities'; import { authHandler } from '../../utils'; @@ -50,7 +51,7 @@ export default class LogoutCommand extends BaseCommand { 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')); @@ -58,17 +59,13 @@ export default class LogoutCommand extends BaseCommand { 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'); diff --git a/packages/contentstack-auth/src/commands/auth/tokens/add.ts b/packages/contentstack-auth/src/commands/auth/tokens/add.ts index 07480aaf09..3c407aad97 100644 --- a/packages/contentstack-auth/src/commands/auth/tokens/add.ts +++ b/packages/contentstack-auth/src/commands/auth/tokens/add.ts @@ -1,4 +1,3 @@ -import { Command } from '@contentstack/cli-command'; import { cliux, configHandler, @@ -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 { static description = 'Adds management/delivery tokens to your session to use it with other CLI commands'; @@ -100,7 +101,7 @@ export default class TokensAddCommand extends BaseCommand { static aliases = ['tokens']; @@ -55,10 +61,8 @@ export default class TokensListCommand extends BaseCommand { @@ -14,7 +13,6 @@ export default class TokensRemoveCommand extends BaseCommand{ - 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} ) } } } diff --git a/packages/contentstack-auth/src/commands/auth/whoami.ts b/packages/contentstack-auth/src/commands/auth/whoami.ts index bb3cd81653..0aa58fa533 100644 --- a/packages/contentstack-auth/src/commands/auth/whoami.ts +++ b/packages/contentstack-auth/src/commands/auth/whoami.ts @@ -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 { @@ -14,15 +13,13 @@ export default class WhoamiCommand extends BaseCommand { 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 }); } } } diff --git a/packages/contentstack-auth/src/interfaces/index.ts b/packages/contentstack-auth/src/interfaces/index.ts index 85b593ca1c..0e6ac65fd5 100644 --- a/packages/contentstack-auth/src/interfaces/index.ts +++ b/packages/contentstack-auth/src/interfaces/index.ts @@ -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; +} \ No newline at end of file diff --git a/packages/contentstack-auth/src/utils/auth-handler.ts b/packages/contentstack-auth/src/utils/auth-handler.ts index 0a8a48215f..7941b2bfe8 100644 --- a/packages/contentstack-auth/src/utils/auth-handler.ts +++ b/packages/contentstack-auth/src/utils/auth-handler.ts @@ -1,7 +1,6 @@ -import { cliux, CLIError } from '@contentstack/cli-utilities'; +import { cliux, CLIError, handleAndLogError, log } from '@contentstack/cli-utilities'; import { User } from '../interfaces'; import { askOTPChannel, askOTP } from './interactive'; -import { LoggerService } from '@contentstack/cli-utilities'; /** * @class @@ -10,7 +9,6 @@ import { LoggerService } from '@contentstack/cli-utilities'; class AuthHandler { private _client; private _host; - public logger!: LoggerService; set client(contentStackClient) { this._client = contentStackClient; } @@ -18,9 +16,6 @@ class AuthHandler { this._host = contentStackHost; } - initLog() { - this.logger = new LoggerService(process.cwd(), 'cli-log'); - } /** * * @@ -31,7 +26,6 @@ class AuthHandler { * TBD: take out the otp implementation from login and create a new method/function to handle otp */ async login(email: string, password: string, tfaToken?: string): Promise { - this.initLog(); return new Promise((resolve, reject) => { if (email && password) { const loginPayload: { @@ -45,18 +39,19 @@ class AuthHandler { this._client .login(loginPayload) .then(async (result: any) => { - this.logger.debug('login result', result); + log.debug('login result', result); if (result.user) { resolve(result.user as User); } else if (result.error_code === 294) { const otpChannel = await askOTPChannel(); + log.debug('otp channel', otpChannel); // need to send sms to the mobile if (otpChannel === 'sms') { try { await this._client.axiosInstance.post('/user/request_token_sms', { user: loginPayload }); cliux.print('CLI_AUTH_LOGIN_SECURITY_CODE_SEND_SUCCESS'); } catch (error) { - this.logger.error('Failed to send the security code', error); + handleAndLogError(error, {}, 'Failed to send the security code') reject(new CLIError({ message: 'Failed to login - failed to send the security code' })); return; } @@ -65,7 +60,7 @@ class AuthHandler { try { resolve(await this.login(email, password, tfToken)); } catch (error) { - this.logger.error('Failed to login with tfa token', error); + handleAndLogError(error, {}, 'Failed to login with tfa token') reject(new CLIError({ message: 'Failed to login with the tf token' })); } } else { @@ -73,7 +68,7 @@ class AuthHandler { } }) .catch((error: any) => { - this.logger.error('Failed to login', error); + handleAndLogError(error, {}, 'Failed to login with the credentials'); reject(new CLIError({ message: error.errorMessage })); }); } else { @@ -88,7 +83,6 @@ class AuthHandler { * @returns {Promise} Promise object returns response object from Contentstack */ async logout(authtoken: string): Promise { - this.initLog(); return new Promise((resolve, reject) => { if (authtoken) { this._client @@ -97,7 +91,7 @@ class AuthHandler { return resolve(response); }) .catch((error: Error) => { - this.logger.error('Failed to logout', error); + handleAndLogError(error, {}, 'Failed to logout'); return reject(new CLIError({ message: 'Failed to logout - ' + error.message })); }); } else { @@ -112,14 +106,13 @@ class AuthHandler { * @returns {Promise} Promise object returns response object from Contentstack */ async validateAuthtoken(authtoken: string): Promise { - this.initLog(); return new Promise((resolve, reject) => { if (authtoken) { this._client .getUser() .then((user: object) => resolve(user)) .catch((error: Error) => { - this.logger.error('Failed to validate token', error); + handleAndLogError(error, {}, 'Failed to validate token'); reject(new CLIError({ message: 'Failed to validate token - ' + error.message })); }); } else { diff --git a/packages/contentstack-auth/src/utils/tokens-validation.ts b/packages/contentstack-auth/src/utils/tokens-validation.ts index 0fe2bf0c4d..159b72adac 100644 --- a/packages/contentstack-auth/src/utils/tokens-validation.ts +++ b/packages/contentstack-auth/src/utils/tokens-validation.ts @@ -1,5 +1,4 @@ -import { messageHandler } from '@contentstack/cli-utilities'; -import { LoggerService } from '@contentstack/cli-utilities'; +import { messageHandler, handleAndLogError, log } from '@contentstack/cli-utilities'; /** * Validate environment * @param contentStackClient @@ -12,18 +11,17 @@ export const validateEnvironment = async ( apiKey: string, environment: string, ): Promise => { - const newLogger = new LoggerService(process.cwd(),'cli-log'); let result: { valid: boolean; message: string }; try { const validationResult = await contentStackClient.Stack({ api_key: apiKey }).environment(environment).fetch(); - newLogger.debug('environment validation result', validationResult); + log.debug('environment validation result', validationResult); if (validationResult.name === environment) { result = { valid: true, message: validationResult }; } else { result = { valid: false, message: messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_ENVIRONMENT_NAME') }; } } catch (error) { - newLogger.error('validate environment error', error); + handleAndLogError(error, { apiKey, environment }, ); result = { valid: false, message: 'CLI_AUTH_TOKENS_VALIDATION_INVALID_ENVIRONMENT_NAME' }; } return result; @@ -36,18 +34,17 @@ export const validateEnvironment = async ( * @returns */ export const validateAPIKey = async (contentStackClient: any, apiKey: string): Promise => { - const newLogger = new LoggerService(process.cwd(),'cli-log'); let result: { valid: boolean; message: string }; try { const validateAPIKeyResult = await contentStackClient.stack({ api_key: apiKey }).fetch(); - newLogger.debug('api key validation result', validateAPIKeyResult); + log.debug('validate api key result', validateAPIKeyResult); if (validateAPIKeyResult.api_key === apiKey) { result = { valid: true, message: validateAPIKeyResult }; } else { result = { valid: false, message: messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_API_KEY') }; } } catch (error) { - newLogger.error('validate api key error', error); + handleAndLogError(error, { apiKey }, ); result = { valid: false, message: messageHandler.parse('CLI_AUTH_TOKENS_VALIDATION_INVALID_API_KEY') }; } From 9f39fc0e6d712a6a5f5420ea7d0977b1ddeb760a Mon Sep 17 00:00:00 2001 From: Aman Kumar Date: Wed, 11 Jun 2025 10:43:51 +0530 Subject: [PATCH 2/2] refactor: updated talismanrc file --- .talismanrc | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.talismanrc b/.talismanrc index f821df17fb..b2058b42c1 100644 --- a/.talismanrc +++ b/.talismanrc @@ -144,4 +144,10 @@ fileignoreconfig: checksum: 941c6a8d59ba58e2004030202ee6282cdd2a424cf8b089aef70a85198553fefe - filename: packages/contentstack-utilities/src/logger/logger.ts checksum: b56504c1e4fb31b676cc1931eb30afc7b9466f03890fe3c76977309e1fd066a6 + - filename: packages/contentstack-auth/src/base-command.ts + checksum: b7b6b94676f8413bf49cbe591b4242eef7936b9b4660b04cf8c8bcd2e96ce0ec + - filename: packages/contentstack-auth/src/commands/auth/tokens/add.ts + checksum: 40f7a6bdfb4c1d5c19d213feffdf9c76eb2fca451567a2fb1cc26338b2163b26 + - filename: packages/contentstack-auth/src/utils/tokens-validation.ts + checksum: fd7c4ebb6d6d955647012454357c360a292d122227a0d130b39dfd56c41f7529 version: "1.0"