Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: entry for embedded dashboard #17529

Merged
merged 22 commits into from
Jan 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import SupersetClientClass from './SupersetClientClass';
import { SupersetClientInterface } from './types';

// this is local to this file, don't expose it
let singletonClient: SupersetClientClass | undefined;

function getInstance(): SupersetClientClass {
Expand All @@ -39,7 +40,6 @@ const SupersetClient: SupersetClientInterface = {
reset: () => {
singletonClient = undefined;
},
getInstance,
delete: request => getInstance().delete(request),
get: request => getInstance().get(request),
init: force => getInstance().init(force),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ export default class SupersetClientClass {

csrfPromise?: CsrfPromise;

guestToken?: string;

guestTokenHeaderName: string;

fetchRetryOptions?: FetchRetryOptions;

baseUrl: string;
Expand All @@ -64,6 +68,8 @@ export default class SupersetClientClass {
timeout,
credentials = undefined,
csrfToken = undefined,
guestToken = undefined,
guestTokenHeaderName = 'X-GuestToken',
}: ClientConfig = {}) {
const url = new URL(
host || protocol
Expand All @@ -81,6 +87,8 @@ export default class SupersetClientClass {
this.timeout = timeout;
this.credentials = credentials;
this.csrfToken = csrfToken;
this.guestToken = guestToken;
this.guestTokenHeaderName = guestTokenHeaderName;
this.fetchRetryOptions = {
...DEFAULT_FETCH_RETRY_OPTIONS,
...fetchRetryOptions,
Expand All @@ -89,6 +97,9 @@ export default class SupersetClientClass {
this.headers = { ...this.headers, 'X-CSRFToken': this.csrfToken };
this.csrfPromise = Promise.resolve(this.csrfToken);
}
if (guestToken) {
this.headers[guestTokenHeaderName] = guestToken;
}
}

async init(force = false): CsrfPromise {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ export interface ClientConfig {
protocol?: Protocol;
credentials?: Credentials;
csrfToken?: CsrfToken;
guestToken?: string;
guestTokenHeaderName?: string;
fetchRetryOptions?: FetchRetryOptions;
headers?: Headers;
mode?: Mode;
Expand All @@ -149,7 +151,6 @@ export interface SupersetClientInterface
| 'reAuthenticate'
> {
configure: (config?: ClientConfig) => SupersetClientClass;
getInstance: (maybeClient?: SupersetClientClass) => SupersetClientClass;
reset: () => void;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export enum FeatureFlag {
DASHBOARD_CROSS_FILTERS = 'DASHBOARD_CROSS_FILTERS',
DASHBOARD_NATIVE_FILTERS_SET = 'DASHBOARD_NATIVE_FILTERS_SET',
DASHBOARD_FILTERS_EXPERIMENTAL = 'DASHBOARD_FILTERS_EXPERIMENTAL',
EMBEDDED_SUPERSET = 'EMBEDDED_SUPERSET',
ENABLE_FILTER_BOX_MIGRATION = 'ENABLE_FILTER_BOX_MIGRATION',
VERSIONED_EXPORT = 'VERSIONED_EXPORT',
GLOBAL_ASYNC_QUERIES = 'GLOBAL_ASYNC_QUERIES',
Expand Down
117 changes: 117 additions & 0 deletions superset-frontend/src/embedded/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { lazy, Suspense } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { bootstrapData } from 'src/preamble';
import setupClient from 'src/setup/setupClient';
import { RootContextProviders } from 'src/views/RootContextProviders';
import ErrorBoundary from 'src/components/ErrorBoundary';
import Loading from 'src/components/Loading';

const LazyDashboardPage = lazy(
() =>
import(
/* webpackChunkName: "DashboardPage" */ 'src/dashboard/containers/DashboardPage'
),
);

const EmbeddedApp = () => (
<Router>
<Route path="/superset/dashboard/:idOrSlug/embedded">
<Suspense fallback={<Loading />}>
<RootContextProviders>
<ErrorBoundary>
<LazyDashboardPage />
</ErrorBoundary>
</RootContextProviders>
</Suspense>
</Route>
</Router>
);

const appMountPoint = document.getElementById('app')!;

const MESSAGE_TYPE = '__embedded_comms__';

if (!window.parent) {
appMountPoint.innerHTML =
'This page is intended to be embedded in an iframe, but no window.parent was found.';
}

// if the page is embedded in an origin that hasn't
// been authorized by the curator, we forbid access entirely.
// todo: check the referrer on the route serving this page instead
// const ALLOW_ORIGINS = ['http://127.0.0.1:9001', 'http://localhost:9001'];
// const parentOrigin = new URL(document.referrer).origin;
// if (!ALLOW_ORIGINS.includes(parentOrigin)) {
// throw new Error(
// `[superset] iframe parent ${parentOrigin} is not in the list of allowed origins`,
// );
// }

async function start(guestToken: string) {
// the preamble configures a client, but we need to configure a new one
// now that we have the guest token
setupClient({
guestToken,
suddjian marked this conversation as resolved.
Show resolved Hide resolved
guestTokenHeaderName: bootstrapData.config?.GUEST_TOKEN_HEADER_NAME,
});
ReactDOM.render(<EmbeddedApp />, appMountPoint);
}

function validateMessageEvent(event: MessageEvent) {
if (
event.data?.type === 'webpackClose' ||
event.data?.source === '@devtools-page'
) {
// sometimes devtools use the messaging api and we want to ignore those
throw new Error("Sir, this is a Wendy's");
}

// if (!ALLOW_ORIGINS.includes(event.origin)) {
// throw new Error('Message origin is not in the allowed list');
// }

if (typeof event.data !== 'object' || event.data.type !== MESSAGE_TYPE) {
throw new Error(`Message type does not match type used for embedded comms`);
}
}

window.addEventListener('message', function (event) {
try {
validateMessageEvent(event);
} catch (err) {
console.info('[superset] ignoring message', err, event);
return;
}

console.info('[superset] received message', event);
const hostAppPort = event.ports?.[0];
if (hostAppPort) {
hostAppPort.onmessage = function receiveMessage(event) {
console.info('[superset] received message event', event.data);
if (event.data.guestToken) {
start(event.data.guestToken);
}
};
}
});

console.info('[superset] embed page is ready to receive messages');
4 changes: 2 additions & 2 deletions superset-frontend/src/preamble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ if (process.env.WEBPACK_MODE === 'development') {
setHotLoaderConfig({ logLevel: 'debug', trackTailUpdates: false });
}

let bootstrapData: any;
// eslint-disable-next-line import/no-mutable-exports
export let bootstrapData: any;
// Configure translation
if (typeof window !== 'undefined') {
const root = document.getElementById('app');

bootstrapData = root
? JSON.parse(root.getAttribute('data-bootstrap') || '{}')
: {};
Expand Down
13 changes: 10 additions & 3 deletions superset-frontend/src/setup/setupClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,29 @@
* specific language governing permissions and limitations
* under the License.
*/
import { SupersetClient, logging } from '@superset-ui/core';
import { SupersetClient, logging, ClientConfig } from '@superset-ui/core';
import parseCookie from 'src/utils/parseCookie';

export default function setupClient() {
function getDefaultConfiguration(): ClientConfig {
const csrfNode = document.querySelector<HTMLInputElement>('#csrf_token');
const csrfToken = csrfNode?.value;

// when using flask-jwt-extended csrf is set in cookies
const cookieCSRFToken = parseCookie().csrf_access_token || '';

SupersetClient.configure({
return {
protocol: ['http:', 'https:'].includes(window?.location?.protocol)
? (window?.location?.protocol as 'http:' | 'https:')
: undefined,
host: (window.location && window.location.host) || '',
csrfToken: csrfToken || cookieCSRFToken,
};
}

export default function setupClient(customConfig: Partial<ClientConfig> = {}) {
SupersetClient.configure({
...getDefaultConfiguration(),
...customConfig,
})
.init()
.catch(error => {
Expand Down
46 changes: 8 additions & 38 deletions superset-frontend/src/views/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,42 +18,31 @@
*/
import React, { Suspense, useEffect } from 'react';
import { hot } from 'react-hot-loader/root';
import { Provider as ReduxProvider } from 'react-redux';
import {
BrowserRouter as Router,
Switch,
Route,
useLocation,
} from 'react-router-dom';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { QueryParamProvider } from 'use-query-params';
import { initFeatureFlags } from 'src/featureFlags';
import { ThemeProvider } from '@superset-ui/core';
import { DynamicPluginProvider } from 'src/components/DynamicPlugins';
import { EmbeddedUiConfigProvider } from 'src/components/UiConfigContext';
import ErrorBoundary from 'src/components/ErrorBoundary';
import Loading from 'src/components/Loading';
import Menu from 'src/views/components/Menu';
import FlashProvider from 'src/components/FlashProvider';
import { theme } from 'src/preamble';
import { bootstrapData } from 'src/preamble';
import ToastContainer from 'src/components/MessageToasts/ToastContainer';
import setupApp from 'src/setup/setupApp';
import { routes, isFrontendRoute } from 'src/views/routes';
import { Logger } from 'src/logger/LogUtils';
import { store } from './store';
import { RootContextProviders } from './RootContextProviders';

setupApp();

const container = document.getElementById('app');
const bootstrap = JSON.parse(container?.getAttribute('data-bootstrap') ?? '{}');
const user = { ...bootstrap.user };
const menu = { ...bootstrap.common.menu_data };
const common = { ...bootstrap.common };
const user = { ...bootstrapData.user };
const menu = { ...bootstrapData.common.menu_data };
let lastLocationPathname: string;
initFeatureFlags(bootstrap.common.feature_flags);
initFeatureFlags(bootstrapData.common.feature_flags);

const RootContextProviders: React.FC = ({ children }) => {
const LocationPathnameLogger = () => {
const location = useLocation();
useEffect(() => {
// reset performance logger timer start point to avoid soft navigation
Expand All @@ -63,31 +52,12 @@ const RootContextProviders: React.FC = ({ children }) => {
}
lastLocationPathname = location.pathname;
}, [location.pathname]);

return (
<ThemeProvider theme={theme}>
<ReduxProvider store={store}>
<DndProvider backend={HTML5Backend}>
<FlashProvider messages={common.flash_messages}>
<EmbeddedUiConfigProvider>
<DynamicPluginProvider>
<QueryParamProvider
ReactRouterRoute={Route}
stringifyOptions={{ encode: false }}
>
{children}
</QueryParamProvider>
</DynamicPluginProvider>
</EmbeddedUiConfigProvider>
</FlashProvider>
</DndProvider>
</ReduxProvider>
</ThemeProvider>
);
return <></>;
};

const App = () => (
<Router>
<LocationPathnameLogger />
<RootContextProviders>
<Menu data={menu} isFrontendRoute={isFrontendRoute} />
<Switch>
Expand Down
55 changes: 55 additions & 0 deletions superset-frontend/src/views/RootContextProviders.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import React from 'react';
import { Route } from 'react-router-dom';
import { ThemeProvider } from '@superset-ui/core';
import { Provider as ReduxProvider } from 'react-redux';
import { QueryParamProvider } from 'use-query-params';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

import { store } from './store';
import FlashProvider from '../components/FlashProvider';
import { bootstrapData, theme } from '../preamble';
import { EmbeddedUiConfigProvider } from '../components/UiConfigContext';
import { DynamicPluginProvider } from '../components/DynamicPlugins';

const common = { ...bootstrapData.common };

export const RootContextProviders: React.FC = ({ children }) => (
<ThemeProvider theme={theme}>
<ReduxProvider store={store}>
<DndProvider backend={HTML5Backend}>
<FlashProvider messages={common.flash_messages}>
<EmbeddedUiConfigProvider>
<DynamicPluginProvider>
<QueryParamProvider
ReactRouterRoute={Route}
stringifyOptions={{ encode: false }}
>
{children}
</QueryParamProvider>
</DynamicPluginProvider>
</EmbeddedUiConfigProvider>
</FlashProvider>
</DndProvider>
</ReduxProvider>
</ThemeProvider>
);
1 change: 1 addition & 0 deletions superset-frontend/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ const config = {
theme: path.join(APP_DIR, '/src/theme.ts'),
menu: addPreamble('src/views/menu.tsx'),
spa: addPreamble('/src/views/index.tsx'),
embedded: addPreamble('/src/embedded/index.tsx'),
addSlice: addPreamble('/src/addSlice/index.tsx'),
explore: addPreamble('/src/explore/index.jsx'),
sqllab: addPreamble('/src/SqlLab/index.tsx'),
Expand Down
2 changes: 1 addition & 1 deletion superset/templates/superset/spa.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@
{% endblock %}

{% block tail_js %}
{{ js_bundle("spa") }}
{{ js_bundle(entry) }}
{% include "tail_js_custom_extra.html" %}
{% endblock %}
Loading