bito-code-review[bot] commented on code in PR #36933:
URL: https://github.com/apache/superset/pull/36933#discussion_r2894976205
##########
superset/security/manager.py:
##########
@@ -2834,6 +2838,17 @@ def validate_guest_token_resources(resources:
GuestTokenResources) -> None:
embedded =
EmbeddedDashboardDAO.find_by_id(str(resource["id"]))
if not embedded:
raise EmbeddedDashboardNotFoundError()
+ elif resource["type"] ==
GuestTokenResourceType.CHART_PERMALINK.value:
+ # Validate that the chart permalink exists
+ permalink_key = str(resource["id"])
+ try:
+ permalink_value =
GetExplorePermalinkCommand(permalink_key).run()
+ if not permalink_value:
+ raise EmbeddedChartPermalinkNotFoundError()
+ except EmbeddedChartPermalinkNotFoundError:
+ raise
+ except Exception:
+ raise EmbeddedChartPermalinkNotFoundError()
Review Comment:
<!-- Bito Reply -->
This question isn’t related to the pull request. I can only help with
questions about the PR’s code or comments.
##########
superset/embedded_chart/view.py:
##########
@@ -0,0 +1,116 @@
+# 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 logging
+from typing import Any, Callable, cast
+
+from flask import abort, current_app, request
+from flask_appbuilder import expose
+from flask_login import AnonymousUserMixin, login_user
+from flask_wtf.csrf import same_origin
+
+from superset import event_logger, is_feature_enabled
+from superset.commands.explore.permalink.get import GetExplorePermalinkCommand
+from superset.superset_typing import FlaskResponse
+from superset.utils import json
+from superset.views.base import BaseSupersetView, common_bootstrap_payload
+
+logger = logging.getLogger(__name__)
+
+
+class EmbeddedChartView(BaseSupersetView):
+ """Server-side rendering for embedded chart pages."""
+
+ route_base = "/embedded/chart"
+
+ @expose("/")
+ @event_logger.log_this_with_extra_payload
+ def embedded_chart(
+ self,
+ add_extra_log_payload: Callable[..., None] = lambda **kwargs: None,
+ ) -> FlaskResponse:
+ """
+ Server side rendering for the embedded chart page.
+ Expects ?permalink_key=xxx query parameter.
+ """
+ if not is_feature_enabled("EMBEDDABLE_CHARTS_MCP"):
+ abort(404)
+
+ # Get permalink_key from query params
+ permalink_key = request.args.get("permalink_key")
+ if not permalink_key:
+ logger.warning("Missing permalink_key in embedded chart request")
+ abort(404)
+
+ # Fetch permalink to get allowed_domains for referrer validation
+ try:
+ permalink_value = GetExplorePermalinkCommand(permalink_key).run()
+ except Exception:
+ logger.exception("Error fetching permalink for embedded chart")
+ permalink_value = None
+
+ if not permalink_value:
+ logger.warning("Permalink not found for embedded chart: %s",
permalink_key)
+ abort(404)
+
+ assert permalink_value is not None # for mypy
Review Comment:
<!-- Bito Reply -->
This question isn’t related to the pull request. I can only help with
questions about the PR’s code or comments.
##########
superset-frontend/webpack.config.js:
##########
@@ -300,6 +300,7 @@ const config = {
menu: addPreamble('src/views/menu.tsx'),
spa: addPreamble('/src/views/index.tsx'),
embedded: addPreamble('/src/embedded/index.tsx'),
+ embeddedChart: addPreamble('/src/embeddedChart/index.tsx'),
},
Review Comment:
<!-- Bito Reply -->
This question isn’t related to the pull request. I can only help with
questions about the PR’s code or comments.
##########
superset-frontend/src/dashboard/components/EmbeddedChartModal/index.tsx:
##########
@@ -0,0 +1,289 @@
+/**
+ * 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 { useCallback, useEffect, useState } from 'react';
+import { logging, makeApi, SupersetApiError, t } from '@superset-ui/core';
+import { styled, css, Alert } from '@apache-superset/core/ui';
+import {
+ Button,
+ FormItem,
+ InfoTooltip,
+ Input,
+ Modal,
+ Loading,
+ Form,
+ Space,
+} from '@superset-ui/core/components';
+import { useToasts } from 'src/components/MessageToasts/withToasts';
+import { Typography } from '@superset-ui/core/components/Typography';
+import { ModalTitleWithIcon } from 'src/components/ModalTitleWithIcon';
+
+type Props = {
+ chartId: number;
+ formData: Record<string, unknown>;
+ show: boolean;
+ onHide: () => void;
+};
+
+type EmbeddedChart = {
+ uuid: string;
+ allowed_domains: string[];
+ chart_id: number;
+ changed_on: string;
+};
+
+type EmbeddedApiPayload = { allowed_domains: string[] };
+
+const stringToList = (stringyList: string): string[] =>
+ stringyList.split(/(?:\s|,)+/).filter(x => x);
+
+const ButtonRow = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-end;
+`;
+
+export const ChartEmbedControls = ({ chartId, onHide }: Props) => {
+ const { addInfoToast, addDangerToast } = useToasts();
+ const [ready, setReady] = useState(true);
+ const [loading, setLoading] = useState(false);
+ const [embedded, setEmbedded] = useState<EmbeddedChart | null>(null);
+ const [allowedDomains, setAllowedDomains] = useState<string>('');
+ const [showDeactivateConfirm, setShowDeactivateConfirm] = useState(false);
+
+ const endpoint = `/api/v1/chart/${chartId}/embedded`;
+ const isDirty =
+ !embedded ||
+ stringToList(allowedDomains).join() !== embedded.allowed_domains.join();
+
+ const enableEmbedded = useCallback(() => {
+ setLoading(true);
+ makeApi<EmbeddedApiPayload, { result: EmbeddedChart }>({
+ method: 'POST',
+ endpoint,
+ })({
+ allowed_domains: stringToList(allowedDomains),
+ })
+ .then(
+ ({ result }) => {
+ setEmbedded(result);
+ setAllowedDomains(result.allowed_domains.join(', '));
+ addInfoToast(t('Changes saved.'));
+ },
+ err => {
+ logging.error(err);
+ addDangerToast(
+ t('Sorry, something went wrong. The changes could not be saved.'),
+ );
+ },
+ )
+ .finally(() => {
+ setLoading(false);
+ });
+ }, [endpoint, allowedDomains, addInfoToast, addDangerToast]);
+
+ const disableEmbedded = useCallback(() => {
+ setShowDeactivateConfirm(true);
+ }, []);
+
+ const confirmDeactivate = useCallback(() => {
+ setLoading(true);
+ makeApi<object>({ method: 'DELETE', endpoint })({})
+ .then(
+ () => {
+ setEmbedded(null);
+ setAllowedDomains('');
+ setShowDeactivateConfirm(false);
+ addInfoToast(t('Embedding deactivated.'));
+ onHide();
+ },
+ err => {
+ logging.error(err);
+ addDangerToast(
+ t(
+ 'Sorry, something went wrong. Embedding could not be
deactivated.',
+ ),
+ );
+ },
+ )
+ .finally(() => {
+ setLoading(false);
+ });
+ }, [endpoint, addInfoToast, addDangerToast, onHide]);
+
+ useEffect(() => {
+ setReady(false);
+ makeApi<object, { result: EmbeddedChart }>({
+ method: 'GET',
+ endpoint,
+ })({})
+ .catch(err => {
+ if ((err as SupersetApiError).status === 404) {
+ return { result: null };
+ }
+ addDangerToast(t('Sorry, something went wrong. Please try again.'));
+ throw err;
+ })
+ .then(({ result }) => {
+ setReady(true);
+ setEmbedded(result);
+ setAllowedDomains(result ? result.allowed_domains.join(', ') : '');
+ });
Review Comment:
<!-- Bito Reply -->
This question isn’t related to the pull request. I can only help with
questions about the PR’s code or comments.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]