UNPKG

@sonatel-os/juf

Version:

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

138 lines (136 loc) 4.33 kB
import { AuthenticationError, CachingSystem, OAUTH_CONTENT_TYPE, OAUTH_GRANT_TYPE, OAUTH_TOKEN_PATH, envConfig, getApiUrl, logger, requester_default } from "./chunk-4T5F3RH2.js"; // 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 = envConfig.get("apigee"); return new _Authentication({ config: apigeeConfig, cache: CachingSystem, client: requester_default.bootstrap({ baseURL: getApiUrl() }), logger: 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: 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(OAUTH_TOKEN_PATH, payload, { headers: { "Content-Type": OAUTH_CONTENT_TYPE } }); this.#cache.store(cacheKey, data); return data; } catch (error) { const upstream = error.response?.data; this.#logger.error("Authentication request failed", { status: error.response?.status }); throw new AuthenticationError( upstream?.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; export { authenticationService_default }; //# sourceMappingURL=chunk-QDNKDHVC.js.map