UNPKG

@thoughtspot/visual-embed-sdk

Version:
92 lines 3.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resetCachedAuthToken = exports.getAuthenticationToken = void 0; const errors_1 = require("./errors"); const utils_1 = require("./utils"); const authService_1 = require("./utils/authService/authService"); const logger_1 = require("./utils/logger"); const cacheAuthTokenKey = 'cachedAuthToken'; const getCacheAuthToken = () => (0, utils_1.getValueFromWindow)(cacheAuthTokenKey); const storeAuthTokenInCache = (token) => { (0, utils_1.storeValueInWindow)(cacheAuthTokenKey, token); }; // This method can be used to get the authToken using the embedConfig /** * * @param embedConfig */ async function getAuthenticationToken(embedConfig) { const cachedAuthToken = getCacheAuthToken(); // Since we don't have token validation enabled , we cannot tell if the // cached token is valid or not. So we will always fetch a new token. if (cachedAuthToken && !embedConfig.disableTokenVerification) { let isCachedTokenStillValid; try { isCachedTokenStillValid = await validateAuthToken(embedConfig, cachedAuthToken, true); } catch { isCachedTokenStillValid = false; } if (isCachedTokenStillValid) return cachedAuthToken; } const { authEndpoint, getAuthToken } = embedConfig; let authToken = null; if (getAuthToken) { authToken = await getAuthToken(); } else { const response = await (0, authService_1.fetchAuthTokenService)(authEndpoint); authToken = await response.text(); } try { // this will throw error if the token is not valid await validateAuthToken(embedConfig, authToken); } catch (e) { logger_1.logger.error(`${errors_1.ERROR_MESSAGE.INVALID_TOKEN_ERROR} Error : ${e.message}`); throw e; } storeAuthTokenInCache(authToken); return authToken; } exports.getAuthenticationToken = getAuthenticationToken; const validateAuthToken = async (embedConfig, authToken, suppressAlert) => { const cachedAuthToken = getCacheAuthToken(); if (embedConfig.disableTokenVerification) { logger_1.logger.info('Token verification is disabled. Assuming token is valid.'); return true; } try { const isTokenValid = await (0, authService_1.verifyTokenService)(embedConfig.thoughtSpotHost, authToken); if (isTokenValid) return true; } catch { return false; } if (cachedAuthToken && cachedAuthToken === authToken) { if (!embedConfig.suppressErrorAlerts && !suppressAlert) { // eslint-disable-next-line no-alert alert(errors_1.ERROR_MESSAGE.DUPLICATE_TOKEN_ERR); } throw new Error(errors_1.ERROR_MESSAGE.DUPLICATE_TOKEN_ERR); } else { throw new Error(errors_1.ERROR_MESSAGE.INVALID_TOKEN_ERROR); } }; /** * Resets the auth token and a new token will be fetched on the next request. * @example * ```js * resetCachedAuthToken(); * ``` * @version SDK: 1.28.0 | ThoughtSpot: * * @group Authentication / Init */ const resetCachedAuthToken = () => { storeAuthTokenInCache(null); }; exports.resetCachedAuthToken = resetCachedAuthToken; //# sourceMappingURL=authToken.js.map