Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

fix(embed-js, sdk): Properly handle restricted collection access in MetabaseBrowser (#67523)

Timofey Kachalov88684d3b2cf6
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/metabase-browser.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/metabase-browser.cy.spec.ts
new file mode 100644
index 00000000000..47a5089db33
--- /dev/null
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/metabase-browser.cy.spec.ts
@@ -0,0 +1,176 @@
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { DATA_GROUP_ID } from "e2e/support/cypress_sample_instance_data";
+import type { CollectionPermission } from "metabase-types/api";
+
+const { H } = cy;
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+const READ: CollectionPermission = "read";
+const NONE: CollectionPermission = "none";
+
+const setupEmbed = (elementHtml: string) => {
+ H.visitCustomHtmlPage(`
+ ${H.getNewEmbedScriptTag()}
+ ${H.getNewEmbedConfigurationScript({})}
+ ${elementHtml}
+ `);
+};
+
+describe("scenarios > embedding > sdk iframe embedding > metabase-browser", () => {
+ describe("collection permissions", () => {
+ it("should show an error when initial-collection points to a collection the user has no access to", () => {
+ H.prepareSdkIframeEmbedTest({
+ withToken: "bleeding-edge",
+ signOut: false,
+ });
+
+ H.createCollection({
+ name: "Restricted Collection",
+ }).then(({ body: collection }) => {
+ cy.updateCollectionGraph({
+ [DATA_GROUP_ID]: {
+ root: READ,
+ [collection.id]: NONE,
+ },
+ });
+
+ cy.signIn("nocollection");
+
+ setupEmbed(`
+ <metabase-browser
+ initial-collection="${collection.id}"
+ read-only="false"
+ />
+ `);
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.findByText("You don't have access to this collection").should(
+ "be.visible",
+ );
+ cy.findByText("New exploration").should("not.exist");
+ });
+ });
+ });
+
+ it("should not show New exploration button when user has no curate permissions on initial-collection", () => {
+ H.prepareSdkIframeEmbedTest({
+ withToken: "bleeding-edge",
+ signOut: false,
+ });
+
+ H.createCollection({
+ name: "Read Only Collection",
+ }).then(({ body: collection }) => {
+ cy.updateCollectionGraph({
+ [DATA_GROUP_ID]: {
+ root: READ,
+ [collection.id]: READ,
+ },
+ });
+
+ H.createQuestion({
+ name: "Test Question",
+ query: { "source-table": ORDERS_ID },
+ collection_id: collection.id,
+ });
+
+ cy.signIn("nocollection");
+
+ setupEmbed(`
+ <metabase-browser
+ initial-collection="${collection.id}"
+ read-only="false"
+ />
+ `);
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ // User can see the collection contents (they have read access)
+ cy.findByText("Test Question").should("be.visible");
+
+ // But New exploration button should be hidden since they can't save
+ cy.findByText("New exploration").should("not.exist");
+ });
+ });
+ });
+
+ it("should not show Save button when opening an existing question from a read-only collection", () => {
+ H.prepareSdkIframeEmbedTest({
+ withToken: "bleeding-edge",
+ signOut: false,
+ });
+
+ H.createCollection({
+ name: "Read Only Collection",
+ }).then(({ body: collection }) => {
+ cy.updateCollectionGraph({
+ [DATA_GROUP_ID]: {
+ root: READ,
+ [collection.id]: READ,
+ },
+ });
+
+ H.createQuestion({
+ name: "Test Question",
+ query: { "source-table": ORDERS_ID },
+ collection_id: collection.id,
+ });
+
+ cy.signIn("nocollection");
+
+ setupEmbed(`
+ <metabase-browser
+ initial-collection="${collection.id}"
+ read-only="false"
+ />
+ `);
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.findByText("Test Question").should("be.visible").click();
+
+ cy.findByTestId("visualization-root").should("be.visible");
+
+ cy.findByTestId("interactive-question-result-toolbar")
+ .findByText("Filter")
+ .click();
+ });
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.findAllByTestId("dimension-list-item").findByText("ID").click();
+ cy.findByPlaceholderText("Enter an ID").type("1");
+ cy.findByText("Add filter").click();
+ });
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.findByRole("button", { name: "Save" }).should("not.exist");
+ });
+ });
+ });
+ });
+
+ it("should reset `Exploration` editor state when clicking 'new exploration' breadcrumb after selecting a filter", () => {
+ H.prepareSdkIframeEmbedTest({
+ withToken: "bleeding-edge",
+ signOut: false,
+ });
+
+ setupEmbed(`
+ <metabase-browser
+ initial-collection="root"
+ read-only="false"
+ />
+ `);
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.findByText("New exploration").click();
+
+ cy.findByText("Pick your starting data").should("be.visible");
+
+ cy.findByText("Orders").click();
+
+ cy.findByTestId("sdk-breadcrumbs").findByText("New exploration").click();
+
+ cy.findByText("Pick your starting data").should("be.visible");
+ cy.findByText("Orders").should("not.exist");
+ });
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/setup.tsx b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/setup.tsx
index 77a09495225..63d1505a2a0 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/setup.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/setup.tsx
@@ -4,6 +4,7 @@ import {
setupCardEndpoints,
setupCardQueryEndpoints,
setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders } from "__support__/ui";
import { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";
@@ -18,6 +19,7 @@ import type { MetabaseProviderProps } from "embedding-sdk-bundle/types/metabase-
import {
createMockCard,
createMockCardQueryMetadata,
+ createMockCollection,
createMockColumn,
createMockDataset,
createMockDatasetData,
@@ -51,6 +53,20 @@ export const setup = ({
createMockCardQueryMetadata({ databases: [MOCK_DB] }),
);
+ const BOBBY_TEST_COLLECTION = createMockCollection({
+ archived: false,
+ can_write: true,
+ description: null,
+ id: 1,
+ location: "/",
+ name: "Bobby Tables's Personal Collection",
+ personal_owner_id: 100,
+ });
+
+ setupCollectionByIdEndpoint({
+ collections: [BOBBY_TEST_COLLECTION],
+ });
+
const { state } = setupSdkState({
sdkState: createMockSdkState({
initStatus: createMockLoginStatusState({ status: "uninitialized" }),
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SaveButton.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SaveButton.tsx
index 4ed243dd1c8..cdd4b0b23f5 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SaveButton.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SaveButton.tsx
@@ -1,6 +1,7 @@
import type { MouseEventHandler } from "react";
import { t } from "ttag";
+import { useCollectionData } from "embedding-sdk-bundle/hooks/private/use-collection-data";
import type { ButtonProps } from "embedding-sdk-bundle/types/ui";
import { isQuestionDirty } from "metabase/query_builder/utils/question";
import * as Lib from "metabase-lib";
@@ -24,16 +25,18 @@ export type SaveButtonProps = {
export const shouldShowSaveButton = ({
question,
originalQuestion,
+ canWriteToTargetCollection,
}: {
question?: Question;
originalQuestion?: Question;
+ canWriteToTargetCollection: boolean;
}) => {
const canSave = question && Lib.canSave(question.query(), question.type());
const isQuestionChanged = originalQuestion
? isQuestionDirty(question, originalQuestion)
: true;
- return Boolean(isQuestionChanged && canSave);
+ return Boolean(isQuestionChanged && canSave) && canWriteToTargetCollection;
};
/**
@@ -46,11 +49,18 @@ export const shouldShowSaveButton = ({
* @param props
*/
export const SaveButton = ({ ...buttonProps }: SaveButtonProps = {}) => {
- const { question, originalQuestion } = useSdkQuestionContext();
+ const { question, originalQuestion, isSaveEnabled, targetCollection } =
+ useSdkQuestionContext();
+
+ const { canWrite: canWriteToTargetCollection } = useCollectionData(
+ targetCollection,
+ { skipCollectionFetching: !isSaveEnabled },
+ );
const isSaveButtonEnabled = shouldShowSaveButton({
question,
originalQuestion,
+ canWriteToTargetCollection,
});
return (
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
index f5411f2ecfe..2d1a6ddbc7a 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx
@@ -11,6 +11,7 @@ import {
} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
import { QuestionVisualization } from "embedding-sdk-bundle/components/private/SdkQuestion/components/Visualization";
import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion";
+import { useCollectionData } from "embedding-sdk-bundle/hooks/private/use-collection-data";
import { useQuestionEditorSync } from "embedding-sdk-bundle/hooks/private/use-question-editor-sync";
import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
import { shouldRunCardQuery } from "embedding-sdk-bundle/lib/sdk-question";
@@ -87,6 +88,7 @@ export const SdkQuestionDefaultView = ({
originalQuestion,
isSaveEnabled,
withDownloads,
+ targetCollection,
onReset,
onNavigateBack,
queryQuestion,
@@ -122,17 +124,29 @@ export const SdkQuestionDefaultView = ({
question && shouldRunCardQuery({ question, isGuestEmbed }) && !queryResults;
useEffect(() => {
- if (
+ const isNewQuestion = originalId === "new";
+ const isExistingQuestion =
+ question &&
!isQuestionLoading &&
question?.isSaved() &&
originalId !== "new" &&
- queryResults
- ) {
+ queryResults;
+
+ const onNavigate = onNavigateBack ?? onReset ?? undefined;
+
+ if (isNewQuestion) {
+ reportLocation({
+ type: "question",
+ id: "new",
+ name: "New exploration",
+ onNavigate,
+ });
+ } else if (isExistingQuestion) {
reportLocation({
type: "question",
id: question.id(),
name: question.displayName() || "Question",
- onNavigate: onNavigateBack ?? onReset ?? undefined,
+ onNavigate,
});
}
}, [
@@ -145,6 +159,11 @@ export const SdkQuestionDefaultView = ({
onReset,
]);
+ const { canWrite: canWriteToTargetCollection } = useCollectionData(
+ targetCollection,
+ { skipCollectionFetching: !isSaveEnabled },
+ );
+
if (
!isEditorOpen &&
(isLocaleLoading || isQuestionLoading || isQueryResultLoading)
@@ -161,7 +180,11 @@ export const SdkQuestionDefaultView = ({
}
const showSaveButton =
- shouldShowSaveButton({ question, originalQuestion }) && isSaveEnabled;
+ shouldShowSaveButton({
+ question,
+ originalQuestion,
+ canWriteToTargetCollection,
+ }) && isSaveEnabled;
return (
<FlexibleSizeComponent
diff --git a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx
index 5c7ba646155..b1f7991ae6a 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx
@@ -1,26 +1,27 @@
-import { type ComponentType, useEffect, useMemo, useState } from "react";
+import { type ComponentType, useEffect } from "react";
+import { t } from "ttag";
import {
CollectionNotFoundError,
SdkLoader,
withPublicComponentWrapper,
} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
+import { useCollectionData } from "embedding-sdk-bundle/hooks/private/use-collection-data";
import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
-import { useSdkSelector } from "embedding-sdk-bundle/store";
-import { getCollectionIdSlugFromReference } from "embedding-sdk-bundle/store/collections";
import type {
MetabaseCollectionItem,
SdkCollectionId,
} from "embedding-sdk-bundle/types/collection";
import type { CommonStylingProps } from "embedding-sdk-bundle/types/props";
-import { useGetCollectionQuery } from "metabase/api";
import { COLLECTION_PAGE_SIZE } from "metabase/collections/components/CollectionContent";
import { CollectionItemsTable } from "metabase/collections/components/CollectionContent/CollectionItemsTable";
+import EmptyState from "metabase/common/components/EmptyState";
import { useLocale } from "metabase/common/hooks/use-locale";
import { isNotNull } from "metabase/lib/types";
import CollectionBreadcrumbs from "metabase/nav/containers/CollectionBreadcrumbs";
-import { Stack } from "metabase/ui";
+import { Icon, Stack } from "metabase/ui";
import type { CollectionId, CollectionItemModel } from "metabase-types/api";
+import { isObject } from "metabase-types/guards";
import { collectionBrowserPropsSchema } from "./CollectionBrowser.schema";
@@ -96,7 +97,7 @@ export type CollectionBrowserProps = {
} & CommonStylingProps;
export const CollectionBrowserInner = ({
- collectionId = "personal",
+ collectionId,
onClick,
pageSize = COLLECTION_PAGE_SIZE,
visibleEntityTypes = [...USER_FACING_ENTITY_NAMES],
@@ -105,34 +106,22 @@ export const CollectionBrowserInner = ({
className,
style,
}: CollectionBrowserProps) => {
- const baseCollectionId = useSdkSelector((state) =>
- getCollectionIdSlugFromReference(state, collectionId),
- );
-
- // Internal collection state.
- const [internalCollectionId, setInternalCollectionId] =
- useState<CollectionId>(baseCollectionId);
-
const {
- isBreadcrumbEnabled: isGlobalBreadcrumbEnabled,
- currentLocation,
- reportLocation,
- } = useSdkBreadcrumbs();
-
- const effectiveCollectionId = useMemo(() => {
- if (isGlobalBreadcrumbEnabled && currentLocation?.type === "collection") {
- return currentLocation.id as CollectionId;
- }
-
- return internalCollectionId;
- }, [isGlobalBreadcrumbEnabled, currentLocation, internalCollectionId]);
+ baseCollectionId,
+ internalCollectionId,
+ effectiveCollectionId,
+ collection,
+ isFetchingCollection,
+ collectionLoadingError,
+ setInternalCollectionId,
+ } = useCollectionData(collectionId);
- const { data: collection, isFetching: isFetchingCollection } =
- useGetCollectionQuery({ id: effectiveCollectionId });
+ const { isBreadcrumbEnabled: isGlobalBreadcrumbEnabled, reportLocation } =
+ useSdkBreadcrumbs();
useEffect(() => {
setInternalCollectionId(baseCollectionId);
- }, [baseCollectionId]);
+ }, [baseCollectionId, setInternalCollectionId]);
useEffect(() => {
if (isGlobalBreadcrumbEnabled && !isFetchingCollection && collection) {
@@ -149,6 +138,18 @@ export const CollectionBrowserInner = ({
reportLocation,
]);
+ if (
+ isObject(collectionLoadingError) &&
+ collectionLoadingError.status === 403
+ ) {
+ return (
+ <EmptyState
+ title={t`You don't have access to this collection`}
+ illustrationElement={<Icon name="key" size={100} />}
+ />
+ );
+ }
+
const onClickItem = (item: MetabaseCollectionItem) => {
onClick?.(item);
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion-multiple-questions.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion-multiple-questions.unit.spec.tsx
index 28b1d8dc043..b9626e71fee 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion-multiple-questions.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion-multiple-questions.unit.spec.tsx
@@ -5,6 +5,7 @@ import {
setupCardEndpoints,
setupCardQueryEndpoints,
setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
setupDatabaseEndpoints,
setupTableEndpoints,
} from "__support__/server-mocks";
@@ -16,6 +17,7 @@ import type { Card, Dataset } from "metabase-types/api";
import {
createMockCard,
createMockCardQueryMetadata,
+ createMockCollection,
createMockColumn,
createMockDatabase,
createMockDataset,
@@ -76,6 +78,20 @@ const setup = ({
setupDatabaseEndpoints(TEST_DB);
setupTableEndpoints(TEST_TABLE);
+ const BOBBY_TEST_COLLECTION = createMockCollection({
+ archived: false,
+ can_write: true,
+ description: null,
+ id: 1,
+ location: "/",
+ name: "Bobby Tables's Personal Collection",
+ personal_owner_id: 100,
+ });
+
+ setupCollectionByIdEndpoint({
+ collections: [BOBBY_TEST_COLLECTION],
+ });
+
const children = (
<div>
{mocks.map((mock) => (
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.EditorButton.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.EditorButton.unit.spec.tsx
index ed8a8c04eb1..caa33db0701 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.EditorButton.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.EditorButton.unit.spec.tsx
@@ -5,6 +5,7 @@ import {
setupCardEndpoints,
setupCardQueryEndpoints,
setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
setupDatabaseEndpoints,
setupTableEndpoints,
} from "__support__/server-mocks";
@@ -16,6 +17,7 @@ import { QuestionNotebookButton } from "metabase/query_builder/components/view/V
import {
createMockCard,
createMockCardQueryMetadata,
+ createMockCollection,
createMockColumn,
createMockDatabase,
createMockDataset,
@@ -75,6 +77,20 @@ const setup = ({
setupCardQueryEndpoints(TEST_CARD, TEST_DATASET);
+ const BOBBY_TEST_COLLECTION = createMockCollection({
+ archived: false,
+ can_write: true,
+ description: null,
+ id: 1,
+ location: "/",
+ name: "Bobby Tables's Personal Collection",
+ personal_owner_id: 100,
+ });
+
+ setupCollectionByIdEndpoint({
+ collections: [BOBBY_TEST_COLLECTION],
+ });
+
const clickSpy = jest.fn();
renderWithSDKProviders(
diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
index 567c0eeace1..c6a00d71e89 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.unit.spec.tsx
@@ -7,6 +7,7 @@ import {
setupCardEndpoints,
setupCardQueryEndpoints,
setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
setupDatabaseEndpoints,
setupTableEndpoints,
setupUnauthorizedCardEndpoints,
@@ -31,6 +32,7 @@ import type { BaseEntityId, CardId } from "metabase-types/api";
import {
createMockCard,
createMockCardQueryMetadata,
+ createMockCollection,
createMockColumn,
createMockDatabase,
createMockDataset,
@@ -133,6 +135,20 @@ const setup = async ({
setupEntityIdEndpoint({ card: { [TEST_ENTITY_ID]: TEST_CARD_ID } });
+ const BOBBY_TEST_COLLECTION = createMockCollection({
+ archived: false,
+ can_write: true,
+ description: null,
+ id: 1,
+ location: "/",
+ name: "Bobby Tables's Personal Collection",
+ personal_owner_id: 100,
+ });
+
+ setupCollectionByIdEndpoint({
+ collections: [BOBBY_TEST_COLLECTION],
+ });
+
renderWithSDKProviders(
<SdkQuestion
questionId={cardId}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx
index 58e9462923d..0d07e4a78c8 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx
@@ -9,6 +9,7 @@ import {
setupCardEndpoints,
setupCardQueryEndpoints,
setupCardQueryMetadataEndpoint,
+ setupCollectionByIdEndpoint,
setupCollectionItemsEndpoint,
setupCollectionsEndpoints,
setupDashboardEndpoints,
@@ -199,6 +200,20 @@ export const setupSdkDashboard = async ({
setupBookmarksEndpoints([]);
+ const BOBBY_TEST_COLLECTION = createMockCollection({
+ archived: false,
+ can_write: true,
+ description: null,
+ id: 1,
+ location: "/",
+ name: "Bobby Tables's Personal Collection",
+ personal_owner_id: 100,
+ });
+
+ setupCollectionByIdEndpoint({
+ collections: [BOBBY_TEST_COLLECTION],
+ });
+
const user = createMockUser({
permissions: createMockUserPermissions({
can_create_queries: true,
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts
new file mode 100644
index 00000000000..0a84a3a7c93
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-collection-data.ts
@@ -0,0 +1,52 @@
+import { useMemo, useState } from "react";
+
+import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
+import { useSdkSelector } from "embedding-sdk-bundle/store";
+import { getCollectionIdSlugFromReference } from "embedding-sdk-bundle/store/collections";
+import type { SdkCollectionId } from "embedding-sdk-bundle/types/collection";
+import { useGetCollectionQuery } from "metabase/api";
+import type { CollectionId } from "metabase-types/api";
+
+export const useCollectionData = (
+ collectionId: SdkCollectionId = "personal",
+ { skipCollectionFetching = false }: { skipCollectionFetching?: boolean } = {},
+) => {
+ const baseCollectionId = useSdkSelector((state) =>
+ getCollectionIdSlugFromReference(state, collectionId),
+ );
+
+ // Internal collection state.
+ const [internalCollectionId, setInternalCollectionId] =
+ useState<CollectionId>(baseCollectionId);
+
+ const { isBreadcrumbEnabled: isGlobalBreadcrumbEnabled, currentLocation } =
+ useSdkBreadcrumbs();
+
+ const effectiveCollectionId = useMemo(() => {
+ if (isGlobalBreadcrumbEnabled && currentLocation?.type === "collection") {
+ return currentLocation.id as CollectionId;
+ }
+
+ return internalCollectionId;
+ }, [isGlobalBreadcrumbEnabled, currentLocation, internalCollectionId]);
+
+ const {
+ data: collection,
+ error: collectionLoadingError,
+ isFetching: isFetchingCollection,
+ } = useGetCollectionQuery(
+ { id: effectiveCollectionId },
+ { skip: skipCollectionFetching },
+ );
+
+ return {
+ baseCollectionId,
+ internalCollectionId,
+ effectiveCollectionId,
+ collection,
+ canWrite: collection?.can_write ?? false,
+ setInternalCollectionId,
+ isFetchingCollection,
+ collectionLoadingError,
+ };
+};
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx
index 37d3d77d746..8287b68e2fa 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/MetabaseBrowser.tsx
@@ -11,6 +11,7 @@ import {
EditableDashboard,
InteractiveDashboard,
} from "embedding-sdk-bundle/components/public/dashboard";
+import { useCollectionData } from "embedding-sdk-bundle/hooks/private/use-collection-data";
import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
import type { SdkCollectionId } from "embedding-sdk-bundle/types";
import type { SdkBreadcrumbItemType } from "embedding-sdk-bundle/types/breadcrumb";
@@ -40,6 +41,9 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
const { breadcrumbs, currentLocation, reportLocation } = useSdkBreadcrumbs();
+ const { canWrite: canWriteToInitialCollection } =
+ useCollectionData(initialCollection);
+
const [currentView, setCurrentView] = useState<MetabaseBrowserView>({
type: "collection",
id: initialCollection,
@@ -160,9 +164,18 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
const handleNewExploration = () => {
setCurrentView({ type: "exploration" });
- reportLocation({ type: "question", id: "new", name: "New exploration" });
};
+ // Only show "New exploration" button if user has write access and it's enabled
+ const showNewExplorationButton =
+ (settings.withNewQuestion ?? true) && canWriteToInitialCollection;
+
+ // Only show "New dashboard" button if not read-only and user has write access
+ const showNewDashboardButton =
+ !isReadOnly &&
+ (settings.withNewDashboard ?? true) &&
+ canWriteToInitialCollection;
+
return (
<Stack pos="relative" h="100%">
<Box pos="absolute" top={0} left={0} w="100%">
@@ -182,13 +195,13 @@ export function MetabaseBrowser({ settings }: MetabaseBrowserProps) {
{currentView.type === "collection" && (
<Group gap="sm">
- {(settings.withNewQuestion ?? true) && (
+ {showNewExplorationButton && (
<Button justify="center" onClick={handleNewExploration}>
{t`New exploration`}
</Button>
)}
- {!isReadOnly && (settings.withNewDashboard ?? true) && (
+ {showNewDashboardButton && (
<Button
justify="center"
onClick={() => setCurrentView({ type: "create-dashboard" })}