dww-rog-test
Version:
846 lines (744 loc) • 28 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(factory((global['react-onegraph'] = {}),global.React));
}(this, (function (exports,React) { 'use strict';
function __$$styleInject(css, ref) {
if ( ref === void 0 ) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') { return; }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var React__default = 'default' in React ? React['default'] : React;
function OAuthError(errorObject, fileName, lineNumber) {
var message = "OAuthError: " + errorObject.error + " " + errorObject.error_description;
var instance = new Error(message, fileName, lineNumber);
instance.oauthError = errorObject;
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, OAuthError);
}
return instance;
}
OAuthError.prototype = Object.create(Error.prototype, {
constructor: {
value: Error,
enumerable: false,
writable: true,
configurable: true
}
});
if (Object.setPrototypeOf) {
Object.setPrototypeOf(OAuthError, Error);
} else {
OAuthError.__proto__ = Error;
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var InMemoryStorage = function InMemoryStorage() {
var _this = this;
classCallCheck(this, InMemoryStorage);
this.state = {};
this.getItem = function (key) {
return _this.state[key];
};
this.setItem = function (key, value) {
_this.state[key] = value;
};
this.removeItem = function (key) {
delete _this.state[key];
};
};
var OG_PREFIX = 'oneGraph:';
var LocalStorage = function () {
function LocalStorage() {
classCallCheck(this, LocalStorage);
}
createClass(LocalStorage, [{
key: 'getItem',
value: function getItem(key) {
return localStorage.getItem(OG_PREFIX + key);
}
}, {
key: 'setItem',
value: function setItem(key, value) {
return localStorage.setItem(OG_PREFIX + key, value);
}
}, {
key: 'removeItem',
value: function removeItem(key) {
return localStorage.removeItem(OG_PREFIX + key);
}
}]);
return LocalStorage;
}();
var DEBUG_KEY = '__og_debug';
function hasLocalStorage() {
try {
localStorage.setItem(DEBUG_KEY, 'debug');
localStorage.removeItem(DEBUG_KEY);
return true;
} catch (e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
localStorage.length !== 0;
}
}
var URI_REGEX = new RegExp(['^(https?://[^:/?#]*(?::[0-9]+)?)', // origin
'(/{0,1}[^?#]*)', // path
'(\\?[^#]*|)', // search
'(#.*|)$'].join(''));
function parseQuery(queryString) {
return queryString.split(/[?&]/).reduce(function (query, part) {
var _part$split = part.split('='),
_part$split2 = slicedToArray(_part$split, 2),
param = _part$split2[0],
value = _part$split2[1];
if (param != null && value != null) {
query[param] = value;
}
return query;
}, {});
}
function parse(uriString) {
var match = uriString.match(URI_REGEX);
if (!match) {
throw new Error('invalid url ' + uriString);
}
return {
origin: match[1],
path: match[2],
query: parseQuery(match[3])
};
}
function addQueryParams(uri, query) {
return _extends({}, uri, {
query: _extends({}, uri.query, query)
});
}
function setPath(uri, path) {
return _extends({}, uri, {
path: path
});
}
function queryToString(query) {
return Object.keys(query).map(function (k) {
return k + '=' + query[k];
}).join('&');
}
function toString(uri) {
var origin = uri.origin,
path = uri.path,
query = uri.query;
var queryString = queryToString(query);
return origin + path + (queryString ? '?' + queryString : '');
}
function make(_ref) {
var origin = _ref.origin,
path = _ref.path,
query = _ref.query;
var uri = parse(origin);
uri = setPath(uri, path);
uri = addQueryParams(uri, query);
return uri;
}
var URI = { parse: parse, addQueryParams: addQueryParams, setPath: setPath, toString: toString, make: make };
var POLL_INTERVAL = 35;
var ALL_SERVICES = ['eventil', 'github', 'gmail', 'google', 'google-calendar', 'google-compute', 'google-docs', 'google-translate', 'hubspot', 'intercom', 'salesforce', 'slack', 'stripe', 'trello', 'twilio', 'twitter', 'youtube', 'zeit', 'zendesk'];
function _friendlyServiceName(service) {
switch (service) {
case 'eventil':
return 'Eventil';
case 'github':
return 'GitHub';
case 'gmail':
return 'Gmail';
case 'google':
return 'Google';
case 'google-calendar':
return 'Google Calendar';
case 'google-compute':
return 'Google Compute';
case 'google-docs':
return 'Google Docs';
case 'google-translate':
return 'Google Translate';
case 'hubspot':
return 'HubSpot';
case 'intercom':
return 'Intercom';
case 'salesforce':
return 'Salesforce';
case 'slack':
return 'Slack';
case 'stripe':
return 'Stripe';
case 'trello':
return 'Trello';
case 'twilio':
return 'Twilio';
case 'twitter':
return 'Twitter';
case 'youtube':
return 'YouTube';
case 'zeit':
return 'Zeit';
case 'zendesk':
return 'Zendesk';
default:
// exhaustive switch check from flow
throw new Error('No such service');
}
}
function getWindowOpts() {
var windowWidth = Math.min(800, Math.floor(window.outerWidth * 0.8));
var windowHeight = Math.min(630, Math.floor(window.outerHeight * 0.5));
var windowArea = {
width: windowWidth,
height: windowHeight,
left: Math.round(window.screenX + (window.outerWidth - windowWidth) / 2),
top: Math.round(window.screenY + (window.outerHeight - windowHeight) / 8)
};
// TODO: figure out how to show the toolbar icons in the window for password managers
return {
width: windowArea.width,
height: windowArea.height,
left: windowArea.left,
top: windowArea.top,
toolbar: 0,
scrollbars: 1,
status: 1,
resizable: 1,
menuBar: 0
};
}
function createAuthWindow(authUrlString, service, stateParam, scopes) {
var windowOpts = getWindowOpts();
var authUrl = URI.addQueryParams(URI.parse(authUrlString), _extends({
state: stateParam
}, scopes ? { scopes: scopes.join(',') } : {}));
return window.open(URI.toString(authUrl), 'Log in with ' + _friendlyServiceName(service), Object.keys(windowOpts).map(function (k) {
return k + '=' + windowOpts[k];
}).join(','));
}
// Cycles path through URL.origin to ensure that it's the same format we'll
// see in the auth window's location
function normalizeRedirectOrigin(origin) {
return URI.parse(origin).origin;
}
// Cycles path through URL.pathname to ensure that it's the same format we'll
// see in the auth window's location
function normalizeRedirectPath(path) {
return path === '/' ? '' : path;
}
function loggedInQuery(service) {
switch (service) {
case 'eventil':
return 'query { me { eventil { id }}}';
case 'github':
return 'query { me { github { id }}}';
case 'gmail':
return 'query { me { gmail { sub }}}';
case 'google':
return 'query { me { google { sub }}}';
case 'google-calendar':
return 'query { me { googleCalendar { sub }}}';
case 'google-compute':
return 'query { me { googleCompute { sub }}}';
case 'google-docs':
return 'query { me { googleDocs { sub }}}';
case 'google-translate':
return 'query { me { googleTranslate { sub }}}';
case 'hubspot':
return 'query { me { hubspot { userId }}}';
case 'intercom':
return 'query { me { intercom { id }}}';
case 'salesforce':
return 'query { me { salesforce { sub }}}';
case 'slack':
return 'query { me { slack { id }}}';
case 'stripe':
return 'query { me { stripe { id }}}';
case 'trello':
return 'query { me { trello { id }}}';
case 'twilio':
return 'query { me { twilio { id }}}';
case 'twitter':
return 'query { me { twitter { id }}}';
case 'youtube':
return 'query { me { youTube { sub }}}';
case 'zeit':
return 'query { me { zeit { id }}}';
case 'zendesk':
return 'query { me { zendesk { id }}}';
default:
// exhaustive switch check from flow
throw new Error('No such service ' + service);
}
}
function getIsLoggedIn(queryResult, service) {
var _ref, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9, _ref10, _ref11, _ref12, _ref13, _ref14, _ref15, _ref16, _ref17, _ref18, _ref19;
switch (service) {
case 'eventil':
return !!((_ref = queryResult) != null ? (_ref = _ref.data) != null ? (_ref = _ref.me) != null ? (_ref = _ref.eventil) != null ? _ref.id : _ref : _ref : _ref : _ref);
case 'github':
return !!((_ref2 = queryResult) != null ? (_ref2 = _ref2.data) != null ? (_ref2 = _ref2.me) != null ? (_ref2 = _ref2.github) != null ? _ref2.id : _ref2 : _ref2 : _ref2 : _ref2);
case 'gmail':
return !!((_ref3 = queryResult) != null ? (_ref3 = _ref3.data) != null ? (_ref3 = _ref3.me) != null ? (_ref3 = _ref3.gmail) != null ? _ref3.sub : _ref3 : _ref3 : _ref3 : _ref3);
case 'google':
return !!((_ref4 = queryResult) != null ? (_ref4 = _ref4.data) != null ? (_ref4 = _ref4.me) != null ? (_ref4 = _ref4.google) != null ? _ref4.sub : _ref4 : _ref4 : _ref4 : _ref4);
case 'google-calendar':
return !!((_ref5 = queryResult) != null ? (_ref5 = _ref5.data) != null ? (_ref5 = _ref5.me) != null ? (_ref5 = _ref5.googleCalendar) != null ? _ref5.sub : _ref5 : _ref5 : _ref5 : _ref5);
case 'google-compute':
return !!((_ref6 = queryResult) != null ? (_ref6 = _ref6.data) != null ? (_ref6 = _ref6.me) != null ? (_ref6 = _ref6.googleCompute) != null ? _ref6.sub : _ref6 : _ref6 : _ref6 : _ref6);
case 'google-docs':
return !!((_ref7 = queryResult) != null ? (_ref7 = _ref7.data) != null ? (_ref7 = _ref7.me) != null ? (_ref7 = _ref7.googleDocs) != null ? _ref7.sub : _ref7 : _ref7 : _ref7 : _ref7);
case 'google-translate':
return !!((_ref8 = queryResult) != null ? (_ref8 = _ref8.data) != null ? (_ref8 = _ref8.me) != null ? (_ref8 = _ref8.googleTranslate) != null ? _ref8.sub : _ref8 : _ref8 : _ref8 : _ref8);
case 'intercom':
return !!((_ref9 = queryResult) != null ? (_ref9 = _ref9.data) != null ? (_ref9 = _ref9.me) != null ? (_ref9 = _ref9.intercom) != null ? _ref9.id : _ref9 : _ref9 : _ref9 : _ref9);
case 'hubspot':
return !!((_ref10 = queryResult) != null ? (_ref10 = _ref10.data) != null ? (_ref10 = _ref10.me) != null ? (_ref10 = _ref10.hubspot) != null ? _ref10.userId : _ref10 : _ref10 : _ref10 : _ref10);
case 'salesforce':
return !!((_ref11 = queryResult) != null ? (_ref11 = _ref11.data) != null ? (_ref11 = _ref11.me) != null ? (_ref11 = _ref11.salesforce) != null ? _ref11.sub : _ref11 : _ref11 : _ref11 : _ref11);
case 'slack':
return !!((_ref12 = queryResult) != null ? (_ref12 = _ref12.data) != null ? (_ref12 = _ref12.me) != null ? (_ref12 = _ref12.slack) != null ? _ref12.id : _ref12 : _ref12 : _ref12 : _ref12);
case 'stripe':
return !!((_ref13 = queryResult) != null ? (_ref13 = _ref13.data) != null ? (_ref13 = _ref13.me) != null ? (_ref13 = _ref13.stripe) != null ? _ref13.id : _ref13 : _ref13 : _ref13 : _ref13);
case 'trello':
return !!((_ref14 = queryResult) != null ? (_ref14 = _ref14.data) != null ? (_ref14 = _ref14.me) != null ? (_ref14 = _ref14.trello) != null ? _ref14.id : _ref14 : _ref14 : _ref14 : _ref14);
case 'twilio':
return !!((_ref15 = queryResult) != null ? (_ref15 = _ref15.data) != null ? (_ref15 = _ref15.me) != null ? (_ref15 = _ref15.twilio) != null ? _ref15.id : _ref15 : _ref15 : _ref15 : _ref15);
case 'twitter':
return !!((_ref16 = queryResult) != null ? (_ref16 = _ref16.data) != null ? (_ref16 = _ref16.me) != null ? (_ref16 = _ref16.twitter) != null ? _ref16.id : _ref16 : _ref16 : _ref16 : _ref16);
case 'youtube':
return !!((_ref17 = queryResult) != null ? (_ref17 = _ref17.data) != null ? (_ref17 = _ref17.me) != null ? (_ref17 = _ref17.youTube) != null ? _ref17.sub : _ref17 : _ref17 : _ref17 : _ref17);
case 'zeit':
return !!((_ref18 = queryResult) != null ? (_ref18 = _ref18.data) != null ? (_ref18 = _ref18.me) != null ? (_ref18 = _ref18.zeit) != null ? _ref18.id : _ref18 : _ref18 : _ref18 : _ref18);
case 'zendesk':
return !!((_ref19 = queryResult) != null ? (_ref19 = _ref19.data) != null ? (_ref19 = _ref19.me) != null ? (_ref19 = _ref19.zendesk) != null ? _ref19.id : _ref19 : _ref19 : _ref19 : _ref19);
default:
// exhaustive switch check from flow
throw new Error('No such service ' + service);
}
}
function getServiceErrors(errors, service) {
return errors.filter(function (error) {
return error.path && error.path.includes(service);
});
}
// Don't support fragments for gql services, yet.
var ME_PSUEDO_FRAGMENT = '\nme {\n eventil {\n id\n }\n github {\n id\n }\n gmail {\n sub\n }\n google {\n sub\n }\n googleCalendar {\n sub\n }\n googleCompute {\n sub\n }\n googleDocs {\n sub\n }\n googleTranslate {\n sub\n }\n hubspot {\n userId\n }\n intercom {\n id\n }\n salesforce {\n sub\n }\n slack {\n id\n }\n stripe {\n id\n }\n trello {\n id\n }\n twilio {\n id\n }\n twitter {\n id\n }\n youTube {\n sub\n }\n zeit {\n id\n }\n zendesk {\n id\n }\n}\n';
var ALL_SERVICES_QUERY = '\n{\n ' + ME_PSUEDO_FRAGMENT + '\n}';
function logoutMutation(service) {
var serviceEnum = service.toUpperCase().replace(/-/, '_');
return 'mutation {\n signoutServices(data: {services: [' + serviceEnum + ']}) {\n ' + ME_PSUEDO_FRAGMENT + '\n }\n }';
}
function fetchQuery(fetchUrl, query, token) {
return fetch(fetchUrl, {
method: 'POST',
headers: {
Authentication: 'Bearer ' + token.accessToken,
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({ query: query })
}).then(function (response) {
return response.json();
});
}
function exchangeCode(oneGraphOrigin, appId, redirectOrigin, redirectPath, code, token) {
var redirectUri = redirectOrigin + redirectPath;
var url = URI.make({
origin: oneGraphOrigin,
path: '/oauth/code',
query: {
app_id: appId,
redirect_uri: redirectUri,
code: code
}
});
var headers = _extends({
'Content-Type': 'application/json',
Accept: 'application/json'
}, token ? { Authentication: 'Bearer ' + token.accessToken } : {});
return fetch(URI.toString(url), {
method: 'POST',
headers: headers
}).then(function (response) {
return response.json();
});
}
function byteArrayToString(byteArray) {
return byteArray.reduce(function (acc, byte) {
return acc + (byte & 0xff).toString(16).slice(-2);
}, '');
}
function makeStateParam() {
return byteArrayToString(window.crypto.getRandomValues(new Uint8Array(32)));
}
function isExpired(token) {
return token.expireDate < Date.now();
}
function tokenFromStorage(storage, appId) {
var v = storage.getItem(appId);
if (v) {
var possibleToken = JSON.parse(v);
if (typeof possibleToken.accessToken === 'string' && typeof possibleToken.expireDate === 'number' && !isExpired(possibleToken)) {
return possibleToken;
}
}
return null;
}
var DEFAULT_ONEGRAPH_ORIGIN = 'https://serve.onegraph.com';
var OneGraphAuth = function () {
function OneGraphAuth(opts) {
var _this = this;
classCallCheck(this, OneGraphAuth);
this._authWindows = {};
this._intervalIds = {};
this._accessToken = null;
this.supportedServices = ALL_SERVICES;
this._clearInterval = function (service) {
clearInterval(_this._intervalIds[service]);
delete _this._intervalIds[service];
};
this._clearAuthWindow = function (service) {
var w = _this._authWindows[service];
w && w.close();
delete _this._authWindows[service];
};
this.cleanup = function (service) {
_this._clearInterval(service);
_this._clearAuthWindow(service);
};
this.accessToken = function () {
return _this._accessToken;
};
this.authHeaders = function () {
if (_this._accessToken) {
return { Authentication: 'Bearer ' + _this._accessToken.accessToken };
} else {
return {};
}
};
this._makeAuthUrl = function (service) {
var authUrl = URI.make({
origin: _this.oneGraphOrigin,
path: '/oauth/start',
query: {
service: service,
app_id: _this.appId,
response_type: 'code',
redirect_origin: _this._redirectOrigin,
redirect_path: _this._redirectPath
}
});
return URI.toString(authUrl);
};
this.setToken = function (token) {
_this._accessToken = token;
_this._storage.setItem(_this._storageKey, JSON.stringify(token));
};
this._waitForAuthFinish = function (service, stateParam) {
return new Promise(function (resolve, reject) {
_this._intervalIds[service] = setInterval(function () {
try {
var authLocation = _this._authWindows[service].location;
if (authLocation.origin === _this._redirectOrigin) {
var params = URI.parse(authLocation.href).query;
if (stateParam !== params.state) {
reject(new OAuthError({
error: 'invalid_request',
error_description: 'The state param does not match'
}));
} else {
var code = params.code;
if (!code) {
reject(new OAuthError({
error: 'invalid_grant',
error_description: 'Missing code'
}));
} else {
exchangeCode(_this.oneGraphOrigin, _this.appId, _this._redirectOrigin, _this._redirectPath, code, _this._accessToken).then(function (response) {
if (response.error) {
reject(new OAuthError(response));
} else if (typeof response.access_token === 'string' && typeof response.expires_in === 'number') {
var _token = {
accessToken: response.access_token,
expireDate: Date.now() + response.expires_in * 1000
};
_this.setToken(_token);
resolve({ token: _token });
} else {
reject(new Error('Unexpected result from server'));
}
}).catch(function (e) {
return reject(e);
});
}
}
_this.cleanup(service);
}
} catch (e) {
if (e instanceof window.DOMException) {
// do nothing--probably on the service's or onegraph's domain
} else {
console.error('unexpected error waiting for auth to finish for ' + service, e);
_this.cleanup(service);
reject(e);
}
}
}, POLL_INTERVAL);
});
};
this.login = function (service, scopes) {
_this.cleanup(service);
var stateParam = makeStateParam();
_this._authWindows[service] = createAuthWindow(_this._makeAuthUrl(service), service, stateParam, scopes);
return _this._waitForAuthFinish(service, stateParam);
};
this.isLoggedIn = function (service) {
var accessToken = _this._accessToken;
if (accessToken) {
return fetchQuery(_this._fetchUrl, loggedInQuery(service), accessToken).then(function (result) {
return getIsLoggedIn(result, service);
});
} else {
return Promise.resolve(false);
}
};
this.servicesStatus = function () {
var accessToken = _this._accessToken;
if (accessToken) {
return fetchQuery(_this._fetchUrl, ALL_SERVICES_QUERY, accessToken).then(function (result) {
return ALL_SERVICES.reduce(function (acc, service) {
acc[service] = { isLoggedIn: getIsLoggedIn(result, service) };
return acc;
}, {});
});
} else {
return Promise.resolve(ALL_SERVICES.reduce(function (acc, service) {
acc[service] = { isLoggedIn: false };
return acc;
}, {}));
}
};
this.logout = function (service) {
_this.cleanup(service);
var accessToken = _this._accessToken;
if (accessToken) {
return fetchQuery(_this._fetchUrl, logoutMutation(service), accessToken).then(function (result) {
if (result.errors && result.errors.length && getServiceErrors(result.errors).length) {
return { result: 'failure', errors: result.errors };
} else {
var loggedIn = getIsLoggedIn({ data: result.signoutServices }, service);
return { result: loggedIn ? 'failure' : 'success' };
}
});
} else {
return Promise.resolve({ result: 'failure' });
}
};
this.destroy = function () {
Object.keys(_this._intervalIds).forEach(function (key) {
return _this.cleanup(key);
});
Object.keys(_this._authWindows).forEach(function (key) {
return _this.cleanup(key);
});
_this._storage.removeItem(_this._storageKey);
};
var appId = opts.appId,
oauthFinishOrigin = opts.oauthFinishOrigin,
oauthFinishPath = opts.oauthFinishPath;
this.oneGraphOrigin = opts.oneGraphOrigin || DEFAULT_ONEGRAPH_ORIGIN;
this.appId = appId;
this._redirectOrigin = normalizeRedirectOrigin(oauthFinishOrigin || window.location.origin);
if (this._redirectOrigin !== window.location.origin) {
console.warn('oauthFinishOrigin does not match window.location.origin');
}
this._redirectPath = normalizeRedirectPath(oauthFinishPath || window.location.pathname);
var fetchUrl = URI.make({
origin: opts.oneGraphOrigin || DEFAULT_ONEGRAPH_ORIGIN,
path: '/dynamic',
query: { app_id: appId }
});
this._fetchUrl = URI.toString(fetchUrl);
this._storage = opts.storage || (hasLocalStorage() ? new LocalStorage() : new InMemoryStorage());
this._storageKey = this.appId;
this._accessToken = tokenFromStorage(this._storage, this._storageKey);
}
createClass(OneGraphAuth, [{
key: 'friendlyServiceName',
value: function friendlyServiceName(service) {
return _friendlyServiceName(service);
}
}]);
return OneGraphAuth;
}();
var _extends$1 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
const AuthContext = React.createContext();
class AuthProvider extends React.Component {
constructor(...args) {
var _temp;
return _temp = super(...args), this.state = {
auth: null,
status: {},
headers: {}
}, this.login = (service, callback) => {
const { auth, status, headers } = this.state;
if (auth) {
auth.login(service).then(() => {
auth.isLoggedIn(service).then(isLoggedIn => {
callback && callback(isLoggedIn);
this.setState({
status: _extends$1({}, status, {
[service]: isLoggedIn
}),
headers: auth.authHeaders()
});
});
});
}
}, this.logout = (service, callback) => {
const { auth, status, headers } = this.state;
auth.logout(service).then(() => {
auth.isLoggedIn(service).then(isLoggedIn => {
callback && callback(isLoggedIn);
this.setState({
status: _extends$1({}, status, {
[service]: isLoggedIn
}),
headers: auth.authHeaders()
});
});
});
}, _temp;
}
componentDidMount() {
const auth = new OneGraphAuth({
appId: this.props.appId
});
window.auth = auth;
auth.servicesStatus().then(status => this.setState({
headers: auth.authHeaders(),
status: Object.keys(status).reduce((out, service) => {
out[service] = status[service].isLoggedIn;
return out;
}, {}),
auth
}));
}
render() {
const { appId, children } = this.props;
const { auth, status, headers } = this.state;
const authInterface = {
status,
headers,
login: this.login,
logout: this.logout,
appId
};
return React__default.createElement(
AuthContext.Provider,
{ value: authInterface },
this.props.children
);
}
}
const AuthConsumer = AuthContext.Consumer;
exports.AuthContext = AuthContext;
exports.AuthConsumer = AuthConsumer;
exports.AuthProvider = AuthProvider;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=bundle.umd.js.map