@infosel-sdk/core
Version:
Core SDK for Infosel financial services platform. Provides essential infrastructure for authentication, HTTP/GraphQL communication, storage management, and error handling.
130 lines • 5.47 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const axios_1 = tslib_1.__importStar(require("axios"));
const errors_1 = require("../../../errors");
const sdk_error_1 = require("../../../errors/sdk_error");
class TokenAuthProvider {
constructor(mode, token, realm, clientId = 'hub-app') {
this.mode = mode;
this.token = token;
// Validate mode first
if (mode !== 'qa' && mode !== 'prod') {
throw new Error(`Invalid mode: ${mode}. Only 'qa' and 'prod' are supported.`);
}
this.realm = realm !== null && realm !== void 0 ? realm : 'hub'; // Valor por defecto
this.clientId = clientId;
// Validar que el realm no esté vacío
if (!this.realm.trim()) {
throw new Error('Realm cannot be empty');
}
// Validar formato del realm (opcional)
if (!/^[a-zA-Z0-9-_]+$/.test(this.realm)) {
throw new Error('Realm contains invalid characters');
}
// Validar que el clientId no esté vacío
if (!this.clientId.trim()) {
throw new Error('Client ID cannot be empty');
}
}
// Método para obtener el realm actual
getRealm() {
return this.realm;
}
// Método para actualizar el realm dinámicamente
setRealm(realm) {
this.realm = realm;
// Limpiar instancia de axios para que se recree con nueva URL
this._axiosInstance = undefined;
}
get axiosInstance() {
if (!this._axiosInstance) {
const baseURL = this.getBaseUrl();
this._axiosInstance = axios_1.default.create({
baseURL,
timeout: 60000,
});
}
return this._axiosInstance;
}
getBaseUrl() {
switch (this.mode) {
case 'qa':
return 'https://iam-admin-qa.infosel-digitalfactory.com';
case 'prod':
return 'https://iam-admin-prodaws.infosel-digitalfactory.com';
case 'preprod':
return 'https://iam-admin-preprod.infosel-digitalfactory.com';
default:
throw new Error(`Invalid mode: ${this.mode}. Only 'qa' and 'prod' are supported.`);
}
}
generateToken(_) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
// If storage is available, save the token for auth interceptors
if (this._storage) {
try {
yield this._storage.saveObject('oauth_token', this.token);
}
catch (error) {
console.warn('⚠️ Could not save token to storage:', error);
}
}
return this.token;
});
}
shouldRefreshTokenOnError(error) {
var _a, _b, _c;
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const tokenExpired = (0, axios_1.isAxiosError)(error) &&
((_b = (_a = error.config) === null || _a === void 0 ? void 0 : _a.url) === null || _b === void 0 ? void 0 : _b.match(`/auth/realms/${this.realm}/protocol/openid-connect/token`)) === null &&
((_c = error.response) === null || _c === void 0 ? void 0 : _c.status) === 401;
const sdkError = (0, errors_1.parseSdkError)(error);
return (tokenExpired ||
(sdkError.type === sdk_error_1.SdkErrorType.LOCAL_STORAGE_KEY_NOT_FOUND &&
sdkError.message === 'oauth_token'));
});
}
refreshToken(__, ___) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (this._refreshTokenRequest) {
return yield this._refreshTokenRequest;
}
const requestRef = () => tslib_1.__awaiter(this, void 0, void 0, function* () {
const { data } = yield this.axiosInstance.post(`/auth/realms/${this.realm}/protocol/openid-connect/token`, {
client_id: this.clientId,
refresh_token: this.token.refreshToken,
grant_type: 'refresh_token',
}, { headers: { 'content-type': 'application/x-www-form-urlencoded' } });
this.token.accessToken = data.access_token || '';
this.token.refreshToken = data.refresh_token || '';
return this.token;
});
this._refreshTokenRequest = requestRef().finally(() => {
this._refreshTokenRequest = undefined;
});
return yield this._refreshTokenRequest;
});
}
setToken(token) {
this.token = token;
// Auto-save to storage if available
if (this._storage) {
this._storage.saveObject('oauth_token', token).catch((error) => {
console.warn('⚠️ Could not save updated token to storage:', error);
});
}
}
// Method to inject storage instance (called by InfoselSdkManager)
setStorage(storage) {
this._storage = storage;
// Auto-save current token to storage
if (this.token) {
this._storage.saveObject('oauth_token', this.token).catch((error) => {
console.warn('⚠️ Could not save initial token to storage:', error);
});
}
}
}
exports.default = TokenAuthProvider;
//# sourceMappingURL=index.js.map