codogo-react-widgets
Version:
Provides a unified way to access the styling of commonly used widgets across different apps
79 lines (66 loc) • 1.75 kB
JavaScript
import jwtDecode from "jwt-decode";
import Channel from "js-channel";
import moment from "moment";
import { accountURL, scapholdAuthTokenStorageKey } from "./consts";
var tokenIsValid = function tokenIsValid(jwt) {
try {
jwtDecode(jwt);
return true;
} catch (e) {
return false;
}
};
var tokenInDate = function tokenInDate(jwt) {
try {
return moment.unix(jwtDecode(jwt).exp).isAfter(moment());
} catch (e) {
return false;
}
};
var shouldTryToVendJWT = function shouldTryToVendJWT() {
return window.location.origin === accountURL;
};
var callbackQueue = [];
var redirectToGetToken = function redirectToGetToken() {
window.location = accountURL + "/app/login?come_from=" + window.location;
};
var retrivedJWT = function retrivedJWT(jwt) {
if (shouldTryToVendJWT()) {
return false;
}
if (!jwt || !tokenInDate(jwt)) {
return redirectToGetToken();
} else {
localStorage.setItem(scapholdAuthTokenStorageKey, jwt);
}
callbackQueue.forEach(function (cb) {
return cb(jwt);
});
};
if (document.getElementById("codogo-account-iframe")) {
Channel.build({
window: document.getElementById("codogo-account-iframe").contentWindow,
origin: "*",
scope: "jwtVending",
onReady: function onReady(chan) {
chan.call({
method: "getJWT",
success: retrivedJWT,
error: redirectToGetToken
});
}
});
}
var getJWTFromIFrame = function getJWTFromIFrame() {
if (shouldTryToVendJWT()) {
return false;
}
return new Promise(function (done) {
return callbackQueue.push(done);
});
};
export default (function () {
return Promise.resolve(localStorage.getItem(scapholdAuthTokenStorageKey)).then(function (jwt) {
return jwt && tokenIsValid(jwt) && tokenInDate(jwt) ? jwt : getJWTFromIFrame();
});
});