Skip to content

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

Move route guards out of metabase/router (#78526)

Romeo Van Snick03b8f5cefc82
diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjs
index 006ea538cae..05d4977f8c7 100644
--- a/frontend/lint/module-boundaries.mjs
+++ b/frontend/lint/module-boundaries.mjs
@@ -161,6 +161,7 @@ const elements = [
createElement({ type: "shared", name: "questions" }),
createElement({ type: "shared", name: "redux" }),
createElement({ type: "shared", name: "rich_text_editing" }),
+ createElement({ type: "shared", name: "route-guards" }),
createElement({ type: "shared", name: "router" }),
createElement({
type: "shared",
diff --git a/frontend/src/metabase/admin/utils.ts b/frontend/src/metabase/admin/utils.ts
index 35e254a611c..5c02abaf949 100644
--- a/frontend/src/metabase/admin/utils.ts
+++ b/frontend/src/metabase/admin/utils.ts
@@ -4,8 +4,8 @@ import { shouldShowTenantsUpsell } from "metabase/admin/people/selectors";
import { connect } from "metabase/redux";
import type { State } from "metabase/redux/store";
import type { AdminPath } from "metabase/redux/store/admin";
+import { createRedirectGuard } from "metabase/route-guards";
import { push, replace } from "metabase/router";
-import { createRedirectGuard } from "metabase/router/guards";
import { getAdminPaths } from "metabase/selectors/admin";
import { getSetting } from "metabase/selectors/settings";
diff --git a/frontend/src/metabase/common/data-studio/selectors.ts b/frontend/src/metabase/common/data-studio/selectors.ts
index 6ec87d798c1..d5954e3fd1c 100644
--- a/frontend/src/metabase/common/data-studio/selectors.ts
+++ b/frontend/src/metabase/common/data-studio/selectors.ts
@@ -3,7 +3,7 @@ import type { State } from "metabase/redux/store";
import { getIsEmbeddingIframe } from "metabase/selectors/embed";
import { getUserIsAdmin, getUserIsAnalyst } from "metabase/selectors/user";
-// Must be in sync with CanAccessDataStudio in frontend/src/metabase/router/guards.tsx
+// Must be in sync with CanAccessDataStudio in frontend/src/metabase/data-studio/route-guards.tsx
export function canAccessDataStudio(state: State) {
if (getIsEmbeddingIframe(state)) {
return false;
diff --git a/frontend/src/metabase/data-studio/route-guards.tsx b/frontend/src/metabase/data-studio/route-guards.tsx
new file mode 100644
index 00000000000..904187059fc
--- /dev/null
+++ b/frontend/src/metabase/data-studio/route-guards.tsx
@@ -0,0 +1,38 @@
+import { canAccessDataStudio } from "metabase/common/data-studio/selectors";
+import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";
+import {
+ AvailableInEmbedding,
+ MetabaseIsSetup,
+ UserIsAuthenticated,
+ createRedirectGuard,
+} from "metabase/route-guards";
+import { Outlet } from "metabase/router";
+
+const UserCanAccessDataStudio = createRedirectGuard(
+ (state) => canAccessDataStudio(state),
+ "/unauthorized",
+);
+
+const UserCanAccessDataModel = createRedirectGuard(
+ (state) => PLUGIN_FEATURE_LEVEL_PERMISSIONS.canAccessDataModel(state),
+ "/unauthorized",
+);
+
+// Must be in sync with canAccessDataStudio in frontend/src/metabase/data-studio/selectors.ts
+export const CanAccessDataStudio = () => (
+ <MetabaseIsSetup>
+ <UserIsAuthenticated>
+ <UserCanAccessDataStudio>
+ <AvailableInEmbedding>
+ <Outlet />
+ </AvailableInEmbedding>
+ </UserCanAccessDataStudio>
+ </UserIsAuthenticated>
+ </MetabaseIsSetup>
+);
+
+export const CanAccessDataModel = () => (
+ <UserCanAccessDataModel>
+ <Outlet />
+ </UserCanAccessDataModel>
+);
diff --git a/frontend/src/metabase/data-studio/routes.tsx b/frontend/src/metabase/data-studio/routes.tsx
index 9e79aca3a35..e41e7e01ac7 100644
--- a/frontend/src/metabase/data-studio/routes.tsx
+++ b/frontend/src/metabase/data-studio/routes.tsx
@@ -27,6 +27,7 @@ import { TransformsSectionLayout } from "./app/pages/TransformsSectionLayout";
import { WorkspacesSectionLayout } from "./app/pages/WorkspacesSectionLayout";
import { getDataStudioMetadataRoutes } from "./data-model/routes";
import { getDataStudioGlossaryRoutes } from "./glossary/routes";
+import { CanAccessDataModel, CanAccessDataStudio } from "./route-guards";
import { getDataStudioSettingsRoutes } from "./settings/routes";
import {
DependenciesUpsellPage,
@@ -36,11 +37,7 @@ import {
const RoutedTransformsSectionLayout = withRouteProps(TransformsSectionLayout);
-export function getDataStudioRoutes(
- CanAccessDataStudio: RouteComponent,
- CanAccessDataModel: RouteComponent,
- IsAdmin: RouteComponent,
-) {
+export function getDataStudioRoutes(IsAdmin: RouteComponent) {
return (
<>
{/* These redirects sit
diff --git a/frontend/src/metabase/data-studio/routes.unit.spec.tsx b/frontend/src/metabase/data-studio/routes.unit.spec.tsx
index a668e22014e..f5def8fb9c2 100644
--- a/frontend/src/metabase/data-studio/routes.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/routes.unit.spec.tsx
@@ -3,19 +3,24 @@ import { Outlet, Route } from "metabase/router";
import { getDataStudioRoutes } from "./routes";
-const DenyingDataStudioGuard = () => (
- <div data-testid="data-studio-access-denied" />
-);
+/**
+ * These specs assert that the legacy redirects sit outside the Data Studio
+ * access guard, so the guard is stubbed to always deny.
+ */
+jest.mock("./route-guards", () => {
+ const { Outlet } = jest.requireActual("metabase/router");
+ return {
+ CanAccessDataStudio: () => <div data-testid="data-studio-access-denied" />,
+ CanAccessDataModel: () => <Outlet />,
+ };
+});
+
const AllowingGuard = () => <Outlet />;
function setup(initialRoute: string) {
renderWithProviders(
<Route path="/">
- {getDataStudioRoutes(
- DenyingDataStudioGuard,
- AllowingGuard,
- AllowingGuard,
- )}
+ {getDataStudioRoutes(AllowingGuard)}
<Route
path="monitor/dependency-diagnostics"
element={<div data-testid="diagnostics-index" />}
diff --git a/frontend/src/metabase/monitor/route-guards.tsx b/frontend/src/metabase/monitor/route-guards.tsx
new file mode 100644
index 00000000000..7dff1017c08
--- /dev/null
+++ b/frontend/src/metabase/monitor/route-guards.tsx
@@ -0,0 +1,60 @@
+import {
+ canAccessAlertsManagement,
+ canAccessMonitor,
+ canAccessMonitorDiagnostics,
+ canAccessMonitoringTools,
+} from "metabase/common/monitor/selectors";
+import {
+ MetabaseIsSetup,
+ UserIsAuthenticated,
+ createRedirectGuard,
+} from "metabase/route-guards";
+import { Outlet } from "metabase/router";
+
+const UserCanAccessMonitor = createRedirectGuard(
+ (state) => canAccessMonitor(state),
+ "/unauthorized",
+);
+
+const UserCanAccessMonitorDiagnostics = createRedirectGuard(
+ (state) => canAccessMonitorDiagnostics(state),
+ "/unauthorized",
+);
+
+const UserCanAccessMonitoringTools = createRedirectGuard(
+ (state) => canAccessMonitoringTools(state),
+ "/unauthorized",
+);
+
+const UserCanAccessAlertsManagement = createRedirectGuard(
+ (state) => canAccessAlertsManagement(state),
+ "/unauthorized",
+);
+
+export const CanAccessMonitor = () => (
+ <MetabaseIsSetup>
+ <UserIsAuthenticated>
+ <UserCanAccessMonitor>
+ <Outlet />
+ </UserCanAccessMonitor>
+ </UserIsAuthenticated>
+ </MetabaseIsSetup>
+);
+
+export const CanAccessMonitorDiagnostics = () => (
+ <UserCanAccessMonitorDiagnostics>
+ <Outlet />
+ </UserCanAccessMonitorDiagnostics>
+);
+
+export const CanAccessMonitoringTools = () => (
+ <UserCanAccessMonitoringTools>
+ <Outlet />
+ </UserCanAccessMonitoringTools>
+);
+
+export const CanAccessAlertsManagement = () => (
+ <UserCanAccessAlertsManagement>
+ <Outlet />
+ </UserCanAccessAlertsManagement>
+);
diff --git a/frontend/src/metabase/monitor/route-guards.unit.spec.tsx b/frontend/src/metabase/monitor/route-guards.unit.spec.tsx
new file mode 100644
index 00000000000..3e36a675989
--- /dev/null
+++ b/frontend/src/metabase/monitor/route-guards.unit.spec.tsx
@@ -0,0 +1,142 @@
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import {
+ createMockSettingsState,
+ createMockState,
+} from "metabase/redux/store/mocks";
+import { Route } from "metabase/router";
+import { createMockUser } from "metabase-types/api/mocks";
+
+import { CanAccessAlertsManagement, CanAccessMonitor } from "./route-guards";
+
+describe("monitor route-guards", () => {
+ describe("CanAccessMonitor", () => {
+ interface SetupOpts {
+ currentUser?: ReturnType<typeof createMockUser>;
+ }
+
+ const setup = ({ currentUser }: SetupOpts = {}) => {
+ return renderWithProviders(
+ <>
+ <Route element={<CanAccessMonitor />}>
+ <Route path="/monitor" element={<div>monitor page</div>} />
+ </Route>
+ <Route path="/auth/login" element={<div>login page</div>} />
+ <Route path="/unauthorized" element={<div>unauthorized</div>} />
+ </>,
+ {
+ storeInitialState: createMockState({
+ currentUser,
+ settings: createMockSettingsState({ "has-user-setup": true }),
+ }),
+ withRouter: true,
+ initialRoute: "/monitor",
+ },
+ );
+ };
+
+ it("redirects unauthenticated users to login with redirect back", async () => {
+ const { history } = setup({ currentUser: undefined });
+
+ await waitFor(() => {
+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");
+ });
+
+ expect(history?.getCurrentLocation().query).toEqual(
+ expect.objectContaining({ redirect: "/monitor" }),
+ );
+ });
+
+ it("redirects users without monitor access to unauthorized", async () => {
+ const { history } = setup({
+ currentUser: createMockUser({
+ is_data_analyst: false,
+ is_superuser: false,
+ }),
+ });
+
+ await waitFor(() => {
+ expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
+ });
+
+ expect(history?.getCurrentLocation().query).toEqual({});
+ });
+
+ it("renders for analysts", () => {
+ setup({
+ currentUser: createMockUser({
+ is_data_analyst: true,
+ is_superuser: false,
+ }),
+ });
+
+ expect(screen.getByText("monitor page")).toBeInTheDocument();
+ });
+ });
+
+ describe("CanAccessAlertsManagement", () => {
+ interface SetupOpts {
+ currentUser?: ReturnType<typeof createMockUser>;
+ }
+
+ const setup = ({ currentUser }: SetupOpts = {}) => {
+ return renderWithProviders(
+ <>
+ <Route element={<CanAccessAlertsManagement />}>
+ <Route
+ path="/monitor/notifications"
+ element={<div>alerts page</div>}
+ />
+ </Route>
+ <Route path="/unauthorized" element={<div>unauthorized</div>} />
+ </>,
+ {
+ storeInitialState: createMockState({
+ currentUser,
+ settings: createMockSettingsState({ "has-user-setup": true }),
+ }),
+ withRouter: true,
+ initialRoute: "/monitor/notifications",
+ },
+ );
+ };
+
+ it("renders the page for superusers", async () => {
+ setup({ currentUser: createMockUser({ is_superuser: true }) });
+
+ expect(await screen.findByText("alerts page")).toBeInTheDocument();
+ });
+
+ it("redirects a non-admin with monitoring permission to unauthorized without redirect-back", async () => {
+ const { history } = setup({
+ currentUser: createMockUser({
+ is_superuser: false,
+ is_data_analyst: false,
+ permissions: { can_access_monitoring: true },
+ }),
+ });
+
+ await waitFor(() => {
+ expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
+ });
+
+ expect(history?.getCurrentLocation().query).toEqual({});
+ expect(screen.queryByText("alerts page")).not.toBeInTheDocument();
+ });
+
+ it("redirects an analyst to unauthorized without redirect-back", async () => {
+ const { history } = setup({
+ currentUser: createMockUser({
+ is_superuser: false,
+ is_data_analyst: true,
+ }),
+ });
+
+ await waitFor(() => {
+ expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
+ });
+
+ expect(history?.getCurrentLocation().query).toEqual({});
+ expect(screen.queryByText("alerts page")).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/frontend/src/metabase/monitor/routes.tsx b/frontend/src/metabase/monitor/routes.tsx
index f0cb2f40fd8..ccc02dcb5ce 100644
--- a/frontend/src/metabase/monitor/routes.tsx
+++ b/frontend/src/metabase/monitor/routes.tsx
@@ -20,15 +20,16 @@ import {
import { PLUGIN_MONITOR, PLUGIN_MONITOR_TOOLS } from "metabase/plugins";
import { useSelector } from "metabase/redux";
import type { State } from "metabase/redux/store";
-import {
- Navigate,
- Route,
- type RouteComponent,
- redirect,
-} from "metabase/router";
+import { Navigate, Route, redirect } from "metabase/router";
import * as Urls from "metabase/urls";
import { MonitorLayout } from "./components/MonitorLayout";
+import {
+ CanAccessAlertsManagement,
+ CanAccessMonitor,
+ CanAccessMonitorDiagnostics,
+ CanAccessMonitoringTools,
+} from "./route-guards";
/** Lands on the first Monitor section the user can access. */
function MonitorIndexRedirect() {
@@ -36,12 +37,7 @@ function MonitorIndexRedirect() {
return <Navigate to={indexPath} replace />;
}
-export function getMonitorRoutes(
- CanAccessMonitor: RouteComponent,
- CanAccessMonitorDiagnostics: RouteComponent,
- CanAccessMonitoringTools: RouteComponent,
- CanAccessAlertsManagement: RouteComponent,
-) {
+export function getMonitorRoutes() {
return (
<Route element={<CanAccessMonitor />}>
<Route path="monitor" element={<MonitorLayout />}>
diff --git a/frontend/src/metabase/monitor/routes.unit.spec.tsx b/frontend/src/metabase/monitor/routes.unit.spec.tsx
index 1afa7c67c42..77742e4c094 100644
--- a/frontend/src/metabase/monitor/routes.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/routes.unit.spec.tsx
@@ -1,14 +1,45 @@
-import type { ReactNode } from "react";
-
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import { renderWithProviders, screen } from "__support__/ui";
import { reinitialize } from "metabase/plugins";
import { createMockState } from "metabase/redux/store/mocks";
-import { Outlet, Route } from "metabase/router";
+import { Route } from "metabase/router";
import { createMockUser } from "metabase-types/api/mocks";
import { getMonitorRedirects, getMonitorRoutes } from "./routes";
+type MonitorGuard =
+ | "CanAccessMonitor"
+ | "CanAccessMonitorDiagnostics"
+ | "CanAccessMonitoringTools"
+ | "CanAccessAlertsManagement";
+
+/**
+ * These specs assert route-tree structure, not access policy, so the guards are
+ * stubbed to allow by default. Adding a guard here makes it deny instead, which
+ * is how a single section gets blocked without touching permissions state.
+ */
+const mockDeniedGuards = new Set<MonitorGuard>();
+
+jest.mock("./route-guards", () => {
+ const { Outlet } = jest.requireActual("metabase/router");
+ const stubGuard = (name: MonitorGuard) => {
+ const Guard = () =>
+ mockDeniedGuards.has(name) ? (
+ <div data-testid="unauthorized-marker">{"Unauthorized"}</div>
+ ) : (
+ <Outlet />
+ );
+ return Guard;
+ };
+
+ return {
+ CanAccessMonitor: stubGuard("CanAccessMonitor"),
+ CanAccessMonitorDiagnostics: stubGuard("CanAccessMonitorDiagnostics"),
+ CanAccessMonitoringTools: stubGuard("CanAccessMonitoringTools"),
+ CanAccessAlertsManagement: stubGuard("CanAccessAlertsManagement"),
+ };
+});
+
jest.mock("metabase-enterprise/settings", () => ({
hasPremiumFeature: jest.fn().mockReturnValue(true),
}));
@@ -90,67 +121,32 @@ jest.mock(
}),
);
-const CanAccessMonitor = () => <Outlet />;
-const CanAccessMonitorDiagnostics = () => <Outlet />;
-const CanAccessMonitoringTools = () => <Outlet />;
-const CanAccessAlertsManagement = () => <Outlet />;
-
const UPSELL_TITLE =
"Find and fix broken dependencies without hunting them down";
type SetupOpts = {
initialRoute: string;
user?: ReturnType<typeof createMockUser>;
+ /** Guards to make deny access, so a section can be blocked in isolation. */
+ deny?: MonitorGuard[];
};
const setup = ({
initialRoute,
user = createMockUser({ is_superuser: true }),
+ deny = [],
}: SetupOpts) => {
- return renderWithProviders(
- <Route path="/">
- {getMonitorRedirects()}
- {getMonitorRoutes(
- CanAccessMonitor,
- CanAccessMonitorDiagnostics,
- CanAccessMonitoringTools,
- CanAccessAlertsManagement,
- )}
- </Route>,
- {
- withRouter: true,
- initialRoute,
- storeInitialState: createMockState({ currentUser: user }),
- },
- );
-};
+ deny.forEach((guard) => mockDeniedGuards.add(guard));
-const DenyingGuard = () => (
- <div data-testid="unauthorized-marker">{"Unauthorized"}</div>
-);
-
-const setupWithGuards = ({
- initialRoute,
- CanAccessMonitorDiagnostics: Diagnostics = CanAccessMonitorDiagnostics,
- CanAccessMonitoringTools: Tools = CanAccessMonitoringTools,
- CanAccessAlertsManagement: AlertsManagement = CanAccessAlertsManagement,
-}: {
- initialRoute: string;
- CanAccessMonitorDiagnostics?: () => ReactNode;
- CanAccessMonitoringTools?: () => ReactNode;
- CanAccessAlertsManagement?: () => ReactNode;
-}) => {
return renderWithProviders(
<Route path="/">
{getMonitorRedirects()}
- {getMonitorRoutes(CanAccessMonitor, Diagnostics, Tools, AlertsManagement)}
+ {getMonitorRoutes()}
</Route>,
{
withRouter: true,
initialRoute,
- storeInitialState: createMockState({
- currentUser: createMockUser({ is_superuser: true }),
- }),
+ storeInitialState: createMockState({ currentUser: user }),
},
);
};
@@ -158,6 +154,7 @@ const setupWithGuards = ({
describe("monitor routes", () => {
afterEach(() => {
reinitialize();
+ mockDeniedGuards.clear();
});
describe("getMonitorRoutes", () => {
@@ -236,9 +233,9 @@ describe("monitor routes", () => {
});
it("blocks section routes when the section guard denies", async () => {
- setupWithGuards({
+ setup({
initialRoute: "/monitor/logs",
- CanAccessMonitoringTools: DenyingGuard,
+ deny: ["CanAccessMonitoringTools"],
});
expect(
@@ -248,9 +245,9 @@ describe("monitor routes", () => {
});
it("blocks the notifications route when its own guard denies, independent of the Tools guard", async () => {
- setupWithGuards({
+ setup({
initialRoute: "/monitor/notifications",
- CanAccessAlertsManagement: DenyingGuard,
+ deny: ["CanAccessAlertsManagement"],
});
expect(
@@ -262,10 +259,9 @@ describe("monitor routes", () => {
});
it("renders NotFound for unknown paths even when both section guards deny (catch-all sits outside the guards)", async () => {
- setupWithGuards({
+ setup({
initialRoute: "/monitor/does-not-exist",
- CanAccessMonitorDiagnostics: DenyingGuard,
- CanAccessMonitoringTools: DenyingGuard,
+ deny: ["CanAccessMonitorDiagnostics", "CanAccessMonitoringTools"],
});
expect(await screen.findByLabelText("error page")).toBeInTheDocument();
diff --git a/frontend/src/metabase/route-guards/auth-guards.tsx b/frontend/src/metabase/route-guards/auth-guards.tsx
new file mode 100644
index 00000000000..00f8ef34bea
--- /dev/null
+++ b/frontend/src/metabase/route-guards/auth-guards.tsx
@@ -0,0 +1,124 @@
+import { useEffect } from "react";
+
+import { type Location, Navigate, Outlet } from "metabase/router";
+import { getAdminPaths } from "metabase/selectors/admin";
+import { getIsEmbeddingIframe } from "metabase/selectors/embed";
+import { getCanAccessOnboardingPage } from "metabase/selectors/onboarding";
+import { getSetting } from "metabase/selectors/settings";
+import { replaceLocation } from "metabase/utils/dom";
+
+import { createGuard, createRedirectGuard } from "./create-guard";
+import {
+ getRedirectUrl,
+ isBackendOnlyPath,
+ resolveRedirectTarget,
+} from "./redirect-target";
+
+function FullPageRedirect({ to }: { to: string }): null {
+ useEffect(() => {
+ replaceLocation(to);
+ }, [to]);
+ return null;
+}
+
+const loginUrlWithRedirect = (location: Omit<Location, "query" | "action">) => {
+ const from = `${location.pathname}${location.search}`;
+ const query = new URLSearchParams({ redirect: from }).toString();
+ return `/auth/login?${query}`;
+};
+
+/**
+ * The building blocks features compose their own guards from. A feature guard
+ * wraps its access check in `MetabaseIsSetup` + `UserIsAuthenticated` so an
+ * unauthenticated visitor lands on login rather than on `/unauthorized`.
+ */
+export const MetabaseIsSetup = createRedirectGuard(
+ (state) => getSetting(state, "has-user-setup"),
+ "/setup",
+);
+
+export const AvailableInEmbedding = createRedirectGuard(
+ (state) => !getIsEmbeddingIframe(state),
+ "/unauthorized",
+);
+
+export const UserIsAuthenticated = createGuard(
+ { isAllowed: (state) => !!state.currentUser },
+ (location) => <Navigate to={loginUrlWithRedirect(location)} replace />,
+);
+
+const UserIsAdmin = createRedirectGuard(
+ (state) => Boolean(state.currentUser && state.currentUser.is_superuser),
+ "/unauthorized",
+);
+
+const UserIsNotAuthenticated = createGuard(
+ {
+ isAllowed: (state) => !state.currentUser,
+ isAuthenticating: (state) =>
+ state.auth.loginPending || !state.auth.redirect,
+ },
+ () => {
+ const { href, path, isInAppOrigin } =
+ resolveRedirectTarget(getRedirectUrl());
+ const needsFullPageLoad = !isInAppOrigin || isBackendOnlyPath(path);
+
+ return needsFullPageLoad ? (
+ <FullPageRedirect to={href} />
+ ) : (
+ <Navigate to={path} replace />
+ );
+ },
+);
+
+const UserCanAccessSettings = createRedirectGuard(
+ (state) => (getAdminPaths(state)?.length ?? 0) > 0,
+ "/unauthorized",
+);
+
+const UserCanAccessOnboarding = createRedirectGuard(
+ (state) => getCanAccessOnboardingPage(state),
+ "/",
+);
+
+export const IsAuthenticated = () => (
+ <MetabaseIsSetup>
+ <UserIsAuthenticated>
+ <Outlet />
+ </UserIsAuthenticated>
+ </MetabaseIsSetup>
+);
+
+export const IsAdmin = () => (
+ <MetabaseIsSetup>
+ <UserIsAuthenticated>
+ <UserIsAdmin>
+ <Outlet />
+ </UserIsAdmin>
+ </UserIsAuthenticated>
+ </MetabaseIsSetup>
+);
+
+export const IsNotAuthenticated = () => (
+ <MetabaseIsSetup>
+ <UserIsNotAuthenticated>
+ <Outlet />
+ </UserIsNotAuthenticated>
+ </MetabaseIsSetup>
+);
+
+export const CanAccessSettings = () => (
+ <MetabaseIsSetup>
+ <UserIsAuthenticated>
+ <UserCanAccessSettings>
+ <Outlet />
+ </UserCanAccessSettings>
+ </UserIsAuthenticated>
+ </MetabaseIsSetup>
+);
+
+export const CanAccessOnboarding = () => (
+ <UserCanAccessOnboarding>
+ <Outlet />
+ </UserCanAccessOnboarding>
+);
diff --git a/frontend/src/metabase/router/guards.unit.spec.tsx b/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx
similarity index 62%
rename from frontend/src/metabase/router/guards.unit.spec.tsx
rename to frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx
index 11067e3eeb0..41a38f95657 100644
--- a/frontend/src/metabase/router/guards.unit.spec.tsx
+++ b/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx
@@ -1,22 +1,15 @@
import { mockSettings } from "__support__/settings";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { renderWithProviders, waitFor } from "__support__/ui";
import {
createMockSettingsState,
createMockState,
} from "metabase/redux/store/mocks";
+import { Route } from "metabase/router";
import { setBasename } from "metabase/utils/basename";
import { replaceLocation } from "metabase/utils/dom";
import { createMockUser } from "metabase-types/api/mocks";
-import {
- CanAccessAlertsManagement,
- CanAccessMonitor,
- IsAdmin,
- IsAuthenticated,
- IsNotAuthenticated,
- isBackendOnlyPath,
-} from "./guards";
-import { Route } from "./route";
+import { IsAdmin, IsAuthenticated, IsNotAuthenticated } from "./auth-guards";
jest.mock("metabase/utils/dom", () => ({
...jest.requireActual("metabase/utils/dom"),
@@ -276,160 +269,4 @@ describe("route-guards", () => {
});
});
});
-
- describe("CanAccessMonitor", () => {
- interface SetupOpts {
- currentUser?: ReturnType<typeof createMockUser>;
- }
-
- const setup = ({ currentUser }: SetupOpts = {}) => {
- return renderWithProviders(
- <>
- <Route element={<CanAccessMonitor />}>
- <Route path="/monitor" element={<div>monitor page</div>} />
- </Route>
- <Route path="/auth/login" element={<div>login page</div>} />
- <Route path="/unauthorized" element={<div>unauthorized</div>} />
- </>,
- {
- storeInitialState: createMockState({
- currentUser,
- settings: createMockSettingsState({ "has-user-setup": true }),
- }),
- withRouter: true,
- initialRoute: "/monitor",
- },
- );
- };
-
- it("redirects unauthenticated users to login with redirect back", async () => {
- const { history } = setup({ currentUser: undefined });
-
- await waitFor(() => {
- expect(history?.getCurrentLocation().pathname).toBe("/auth/login");
- });
-
- expect(history?.getCurrentLocation().query).toEqual(
- expect.objectContaining({ redirect: "/monitor" }),
- );
- });
-
- it("redirects users without monitor access to unauthorized", async () => {
- const { history } = setup({
- currentUser: createMockUser({
- is_data_analyst: false,
- is_superuser: false,
- }),
- });
-
- await waitFor(() => {
- expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
- });
-
- expect(history?.getCurrentLocation().query).toEqual({});
- });
-
- it("renders for analysts", () => {
- setup({
- currentUser: createMockUser({
- is_data_analyst: true,
- is_superuser: false,
- }),
- });
-
- expect(screen.getByText("monitor page")).toBeInTheDocument();
- });
- });
-
- describe("CanAccessAlertsManagement", () => {
- interface SetupOpts {
- currentUser?: ReturnType<typeof createMockUser>;
- }
-
- const setup = ({ currentUser }: SetupOpts = {}) => {
- return renderWithProviders(
- <>
- <Route element={<CanAccessAlertsManagement />}>
- <Route
- path="/monitor/notifications"
- element={<div>alerts page</div>}
- />
- </Route>
- <Route path="/unauthorized" element={<div>unauthorized</div>} />
- </>,
- {
- storeInitialState: createMockState({
- currentUser,
- settings: createMockSettingsState({ "has-user-setup": true }),
- }),
- withRouter: true,
- initialRoute: "/monitor/notifications",
- },
- );
- };
-
- it("renders the page for superusers", async () => {
- setup({ currentUser: createMockUser({ is_superuser: true }) });
-
- expect(await screen.findByText("alerts page")).toBeInTheDocument();
- });
-
- it("redirects a non-admin with monitoring permission to unauthorized without redirect-back", async () => {
- const { history } = setup({
- currentUser: createMockUser({
- is_superuser: false,
- is_data_analyst: false,
- permissions: { can_access_monitoring: true },
- }),
- });
-
- await waitFor(() => {
- expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
- });
-
- expect(history?.getCurrentLocation().query).toEqual({});
- expect(screen.queryByText("alerts page")).not.toBeInTheDocument();
- });
-
- it("redirects an analyst to unauthorized without redirect-back", async () => {
- const { history } = setup({
- currentUser: createMockUser({
- is_superuser: false,
- is_data_analyst: true,
- }),
- });
-
- await waitFor(() => {
- expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
- });
-
- expect(history?.getCurrentLocation().query).toEqual({});
- expect(screen.queryByText("alerts page")).not.toBeInTheDocument();
- });
- });
-
- describe("isBackendOnlyPath", () => {
- it("should return true for /oauth/ paths", () => {
- expect(isBackendOnlyPath("/oauth/authorize")).toBe(true);
- expect(isBackendOnlyPath("/oauth/authorize/decision")).toBe(true);
- expect(isBackendOnlyPath("/oauth/token")).toBe(true);
- });
-
- it("should return true for /auth/sso/ paths", () => {
- expect(isBackendOnlyPath("/auth/sso/slack-connect")).toBe(true);
- expect(isBackendOnlyPath("/auth/sso/slack-connect/callback")).toBe(true);
- expect(isBackendOnlyPath("/auth/sso/my-provider")).toBe(true);
- });
-
- it("should return false for frontend paths", () => {
- expect(isBackendOnlyPath("/")).toBe(false);
- expect(isBackendOnlyPath("/auth/login")).toBe(false);
- expect(isBackendOnlyPath("/collection/root")).toBe(false);
- expect(isBackendOnlyPath("/question/1")).toBe(false);
- });
-
- it("should not match partial prefixes", () => {
- expect(isBackendOnlyPath("/oauthx/foo")).toBe(false);
- });
- });
});
diff --git a/frontend/src/metabase/route-guards/create-guard.tsx b/frontend/src/metabase/route-guards/create-guard.tsx
new file mode 100644
index 00000000000..698484bca4e
--- /dev/null
+++ b/frontend/src/metabase/route-guards/create-guard.tsx
@@ -0,0 +1,60 @@
+import type { ReactElement, ReactNode } from "react";
+
+import { useSelector } from "metabase/redux";
+import type { State } from "metabase/redux/store";
+import { type Location, Navigate, Outlet, useLocation } from "metabase/router";
+
+/**
+ * Guards double as route elements and as wrapper components. As a route element
+ * (`element={<IsAuthenticated/>}`) no `children` are passed, so they fall back to
+ * `<Outlet/>` and render whatever nested route matched.
+ */
+type Props = { children?: ReactNode };
+
+const NEVER_AUTHENTICATING = () => false;
+
+type GuardSelectors = {
+ isAllowed: (state: State) => boolean;
+ isAuthenticating?: (state: State) => boolean;
+};
+
+/**
+ * Builds a route guard component from redux selectors. When access is denied it
+ * renders the element from `renderRedirect` instead of the guarded children.
+ *
+ * While `isAuthenticating` is true the guard renders nothing (no redirect and no
+ * children), so a route is not bounced while its auth state is still resolving.
+ */
+export function createGuard(
+ { isAllowed, isAuthenticating = NEVER_AUTHENTICATING }: GuardSelectors,
+ renderRedirect: (
+ location: Omit<Location, "query" | "action">,
+ ) => ReactElement | null,
+) {
+ return function Guard({ children = <Outlet /> }: Props) {
+ const location = useLocation();
+ const allowed = useSelector(isAllowed);
+ const authenticating = useSelector(isAuthenticating);
+
+ if (allowed) {
+ return children;
+ }
+ if (authenticating) {
+ return null;
+ }
+ return renderRedirect(location);
+ };
+}
+
+/**
+ * Builds a guard that redirects to a fixed path when access is denied, the
+ * common case with no `?redirect=` round-trip.
+ */
+export function createRedirectGuard(
+ isAllowed: (state: State) => boolean,
+ redirectPath: string,
+) {
+ return createGuard({ isAllowed }, () => (
+ <Navigate to={redirectPath} replace />
+ ));
+}
diff --git a/frontend/src/metabase/route-guards/index.ts b/frontend/src/metabase/route-guards/index.ts
new file mode 100644
index 00000000000..7d8589513b2
--- /dev/null
+++ b/frontend/src/metabase/route-guards/index.ts
@@ -0,0 +1,11 @@
+export {
+ AvailableInEmbedding,
+ CanAccessOnboarding,
+ CanAccessSettings,
+ IsAdmin,
+ IsAuthenticated,
+ IsNotAuthenticated,
+ MetabaseIsSetup,
+ UserIsAuthenticated,
+} from "./auth-guards";
+export { createGuard, createRedirectGuard } from "./create-guard";
diff --git a/frontend/src/metabase/route-guards/redirect-target.ts b/frontend/src/metabase/route-guards/redirect-target.ts
new file mode 100644
index 00000000000..94b66963746
--- /dev/null
+++ b/frontend/src/metabase/route-guards/redirect-target.ts
@@ -0,0 +1,66 @@
+import { getBasename } from "metabase/utils/basename";
+import { isSameOrSiteUrlOrigin } from "metabase/utils/dom";
+
+/** Paths that are handled by the backend server, not the frontend SPA router. */
+export const BACKEND_ONLY_PATH_PREFIXES = ["/oauth/", "/auth/sso/"];
+
+export const isBackendOnlyPath = (path: string): boolean =>
+ BACKEND_ONLY_PATH_PREFIXES.some((prefix) => path.startsWith(prefix));
+
+export const getRedirectUrl = () => {
+ const params = new URLSearchParams(window.location.search);
+ const redirectUrlParam = params.get("redirect");
+
+ return redirectUrlParam != null && isSameOrSiteUrlOrigin(redirectUrlParam)
+ ? redirectUrlParam
+ : "/";
+};
+
+/**
+ * A redirect target arrives in one of two shapes: an absolute URL
+ * (`https://host/metabase/x`, `//host/x`) whose pathname is already what the
+ * browser sees, or a basename-relative path (`/oauth/x`, sloppily `oauth/x`) —
+ * the convention for every SPA path, including the backend's login redirect
+ * (the server sits behind the prefix-stripping proxy and never sees the
+ * subpath). Normalize to a browser-real URL.
+ */
+const toBrowserUrl = (url: string) => {
+ const hasExplicitOrigin = /^[a-z][a-z0-9+.-]*:|^\/\//i.test(url);
+ // String-join for paths, not URL resolution: a leading "/" is *root*-relative
+ // and would discard the basename from a URL base.
+ return hasExplicitOrigin
+ ? new URL(url, window.location.origin)
+ : new URL(
+ `${getBasename()}/${url.replace(/^\//, "")}`,
+ window.location.origin,
+ );
+};
+
+/** The inverse: strip the basename back off for the SPA router, which prepends
+ * it itself (and for prefix checks like `isBackendOnlyPath`). */
+const toRouterPath = ({ pathname, search, hash }: URL) => {
+ const basename = getBasename();
+ const relativePathname =
+ basename && pathname.startsWith(`${basename}/`)
+ ? pathname.slice(basename.length)
+ : pathname;
+ return `${relativePathname}${search}${hash}`;
+};
+
+/**
+ * `getRedirectUrl` accepts site-url-origin targets as well as same-origin ones,
+ * so it can hand back an absolute URL. The SPA router only understands in-app
+ * paths, so split the target into the path to navigate to and whether the SPA
+ * can serve that origin at all.
+ */
+export const resolveRedirectTarget = (url: string) => {
+ const target = toBrowserUrl(url);
+
+ return {
+ // Absolute, so a full-page redirect is not re-resolved against the current
+ // path (a bare `auth/sso/x` would otherwise land under `/auth/login`).
+ href: target.href,
+ path: toRouterPath(target),
+ isInAppOrigin: target.origin === window.location.origin,
+ };
+};
diff --git a/frontend/src/metabase/route-guards/redirect-target.unit.spec.ts b/frontend/src/metabase/route-guards/redirect-target.unit.spec.ts
new file mode 100644
index 00000000000..c19f1d9444c
--- /dev/null
+++ b/frontend/src/metabase/route-guards/redirect-target.unit.spec.ts
@@ -0,0 +1,26 @@
+import { isBackendOnlyPath } from "./redirect-target";
+
+describe("isBackendOnlyPath", () => {
+ it("should return true for /oauth/ paths", () => {
+ expect(isBackendOnlyPath("/oauth/authorize")).toBe(true);
+ expect(isBackendOnlyPath("/oauth/authorize/decision")).toBe(true);
+ expect(isBackendOnlyPath("/oauth/token")).toBe(true);
+ });
+
+ it("should return true for /auth/sso/ paths", () => {
+ expect(isBackendOnlyPath("/auth/sso/slack-connect")).toBe(true);
+ expect(isBackendOnlyPath("/auth/sso/slack-connect/callback")).toBe(true);
+ expect(isBackendOnlyPath("/auth/sso/my-provider")).toBe(true);
+ });
+
+ it("should return false for frontend paths", () => {
+ expect(isBackendOnlyPath("/")).toBe(false);
+ expect(isBackendOnlyPath("/auth/login")).toBe(false);
+ expect(isBackendOnlyPath("/collection/root")).toBe(false);
+ expect(isBackendOnlyPath("/question/1")).toBe(false);
+ });
+
+ it("should not match partial prefixes", () => {
+ expect(isBackendOnlyPath("/oauthx/foo")).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/router/guards.tsx b/frontend/src/metabase/router/guards.tsx
deleted file mode 100644
index 5b7b1819e64..00000000000
--- a/frontend/src/metabase/router/guards.tsx
+++ /dev/null
@@ -1,323 +0,0 @@
-import { type ReactElement, type ReactNode, useEffect } from "react";
-
-import { canAccessDataStudio } from "metabase/common/data-studio/selectors";
-import {
- canAccessAlertsManagement,
- canAccessMonitor,
- canAccessMonitorDiagnostics,
- canAccessMonitoringTools,
-} from "metabase/common/monitor/selectors";
-import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";
-import { useSelector } from "metabase/redux";
-import type { State } from "metabase/redux/store";
-import { getAdminPaths } from "metabase/selectors/admin";
-import { getIsEmbeddingIframe } from "metabase/selectors/embed";
-import { getCanAccessOnboardingPage } from "metabase/selectors/onboarding";
-import { getSetting } from "metabase/selectors/settings";
-import { getBasename } from "metabase/utils/basename";
-import { isSameOrSiteUrlOrigin, replaceLocation } from "metabase/utils/dom";
-
-import { Navigate } from "./Navigate";
-import { Outlet } from "./Outlet";
-import type { Location } from "./types";
-import { useLocation } from "./use-location";
-
-/**
- * Guards double as route elements and as wrapper components. As a route element
- * (`element={<IsAuthenticated/>}`) no `children` are passed, so they fall back to
- * `<Outlet/>` and render whatever nested route matched.
- */
-type Props = { children?: ReactNode };
-
-/** Paths that are handled by the backend server, not the frontend SPA router. */
-export const BACKEND_ONLY_PATH_PREFIXES = ["/oauth/", "/auth/sso/"];
-
-export const isBackendOnlyPath = (path: string): boolean =>
- BACKEND_ONLY_PATH_PREFIXES.some((prefix) => path.startsWith(prefix));
-
-const getRedirectUrl = () => {
- const params = new URLSearchParams(window.location.search);
- const redirectUrlParam = params.get("redirect");
-
- return redirectUrlParam != null && isSameOrSiteUrlOrigin(redirectUrlParam)
- ? redirectUrlParam
- : "/";
-};
-
-/**
- * A redirect target arrives in one of two shapes: an absolute URL
- * (`https://host/metabase/x`, `//host/x`) whose pathname is already what the
- * browser sees, or a basename-relative path (`/oauth/x`, sloppily `oauth/x`) —
- * the convention for every SPA path, including the backend's login redirect
- * (the server sits behind the prefix-stripping proxy and never sees the
- * subpath). Normalize to a browser-real URL.
- */
-const toBrowserUrl = (url: string) => {
- const hasExplicitOrigin = /^[a-z][a-z0-9+.-]*:|^\/\//i.test(url);
- // String-join for paths, not URL resolution: a leading "/" is *root*-relative
- // and would discard the basename from a URL base.
- return hasExplicitOrigin
- ? new URL(url, window.location.origin)
- : new URL(
- `${getBasename()}/${url.replace(/^\//, "")}`,
- window.location.origin,
- );
-};
-
-/** The inverse: strip the basename back off for the SPA router, which prepends
- * it itself (and for prefix checks like `isBackendOnlyPath`). */
-const toRouterPath = ({ pathname, search, hash }: URL) => {
- const basename = getBasename();
- const relativePathname =
- basename && pathname.startsWith(`${basename}/`)
- ? pathname.slice(basename.length)
- : pathname;
- return `${relativePathname}${search}${hash}`;
-};
-
-/**
- * `getRedirectUrl` accepts site-url-origin targets as well as same-origin ones,
- * so it can hand back an absolute URL. The SPA router only understands in-app
- * paths, so split the target into the path to navigate to and whether the SPA
- * can serve that origin at all.
- */
-const resolveRedirectTarget = (url: string) => {
- const target = toBrowserUrl(url);
-
- return {
- // Absolute, so a full-page redirect is not re-resolved against the current
- // path (a bare `auth/sso/x` would otherwise land under `/auth/login`).
- href: target.href,
- path: toRouterPath(target),
- isInAppOrigin: target.origin === window.location.origin,
- };
-};
-
-const NEVER_AUTHENTICATING = () => false;
-
-type GuardSelectors = {
- isAllowed: (state: State) => boolean;
- isAuthenticating?: (state: State) => boolean;
-};
-
-/**
- * Builds a route guard component from redux selectors. When access is denied it
- * renders the element from `renderRedirect` instead of the guarded children.
- *
- * While `isAuthenticating` is true the guard renders nothing (no redirect and no
- * children), so a route is not bounced while its auth state is still resolving.
- */
-function createGuard(
- { isAllowed, isAuthenticating = NEVER_AUTHENTICATING }: GuardSelectors,
- renderRedirect: (
- location: Omit<Location, "query" | "action">,
- ) => ReactElement | null,
-) {
- return function Guard({ children = <Outlet /> }: Props) {
- const location = useLocation();
- const allowed = useSelector(isAllowed);
- const authenticating = useSelector(isAuthenticating);
-
- if (allowed) {
- return children;
- }
- if (authenticating) {
- return null;
- }
- return renderRedirect(location);
- };
-}
-
-/**
- * Builds a guard that redirects to a fixed path when access is denied, the
- * common case with no `?redirect=` round-trip.
- */
-export function createRedirectGuard(
- isAllowed: (state: State) => boolean,
- redirectPath: string,
-) {
- return createGuard({ isAllowed }, () => (
- <Navigate to={redirectPath} replace />
- ));
-}
-
-function FullPageRedirect({ to }: { to: string }): null {
- useEffect(() => {
- replaceLocation(to);
- }, [to]);
- return null;
-}
-
-const loginUrlWithRedirect = (location: Omit<Location, "query" | "action">) => {
- const from = `${location.pathname}${location.search}`;
- const query = new URLSearchParams({ redirect: from }).toString();
- return `/auth/login?${query}`;
-};
-
-const MetabaseIsSetup = createRedirectGuard(
- (state) => getSetting(state, "has-user-setup"),
- "/setup",
-);
-
-const AvailableInEmbedding = createRedirectGuard(
- (state) => !getIsEmbeddingIframe(state),
- "/unauthorized",
-);
-
-const UserIsAuthenticated = createGuard(
- { isAllowed: (state) => !!state.currentUser },
- (location) => <Navigate to={loginUrlWithRedirect(location)} replace />,
-);
-
-const UserIsAdmin = createRedirectGuard(
- (state) => Boolean(state.currentUser && state.currentUser.is_superuser),
- "/unauthorized",
-);
-
-const UserIsNotAuthenticated = createGuard(
- {
- isAllowed: (state) => !state.currentUser,
- isAuthenticating: (state) =>
- state.auth.loginPending || !state.auth.redirect,
- },
- () => {
- const { href, path, isInAppOrigin } =
- resolveRedirectTarget(getRedirectUrl());
- const needsFullPageLoad = !isInAppOrigin || isBackendOnlyPath(path);
-
- return needsFullPageLoad ? (
- <FullPageRedirect to={href} />
- ) : (
- <Navigate to={path} replace />
- );
- },
-);
-
-const UserCanAccessSettings = createRedirectGuard(
- (state) => (getAdminPaths(state)?.length ?? 0) > 0,
- "/unauthorized",
-);
-
-const UserCanAccessOnboarding = createRedirectGuard(
- (state) => getCanAccessOnboardingPage(state),
- "/",
-);
-
-const UserCanAccessDataModel = createRedirectGuard(
- (state) => PLUGIN_FEATURE_LEVEL_PERMISSIONS.canAccessDataModel(state),
- "/unauthorized",
-);
-
-const UserCanAccessDataStudio = createRedirectGuard(
- (state) => canAccessDataStudio(state),
- "/unauthorized",
-);
-
-const UserCanAccessMonitor = createRedirectGuard(
- (state) => canAccessMonitor(state),
- "/unauthorized",
-);
-
-const UserCanAccessMonitorDiagnostics = createRedirectGuard(
- (state) => canAccessMonitorDiagnostics(state),
- "/unauthorized",
-);
-
-const UserCanAccessMonitoringTools = createRedirectGuard(
- (state) => canAccessMonitoringTools(state),
- "/unauthorized",
-);
-
-const UserCanAccessAlertsManagement = createRedirectGuard(
- (state) => canAccessAlertsManagement(state),
- "/unauthorized",
-);
-
-export const IsAuthenticated = () => (
- <MetabaseIsSetup>
- <UserIsAuthenticated>
- <Outlet />
- </UserIsAuthenticated>
- </MetabaseIsSetup>
-);
-
-export const IsAdmin = () => (
- <MetabaseIsSetup>
- <UserIsAuthenticated>
- <UserIsAdmin>
- <Outlet />
- </UserIsAdmin>
- </UserIsAuthenticated>
- </MetabaseIsSetup>
-);
-
-export const IsNotAuthenticated = () => (
- <MetabaseIsSetup>
- <UserIsNotAuthenticated>
- <Outlet />
- </UserIsNotAuthenticated>
- </MetabaseIsSetup>
-);
-
-export const CanAccessSettings = () => (
- <MetabaseIsSetup>
- <UserIsAuthenticated>
- <UserCanAccessSettings>
- <Outlet />
- </UserCanAccessSettings>
- </UserIsAuthenticated>
- </MetabaseIsSetup>
-);
-
-export const CanAccessOnboarding = () => (
- <UserCanAccessOnboarding>
- <Outlet />
- </UserCanAccessOnboarding>
-);
-
-// Must be in sync with canAccessDataStudio in frontend/src/metabase/data-studio/selectors.ts
-export const CanAccessDataStudio = () => (
- <MetabaseIsSetup>
- <UserIsAuthenticated>
- <UserCanAccessDataStudio>
- <AvailableInEmbedding>
- <Outlet />
- </AvailableInEmbedding>
- </UserCanAccessDataStudio>
- </UserIsAuthenticated>
- </MetabaseIsSetup>
-);
-
-export const CanAccessDataModel = () => (
- <UserCanAccessDataModel>
- <Outlet />
- </UserCanAccessDataModel>
-);
-
-export const CanAccessMonitor = () => (
- <MetabaseIsSetup>
- <UserIsAuthenticated>
- <UserCanAccessMonitor>
- <Outlet />
- </UserCanAccessMonitor>
- </UserIsAuthenticated>
- </MetabaseIsSetup>
-);
-
-export const CanAccessMonitorDiagnostics = () => (
- <UserCanAccessMonitorDiagnostics>
- <Outlet />
- </UserCanAccessMonitorDiagnostics>
-);
-
-export const CanAccessMonitoringTools = () => (
- <UserCanAccessMonitoringTools>
- <Outlet />
- </UserCanAccessMonitoringTools>
-);
-
-export const CanAccessAlertsManagement = () => (
- <UserCanAccessAlertsManagement>
- <Outlet />
- </UserCanAccessAlertsManagement>
-);
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 4f0bf750424..62275e1aed2 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -68,6 +68,13 @@ import SegmentFieldListContainer from "metabase/reference/segments/SegmentFieldL
import SegmentListContainer from "metabase/reference/segments/SegmentListContainer";
import SegmentQuestionsContainer from "metabase/reference/segments/SegmentQuestionsContainer";
import SegmentRevisionsContainer from "metabase/reference/segments/SegmentRevisionsContainer";
+import {
+ CanAccessOnboarding,
+ CanAccessSettings,
+ IsAdmin,
+ IsAuthenticated,
+ IsNotAuthenticated,
+} from "metabase/route-guards";
import {
Navigate,
Route,
@@ -75,19 +82,6 @@ import {
useParams,
withRouteProps,
} from "metabase/router";
-import {
- CanAccessAlertsManagement,
- CanAccessDataModel,
- CanAccessDataStudio,
- CanAccessMonitor,
- CanAccessMonitorDiagnostics,
- CanAccessMonitoringTools,
- CanAccessOnboarding,
- CanAccessSettings,
- IsAdmin,
- IsAuthenticated,
- IsNotAuthenticated,
-} from "metabase/router/guards";
import { SearchApp } from "metabase/search/containers/SearchApp";
import { RedirectIfSetup } from "metabase/setup/components/RedirectIfSetup";
import { Setup } from "metabase/setup/components/Setup";
@@ -397,19 +391,10 @@ export const getRoutes = (store: AppStore) => {
{getAdminRoutes(store, CanAccessSettings, IsAdmin)}
{/* DATA STUDIO */}
- {getDataStudioRoutes(
- CanAccessDataStudio,
- CanAccessDataModel,
- IsAdmin,
- )}
+ {getDataStudioRoutes(IsAdmin)}
{/* MONITOR */}
- {getMonitorRoutes(
- CanAccessMonitor,
- CanAccessMonitorDiagnostics,
- CanAccessMonitoringTools,
- CanAccessAlertsManagement,
- )}
+ {getMonitorRoutes()}
</Route>
</Route>
diff --git a/frontend/src/metabase/transforms/route-guards.tsx b/frontend/src/metabase/transforms/route-guards.tsx
index 6d36f10b8aa..0f3f7e9aeee 100644
--- a/frontend/src/metabase/transforms/route-guards.tsx
+++ b/frontend/src/metabase/transforms/route-guards.tsx
@@ -1,4 +1,4 @@
-import { createRedirectGuard } from "metabase/router/guards";
+import { createRedirectGuard } from "metabase/route-guards";
import { getSetting } from "metabase/selectors/settings";
import * as Urls from "metabase/urls";