(function () {
const TOKEN_ID = 'cmp-ots-token';
const UID_ID = 'cmp-ots-uid';
let BASE_URL = '';
/**
* @typedef {Object} Help4.AuthService.Token
* @property {string} cmp-ots-token
* @property {string} cmp-ots-uid
*/
/**
* @typedef {Object} Help4.AuthService.TokenInfo
* @property {string} baseUrl - base URL of server
* @property {Help4.AuthService.Token} token - OTS token for this server
*/
/**
* Service for OTS
* @namespace AuthService
* @memberof Help4
*/
Help4.AuthService = {
/** @returns {string|null} */
getToken: (url) => _getValue(url)?.[TOKEN_ID] || null,
/** @returns {string|null} */
getUID: (url) => _getValue(url)?.[UID_ID] || null,
/** @param {string} baseUrl */
setBaseUrl: baseUrl => void (BASE_URL = baseUrl),
/** @returns {boolean} */
isOTS: () => !!(_getValue() || []).length,
/** @param {string} baseUrl */
removeToken: (baseUrl) => {
const tokens = _getValue() || [];
const index = tokens.findIndex(({baseUrl: bu}) => bu === baseUrl);
if (index >= 0) {
tokens.splice(index, 1);
_set(tokens);
}
},
/**
* @param {Object} event
* @param {string|Object} event.data - string if coming from {@link Help4.receiveMessage}; Object if external usage from {@link Help4.ajax.Ajax; _handleExternalUsage}
* @returns {boolean}
*/
receiveMessage: ({data} = {}) => {
if (BASE_URL) {
if (typeof data === 'string') {
try {
/** @type {Help4.AuthService.Token} */
data = Help4.JSON.parse(data.replace(/[&><'/\\`=]/g, ''));
} catch (e) {
return false;
}
}
if (data[TOKEN_ID] && data[UID_ID]) {
const {AuthService, ajax: {Ajax}} = Help4;
AuthService.removeToken(BASE_URL);
const tokens = _getValue() || [];
tokens.push({baseUrl: BASE_URL, token: data});
_set(tokens);
BASE_URL = '';
return true;
}
}
return false;
}
}
/**
* @memberof Help4.AuthService
* @private
* @param {string} [url = '']
* @returns {Help4.AuthService.TokenInfo[]|Help4.AuthService.Token|null}
*/
function _getValue(url = '') {
const tokens = _get();
return url && tokens
? (tokens.find(({baseUrl}) => url.startsWith(baseUrl))?.token || null)
: tokens;
}
/**
* @memberof Help4.AuthService
* @private
* @param {Help4.AuthService.TokenInfo[]} tokens
*/
function _set(tokens) {
sessionStorage.setItem(Help4.OPAQUE_TOKEN_SERVICE_KEY, Help4.JSON.stringify(tokens));
}
/**
* @memberof Help4.AuthService
* @private
* @returns {Help4.AuthService.TokenInfo[]|null}
*/
function _get() {
try {
return Help4.JSON.parse(sessionStorage.getItem(Help4.OPAQUE_TOKEN_SERVICE_KEY));
} catch (e) {
return null;
}
}
})();