Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[Enhancement] Demo App Cloud provider refactor (#831)

Ib Green9b5452300852
diff --git a/examples/demo-app/src/actions.js b/examples/demo-app/src/actions.js
index a5fe1106c..a47f7d137 100644
--- a/examples/demo-app/src/actions.js
+++ b/examples/demo-app/src/actions.js
@@ -28,7 +28,7 @@ import {
MAP_CONFIG_URL, MAP_URI
} from './constants/default-settings';
import {LOADING_METHODS_NAMES} from './constants/default-settings';
-import {CLOUD_PROVIDERS} from './utils/cloud-providers';
+import {getCloudProvider} from './cloud-providers';
import {generateHashId} from './utils/strings';
import {parseUri} from './utils/url';
import KeplerGlSchema from 'kepler.gl/schemas';
@@ -351,38 +351,51 @@ export function setPushingFile(isLoading, metadata) {
/**
* This method will export the current kepler config file to the choosen cloud platform
* @param data
- * @param handlerName
+ * @param providerName
* @returns {Function}
*/
-export function exportFileToCloud(handlerName = 'dropbox') {
- const authHandler = CLOUD_PROVIDERS[handlerName];
+export function exportFileToCloud(providerName) {
+ if (!providerName) {
+ throw new Error('No cloud provider identified')
+ }
+ const cloudProvider = getCloudProvider(providerName);
return (dispatch, getState) => {
// extract data from kepler
- const data = KeplerGlSchema.save(getState().demo.keplerGl.map);
- const newBlob = new Blob([JSON.stringify(data)], {type: 'application/json'});
+ const mapData = KeplerGlSchema.save(getState().demo.keplerGl.map);
+ const data = JSON.stringify(mapData);
+ const newBlob = new Blob([data], {type: 'application/json'});
const fileName = `/keplergl_${generateHashId(6)}.json`;
const file = new File([newBlob], fileName);
// We are gonna pass the correct auth token to init the cloud provider
dispatch(setPushingFile(true, {filename: file.name, status: 'uploading', metadata: null}));
- authHandler.uploadFile({blob: file, name: fileName, isPublic: true, authHandler})
+ cloudProvider.uploadFile({
+ data,
+ type: 'application/json',
+ blob: file,
+ name: fileName,
+ isPublic: true,
+ cloudProvider
+ })
// need to perform share as well
- .then(
- response => {
+ .then(
+ response => {
+ if (cloudProvider.shareFile) {
dispatch(push(`/${MAP_URI}${response.url}`));
- dispatch(setPushingFile(false, {filename: file.name, status: 'success', metadata: response}));
- },
- error => {
- dispatch(setPushingFile(false, {filename: file.name, status: 'error', error}));
}
- )
+ dispatch(setPushingFile(false, {filename: file.name, status: 'success', metadata: response}));
+ },
+ error => {
+ dispatch(setPushingFile(false, {filename: file.name, status: 'error', error}));
+ }
+ );
};
}
-export function setCloudLoginSuccess() {
+export function setCloudLoginSuccess(providerName) {
return dispatch => {
dispatch({type: CLOUD_LOGIN_SUCCESS}).then(
() => {
- dispatch(exportFileToCloud());
+ dispatch(exportFileToCloud(providerName));
},
() => {
dispatch(setPushingFile(false, {filename: null, status: 'error', error: 'not able to propagate login successfully'}));
diff --git a/examples/demo-app/src/app.js b/examples/demo-app/src/app.js
index a2c47694c..899812eeb 100644
--- a/examples/demo-app/src/app.js
+++ b/examples/demo-app/src/app.js
@@ -99,7 +99,7 @@ class App extends Component {
height: window.innerHeight
};
- componentWillMount() {
+ UNSAFE_componentWillMount() {
// if we pass an id as part of the url
// we ry to fetch along map configurations
const {
@@ -279,12 +279,12 @@ class App extends Component {
});
};
- _onExportToCloud = () => {
- this.props.dispatch(exportFileToCloud());
+ _onExportToCloud = (providerName) => {
+ this.props.dispatch(exportFileToCloud(providerName));
};
- _onCloudLoginSuccess = () => {
- this.props.dispatch(setCloudLoginSuccess());
+ _onCloudLoginSuccess = (providerName) => {
+ this.props.dispatch(setCloudLoginSuccess(providerName));
};
_getMapboxRef = (mapbox, index) => {
diff --git a/examples/demo-app/src/cloud-providers/dropbox-provider.js b/examples/demo-app/src/cloud-providers/dropbox-provider.js
new file mode 100644
index 000000000..3be7ea63a
--- /dev/null
+++ b/examples/demo-app/src/cloud-providers/dropbox-provider.js
@@ -0,0 +1,164 @@
+// Copyright (c) 2019 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+// DROPBOX
+import {Dropbox} from 'dropbox';
+import window from 'global/window';
+import {parseQueryString} from '../utils/url';
+import DropboxIcon from '../components/icons/dropbox-icon';
+
+const NAME = 'dropbox';
+const DOMAIN = 'www.dropbox.com';
+const KEPLER_DROPBOX_FOLDER_LINK = `//${DOMAIN}/home/Apps`;
+const CORS_FREE_DOMAIN = 'dl.dropboxusercontent.com';
+
+export default class DropboxProvider {
+ constructor(clientId, appName, icon = DropboxIcon) {
+ // All cloud-providers providers must implement the following properties
+ this.name = NAME;
+ this.clientId = clientId;
+ this.appName = appName;
+ this.icon = icon;
+
+ this._folderLink = `${KEPLER_DROPBOX_FOLDER_LINK}/${appName}`;
+
+ // Initialize Dropbox API
+ this._dropbox = new Dropbox({fetch: window.fetch});
+ this._dropbox.setClientId(clientId);
+ }
+
+ /**
+ * This method will handle the oauth flow by performing the following steps:
+ * - Opening a new window
+ * - Subscribe to message channel
+ * - Receive the token when ready
+ * - Close the opened tab
+ */
+ login(onCloudLoginSuccess) {
+ const link = this._authLink();
+ const authWindow = window.open(link, '_blank', 'width=1024,height=716');
+ const handleToken = e => {
+ // TODO: add security step to validate which domain the message is coming from
+ authWindow.close();
+ window.removeEventListener('message', handleToken);
+ this._dropbox.setAccessToken(e.data.token);
+ if (window.localStorage) {
+ window.localStorage.setItem('dropbox', JSON.stringify({
+ // dropbox token doesn't expire unless revoked by the user
+ token: e.data.token,
+ timestamp: new Date()
+ }));
+ }
+ onCloudLoginSuccess(this.name);
+ };
+ window.addEventListener('message', handleToken);
+ }
+
+ /**
+ *
+ * @param blob to upload
+ * @param name if blob doesn't contain a file name, this field is used
+ * @param isPublic define whether the file will be available pubblicaly once uploaded
+ * @returns {Promise<DropboxTypes.files.FileMetadata>}
+ */
+ async uploadFile({blob, name, isPublic = true}) {
+ const metadata = await this._dropbox.filesUpload({
+ path: name || blob.name,
+ contents: blob
+ });
+
+ return isPublic ? await this.shareFile(metadata) : metadata;
+ }
+
+ /**
+ * It will set access to file to public
+ * @param {Object} metadata metadata response from uploading the file
+ * @returns {Promise<DropboxTypes.sharing.FileLinkMetadataReference | DropboxTypes.sharing.FolderLinkMetadataReference | DropboxTypes.sharing.SharedLinkMetadataReference>}
+ */
+ shareFile(metadata) {
+ return this._dropbox.sharingCreateSharedLinkWithSettings({
+ path: metadata.path_display || metadata.path_lower
+ }).then(
+ // Update URL to avoid CORS issue
+ // Unfortunately this is not the ideal scenario but it will make sure people
+ // can share dropbox urls with users without the dropbox account (publish on twitter, facebook)
+ result => ({
+ ...result,
+ folder_link: this._folderLink,
+ url: this._overrideUrl(result.url)
+ })
+ );
+ }
+
+ /**
+ * Provides the current dropbox auth token. If stored in localStorage is set onto dropbox handler and returned
+ * @returns {any}
+ */
+ getAccessToken() {
+ let token = this._dropbox.getAccessToken();
+ if (!token && window.localStorage) {
+ const jsonString = window.localStorage.getItem('dropbox');
+ token = jsonString && JSON.parse(jsonString).token;
+ if (token) {
+ this._dropbox.setAccessToken(token);
+ }
+ }
+ return (token || '') !== '' ? token : null;
+ }
+
+ /**
+ * This method will extract the auth token from the third party service callback url.
+ * @param {object} location the window location provided by react router
+ * @returns {?string} the token extracted from the oauth 2 callback URL
+ */
+ getAccessTokenFromLocation(location) {
+ if (!(location && location.hash.length)) {
+ return null;
+ }
+ // dropbox token usually start with # therefore we want to remore the '#'
+ const query = window.location.hash.substring(1);
+ return parseQueryString(query).access_token;
+ }
+
+ // PRIVATE
+
+ /**
+ * Generate auth link url to open to be used to handle OAuth2
+ * @param {string} path
+ */
+ _authLink(path = 'auth') {
+ return this._dropbox.getAuthenticationUrl(
+ `${window.location.origin}/${path}`,
+ btoa(JSON.stringify({handler: 'dropbox', origin: window.location.origin}))
+ )
+ }
+
+ /**
+ * Override dropbox cloud-providers url
+ * https://www.dropbox.com/s/bxwwdb81z0jg7pb/keplergl_2018-11-01T23%3A22%3A43.940Z.json?dl=0
+ * ->
+ * https://dl.dropboxusercontent.com/s/bxwwdb81z0jg7pb/keplergl_2018-11-01T23%3A22%3A43.940Z.json
+ * @param metadata
+ * @returns {DropboxTypes.sharing.FileLinkMetadataReference}
+ */
+ _overrideUrl(url) {
+ return url ? url.slice(0, url.indexOf('?')).replace(DOMAIN, CORS_FREE_DOMAIN) : null;
+ }
+}
diff --git a/examples/demo-app/src/utils/cloud-providers/index.js b/examples/demo-app/src/cloud-providers/index.js
similarity index 75%
rename from examples/demo-app/src/utils/cloud-providers/index.js
rename to examples/demo-app/src/cloud-providers/index.js
index 14c280a48..4acc581e6 100644
--- a/examples/demo-app/src/utils/cloud-providers/index.js
+++ b/examples/demo-app/src/cloud-providers/index.js
@@ -18,12 +18,16 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-import DropboxHandler from './dropbox';
-import {AUTH_TOKENS} from '../../constants/default-settings';
+import {CLOUD_PROVIDERS} from './providers';
-// configure all clients with the right configuration
-DropboxHandler.setAuthToken(AUTH_TOKENS.DROPBOX_CLIEND_ID);
+export function getCloudProviders() {
+ return CLOUD_PROVIDERS;
+}
-export const CLOUD_PROVIDERS = {
- [DropboxHandler.name]: DropboxHandler
-};
+export function getCloudProvider(providerName) {
+ const cloudProvider = CLOUD_PROVIDERS.find(provider => provider.name === providerName);
+ if (!cloudProvider) {
+ throw new Error(`Unknown cloud provider ${providerName}`)
+ }
+ return cloudProvider;
+}
diff --git a/examples/demo-app/src/cloud-providers/providers.js b/examples/demo-app/src/cloud-providers/providers.js
new file mode 100644
index 000000000..7ba437ac1
--- /dev/null
+++ b/examples/demo-app/src/cloud-providers/providers.js
@@ -0,0 +1,30 @@
+// Copyright (c) 2019 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import {AUTH_TOKENS} from '../constants/default-settings';
+
+import DropboxProvider from './dropbox-provider';
+
+const {DROPBOX_CLIENT_ID} = AUTH_TOKENS;
+const DROPBOX_CLIENT_NAME = 'Kepler.gl%20(managed%20by%20Uber%20Technologies%2C%20Inc.)';
+
+export const CLOUD_PROVIDERS = [
+ new DropboxProvider(DROPBOX_CLIENT_ID, DROPBOX_CLIENT_NAME)
+];
diff --git a/examples/demo-app/src/components/sharing/cloud-storage.js b/examples/demo-app/src/components/sharing/cloud-storage.js
index 6cb6efc79..2bdaa4076 100644
--- a/examples/demo-app/src/components/sharing/cloud-storage.js
+++ b/examples/demo-app/src/components/sharing/cloud-storage.js
@@ -25,7 +25,7 @@ import {CopyToClipboard} from 'react-copy-to-clipboard';
import {StyledModalContent} from 'kepler.gl/components';
import CloudTile from './cloud-tile';
import StatusPanel from './status-panel';
-import {CLOUD_PROVIDERS} from '../../utils/cloud-providers';
+import {getCloudProviders} from '../../cloud-providers';
import {KEPLER_DISCLAIMER} from '../../constants/default-settings';
import {getMapPermalink} from '../../utils/url';
@@ -133,17 +133,18 @@ const ExportCloudModal = ({
<StyledExportDataSection>
<div className="description">
<div className="title">
- Upload through Dropbox
+ Upload to your cloud storage
</div>
</div>
<div className="selection">
- {Object.keys(CLOUD_PROVIDERS).map((name, index) => (
+ {getCloudProviders().map(cloudProvider => (
<CloudTile
- key={index}
- token={CLOUD_PROVIDERS[name].getAccessToken()}
+ key={cloudProvider.name}
+ token={cloudProvider.getAccessToken()}
onExport={onExport}
- onLogin={() => CLOUD_PROVIDERS[name].handleLogin(onCloudLoginSuccess)}
- Icon={CLOUD_PROVIDERS[name].icon}
+ onLogin={() => cloudProvider.login(onCloudLoginSuccess)}
+ Icon={cloudProvider.icon}
+ name={cloudProvider.name}
/>
))}
</div>
diff --git a/examples/demo-app/src/components/sharing/cloud-tile.js b/examples/demo-app/src/components/sharing/cloud-tile.js
index efa76c693..b9995e279 100644
--- a/examples/demo-app/src/components/sharing/cloud-tile.js
+++ b/examples/demo-app/src/components/sharing/cloud-tile.js
@@ -18,7 +18,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-import React from 'react';
+import React, {useCallback} from 'react';
import styled from 'styled-components';
const StyledTileWrapper = styled.div`
@@ -63,11 +63,14 @@ const TileButton = styled.button`
outline: 0;
`;
-const CloudTile = ({token, onExport, onLogin, Icon}) => {
+const CloudTile = ({token, onExport, onLogin, Icon, name}) => {
+ const onExportCallback = useCallback(() => onExport(name), [onExport, name]);
+
return (
- <StyledTileWrapper onClick={token ? onExport : onLogin}>
+ <StyledTileWrapper onClick={token ? onExportCallback : onLogin}>
<StyledTile>
<div>
+ <div style={{textAlign: 'center'}}>{name}</div>
<TileButton>
<Icon height="64px" />
<StyledLabel>{token ? 'Upload' : 'Login'}</StyledLabel>
diff --git a/examples/demo-app/src/constants/default-settings.js b/examples/demo-app/src/constants/default-settings.js
index f4b1ec447..3ce75eeba 100644
--- a/examples/demo-app/src/constants/default-settings.js
+++ b/examples/demo-app/src/constants/default-settings.js
@@ -95,7 +95,7 @@ export const LOADING_SAMPLE_ERROR_MESSAGE = 'Not able to load sample';
export const LOADING_URL_MESSAGE = 'You can use the following formats: CSV | JSON | Kepler.gl config json. Make sure the url contains the file extension.';
export const CORS_LINK = 'https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS';
export const KEPLER_DISCLAIMER = '* Kepler.gl will save your map data to your personal cloud storage, only people with the URL can access your map and data. ' +
- 'You can edit/delete the data file in your Dropbox account anytime.';
+ 'You can edit/delete the data file in your cloud account anytime.';
export const DEFAULT_LOADING_METHOD = LOADING_METHODS[0];
@@ -107,6 +107,6 @@ export const DEFAULT_FEATURE_FLAGS = {
export const AUTH_TOKENS = {
MAPBOX_TOKEN: process.env.MapboxAccessToken, // eslint-disable-line
- DROPBOX_CLIEND_ID: process.env.DropboxClientId, // eslint-disable-line
+ DROPBOX_CLIENT_ID: process.env.DropboxClientId, // eslint-disable-line
EXPORT_MAPBOX_TOKEN: process.env.MapboxExportToken, // eslint-disable-line
};
diff --git a/examples/demo-app/src/reducers/sharing.js b/examples/demo-app/src/reducers/sharing.js
index 4613db490..02f6dae47 100644
--- a/examples/demo-app/src/reducers/sharing.js
+++ b/examples/demo-app/src/reducers/sharing.js
@@ -19,13 +19,13 @@
// THE SOFTWARE.
import {handleActions} from 'redux-actions';
-import {CLOUD_PROVIDERS} from '../utils/cloud-providers';
+import {getCloudProviders} from '../cloud-providers';
import {CLOUD_LOGIN_SUCCESS, LOAD_REMOTE_RESOURCE_ERROR, PUSHING_FILE} from '../actions';
-const readAuthTokens = () => Object.keys(CLOUD_PROVIDERS)
- .reduce((tokens, name) => ({
+const readAuthTokens = () => getCloudProviders()
+ .reduce((tokens, cloudProvider) => ({
...tokens,
- [name]: CLOUD_PROVIDERS[name].getAccessToken()
+ [cloudProvider.name]: cloudProvider.getAccessToken()
}), {});
const sharingInitialState = {
diff --git a/examples/demo-app/src/utils/cloud-providers/dropbox.js b/examples/demo-app/src/utils/cloud-providers/dropbox.js
deleted file mode 100644
index a45b5f33e..000000000
--- a/examples/demo-app/src/utils/cloud-providers/dropbox.js
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright (c) 2019 Uber Technologies, Inc.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-// DROPBOX
-import {Dropbox} from 'dropbox';
-import window from 'global/window';
-import {parseQueryString} from '../url';
-import DropboxIcon from '../../components/icons/dropbox-icon';
-
-const NAME = 'dropbox';
-const DOMAIN = 'www.dropbox.com';
-const APP_NAME= 'Kepler.gl%20(managed%20by%20Uber%20Technologies%2C%20Inc.)';
-const KEPLER_DROPBOX_FOLDER_LINK = `//${DOMAIN}/home/Apps/${APP_NAME}`;
-const CORS_FREE_DOMAIN = 'dl.dropboxusercontent.com';
-const dropbox = new Dropbox({fetch: window.fetch});
-
-/**
- * Set the auth toke to be used with dropbox client
- * @param authToken
- */
-function setAuthToken(authToken) {
- if (dropbox.getClientId()) {
- return;
- }
- dropbox.setClientId(authToken);
-}
-
-/**
- * Generate auth link url to open to be used to handle OAuth2
- * @param {string} path
- */
-function authLink(path = 'auth') {
- return dropbox.getAuthenticationUrl(
- `${window.location.origin}/${path}`,
- btoa(JSON.stringify({handler: 'dropbox', origin: window.location.origin}))
- )
-}
-
-/**
- * This method will extract the atuch token from the third party service callback url. Default: Dropbox
- * @param {object} location the window location provided by react router
- * @returns {?string} the token extracted from the oauth 2 callback URL
- */
-function getAccessTokenFromLocation(location) {
- if (!(location && location.hash.length)) {
- return null;
- }
- // dropbox token usually start with # therefore we want to remore the '#'
- const query = window.location.hash.substring(1);
-
- return parseQueryString(query).access_token;
-}
-
-/**
- *
- * @param blob to upload
- * @param name if blob doesn't contain a file name, this field is used
- * @param isPublic define whether the file will be available pubblicaly once uploaded
- * @returns {Promise<DropboxTypes.files.FileMetadata>}
- */
-function uploadFile({blob, name, isPublic = true}) {
- const promise = dropbox.filesUpload({
- path: name || blob.name,
- contents: blob
- });
-
- return !isPublic ? promise : promise.then(shareFile);
-}
-
-/**
- * It will set access to file to public
- * @param {Object} metadata metadata response from uploading the file
- * @returns {Promise<DropboxTypes.sharing.FileLinkMetadataReference | DropboxTypes.sharing.FolderLinkMetadataReference | DropboxTypes.sharing.SharedLinkMetadataReference>}
- */
-function shareFile(metadata) {
- return dropbox.sharingCreateSharedLinkWithSettings({
- path: metadata.path_display || metadata.path_lower
- }).then(
- // Update URL to avoid CORS issue
- // Unfortunately this is not the ideal scenario but it will make sure people
- // can share dropbox urls with users without the dropbox account (publish on twitter, facebook)
- result => ({
- ...result,
- folder_link: KEPLER_DROPBOX_FOLDER_LINK,
- url: overrideUrl(result.url)
- })
- );
-}
-
-/**
- * Override dropbox cloud-providers url
- * https://www.dropbox.com/s/bxwwdb81z0jg7pb/keplergl_2018-11-01T23%3A22%3A43.940Z.json?dl=0
- * ->
- * https://dl.dropboxusercontent.com/s/bxwwdb81z0jg7pb/keplergl_2018-11-01T23%3A22%3A43.940Z.json
- * @param metadata
- * @returns {DropboxTypes.sharing.FileLinkMetadataReference}
- */
-function overrideUrl(url) {
- return url ? url.slice(0, url.indexOf('?')).replace(DOMAIN, CORS_FREE_DOMAIN) : null;
-}
-
-/**
- * This method will handle the oauth flow by performing the following steps:
- * - Opening a new window
- * - Subscribe to message channel
- * - Receive the token when ready
- * - Close the opened tab
- */
-function handleLogin(onCloudLoginSuccess) {
- const link = authLink();
- const authWindow = window.open(link, '_blank', 'width=1024,height=716');
- const handleToken = e => {
- // TODO: add security step to validate which domain the message is coming from
- authWindow.close();
- window.removeEventListener('message', handleToken);
- dropbox.setAccessToken(e.data.token);
- if (window.localStorage) {
- window.localStorage.setItem('dropbox', JSON.stringify({
- // dropbox token doesn't expire unless revoked by the user
- token: e.data.token,
- timetamp: new Date()
- }));
- }
- onCloudLoginSuccess();
- };
- window.addEventListener('message', handleToken);
-}
-
-/**
- * Provides the current dropbox auth token. If stored in localStorage is set onto dropbox handler and returned
- * @returns {any}
- */
-function getAccessToken() {
- let token = dropbox.getAccessToken();
- if (!token && window.localStorage) {
- const jsonString = window.localStorage.getItem('dropbox');
- token = jsonString && JSON.parse(jsonString).token;
- if (token) {
- dropbox.setAccessToken(token);
- }
- }
-
- return (token || '') !== '' ? token : null;
-}
-
-// All cloud-providers providers must implement the following properties
-export default {
- name: NAME,
- getAccessToken,
- getAccessTokenFromLocation,
- handleLogin,
- icon: DropboxIcon,
- setAuthToken,
- uploadFile
-};
diff --git a/examples/demo-app/src/utils/routes.js b/examples/demo-app/src/utils/routes.js
index 0d6c1d675..38126733f 100644
--- a/examples/demo-app/src/utils/routes.js
+++ b/examples/demo-app/src/utils/routes.js
@@ -18,7 +18,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-import {CLOUD_PROVIDERS} from './cloud-providers';
+import {getCloudProvider} from '../cloud-providers';
import {IndexRoute, Route} from 'react-router';
import React from 'react';
import Demo from '../app';
@@ -26,7 +26,7 @@ import {DEFAULT_CLOUD_PROVIDER} from '../constants/default-settings';
export function onAuthEnterCallback(nextState, replace, callback) {
// TODO: detect auth provider
- const authProvider = CLOUD_PROVIDERS[DEFAULT_CLOUD_PROVIDER];
+ const authProvider = getCloudProvider(DEFAULT_CLOUD_PROVIDER);
// Check if the current tab was opened by our previous tab
if (window.opener) {