UNPKG

@sonatel-os/juf

Version:

The community SDK for Orange Money, SMS, Email & Sonatel APIs on the Orange Developer Platform.

138 lines (125 loc) 5.18 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _chunkW5WEVJMXcjs = require('./chunk-W5WEVJMX.cjs'); // src/auth/authenticationService.js var Authentication = class _Authentication { /** @private @type {Cache} */ #cache; /** * @private * @type {{ * onProd: boolean, * onPProd: boolean, * url: { production: string, sandbox: string, preprod: string }, * client_id: string, * client_secret: string, * decode_qr_sp_authorization: string * }} */ #config; /** @private @type {import('axios').AxiosInstance} */ #client; /** @private */ #logger; /** * Creates an Authentication instance with injectable dependencies. * * @param {object} deps - Dependencies for the authentication service. * @param {object} deps.config - Apigee configuration (client_id, client_secret, urls, etc.). * @param {Cache} deps.cache - Cache instance for token storage. * @param {import('axios').AxiosInstance} deps.client - HTTP client instance. * @param {object} deps.logger - Logger instance with error/warn/info/debug methods. */ constructor({ config, cache, client, logger: logger2 }) { this.#config = config; this.#cache = cache; this.#client = client; this.#logger = logger2; } /** * Factory method to initialize Authentication with default dependencies. * @memberof Service\Authentication * @method init * @returns {Authentication} An initialized instance of Authentication. */ static init() { const apigeeConfig = _chunkW5WEVJMXcjs.envConfig.get("apigee"); return new _Authentication({ config: apigeeConfig, cache: _chunkW5WEVJMXcjs.CachingSystem, client: _chunkW5WEVJMXcjs.requester_default.bootstrap({ baseURL: _chunkW5WEVJMXcjs.getApiUrl.call(void 0, ) }), logger: _chunkW5WEVJMXcjs.logger.child("auth") }); } /** * @private * @returns {string} The generated cache key. */ #getCacheKey() { return `auth_${this.#config.client_id}`; } /** * @private * @returns {string} URL-encoded payload for the authentication request. */ #createAuthPayload() { const { client_id, client_secret } = this.#config; const params = new URLSearchParams({ client_id, client_secret, grant_type: _chunkW5WEVJMXcjs.OAUTH_GRANT_TYPE }); return params.toString(); } /** * Makes the API call to fetch the authentication token and handles caching. * * @private * @param {string} payload - The URL-encoded payload for the authentication request. * @param {string} cacheKey - The cache key to store the token. * @returns {Promise<object>} The authentication response. * @throws {AuthenticationError} When the API request fails. */ async #fetchToken(payload, cacheKey) { try { const { data } = await this.#client.post(_chunkW5WEVJMXcjs.OAUTH_TOKEN_PATH, payload, { headers: { "Content-Type": _chunkW5WEVJMXcjs.OAUTH_CONTENT_TYPE } }); this.#cache.store(cacheKey, data); return data; } catch (error) { const upstream = _optionalChain([error, 'access', _ => _.response, 'optionalAccess', _2 => _2.data]); this.#logger.error("Authentication request failed", { status: _optionalChain([error, 'access', _3 => _3.response, 'optionalAccess', _4 => _4.status]) }); throw new (0, _chunkW5WEVJMXcjs.AuthenticationError)( _optionalChain([upstream, 'optionalAccess', _5 => _5.error_description]) || "Authentication request failed. Check your configuration.", upstream || null ); } } /** * Authenticates against the Sonatel API Platform using the client credentials flow. * Caches the access token to reduce redundant authentication calls. * * @async * @method debug * @memberof Service\Authentication * @returns {Promise<{ access_token: string, expires_in: number, refresh_expires_in: number, token_type: string, notbefore_policy: number, session_state: string }>} * @throws {AuthenticationError} When authentication fails. * * @example * authentication.debug() * .then(console.log) * .catch(({ message }) => console.log(`Failed: ${message}`)) */ async debug() { const cacheKey = this.#getCacheKey(); const cachedResponse = this.#cache.retrieve(cacheKey); if (cachedResponse) { return cachedResponse; } const payload = this.#createAuthPayload(); return this.#fetchToken(payload, cacheKey); } }; var authenticationService_default = Authentication; exports.authenticationService_default = authenticationService_default; //# sourceMappingURL=chunk-UD6WYISC.cjs.map