UNPKG

@infosel-sdk/core

Version:

Core SDK for Infosel financial services platform. Provides essential infrastructure for authentication, HTTP/GraphQL communication, storage management, and error handling.

62 lines 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const axios_1 = require("axios"); const errors_1 = require("../../errors"); class InfoselAuthInterceptor { constructor(sdkManager) { this.sdkManager = sdkManager; } tokenInterceptor(requestConfig) { var _a; return tslib_1.__awaiter(this, void 0, void 0, function* () { /** * We ignore the request that already have a token, this because the * '/refreshToken' request insert the refresh token itself. * And this give us the option to override the existing token if is needed. */ if ((_a = requestConfig.headers) === null || _a === void 0 ? void 0 : _a.Authorization) { return requestConfig; } try { const localToken = yield this.sdkManager.storage.getObject('oauth_token'); if (localToken && requestConfig.headers) { requestConfig.headers['Authorization'] = `Bearer ${localToken.accessToken}`; } return requestConfig; } catch (error) { const shouldRefresh = yield this.sdkManager.authProvider.shouldRefreshTokenOnError(error); if (!shouldRefresh) { return requestConfig; } const token = yield this.sdkManager.authProvider.generateToken(requestConfig.url || '-'); const authenticationToken = yield this.sdkManager.storage.saveObject('oauth_token', token); if (authenticationToken && requestConfig.headers) { requestConfig.headers['Authorization'] = `Bearer ${authenticationToken.accessToken}`; } return requestConfig; } }); } errorInterceptor(axiosInstance, error) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const shouldRefresh = yield this.sdkManager.authProvider.shouldRefreshTokenOnError(error); if (shouldRefresh && (0, axios_1.isAxiosError)(error) && error.config) { return yield this.refreshTokenInterceptor(axiosInstance, error.config); } throw (0, errors_1.parseSdkError)(error); }); } refreshTokenInterceptor(axiosInstance, originalRequestConfig) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const localToken = yield this.sdkManager.storage.getObject('oauth_token'); const authToken = yield this.sdkManager.authProvider.refreshToken(originalRequestConfig.url || '-', localToken); const { accessToken } = yield this.sdkManager.storage.saveObject('oauth_token', authToken); originalRequestConfig.headers = Object.assign(Object.assign({}, originalRequestConfig.headers), { Authorization: `Bearer ${accessToken}` }); return yield axiosInstance.request(originalRequestConfig); }); } } exports.default = InfoselAuthInterceptor; //# sourceMappingURL=infosel_auth_interceptor.js.map