Skip to content

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

Replace `UtilsApi` with RTK-based hooks (#74224)

Romeo Van Snick904632be171d
diff --git a/frontend/src/metabase/account/password/actions.ts b/frontend/src/metabase/account/password/actions.ts
deleted file mode 100644
index 1cd22af3391..00000000000
--- a/frontend/src/metabase/account/password/actions.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { getIn } from "icepick";
-
-import { UtilApi } from "metabase/services";
-import { passwordComplexityDescription } from "metabase/utils/password";
-
-export const validatePassword = async (password: string) => {
- const error = passwordComplexityDescription(password);
- if (error) {
- return error;
- }
-
- try {
- await UtilApi.password_check({ password });
- } catch (error) {
- return getIn(error, ["data", "errors", "password"]);
- }
-};
diff --git a/frontend/src/metabase/account/password/containers/UserPasswordApp/UserPasswordApp.tsx b/frontend/src/metabase/account/password/containers/UserPasswordApp/UserPasswordApp.tsx
index 5babf56766b..d808bda48ec 100644
--- a/frontend/src/metabase/account/password/containers/UserPasswordApp/UserPasswordApp.tsx
+++ b/frontend/src/metabase/account/password/containers/UserPasswordApp/UserPasswordApp.tsx
@@ -1,15 +1,15 @@
-import { connect } from "metabase/redux";
-import type { State } from "metabase/redux/store";
+import { useValidatePassword } from "metabase/common/hooks";
+import { useSelector } from "metabase/redux";
import { getUser } from "metabase/selectors/user";
import { checkNotNull } from "metabase/utils/types";
-import { validatePassword } from "../../actions";
import { UserPasswordForm } from "../../components/UserPasswordForm";
-const mapStateToProps = (state: State) => ({
- user: checkNotNull(getUser(state)),
- onValidatePassword: validatePassword,
-});
+const UserPasswordApp = () => {
+ const user = checkNotNull(useSelector(getUser));
+ const validatePassword = useValidatePassword();
+ return <UserPasswordForm user={user} onValidatePassword={validatePassword} />;
+};
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default connect(mapStateToProps)(UserPasswordForm);
+export default UserPasswordApp;
diff --git a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecretKeyWidget.tsx b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecretKeyWidget.tsx
index 3165c1c800a..25eab184ca4 100644
--- a/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecretKeyWidget.tsx
+++ b/frontend/src/metabase/admin/settings/components/EmbeddingSettings/EmbeddingSecretKeyWidget.tsx
@@ -2,10 +2,10 @@ import { useDisclosure } from "@mantine/hooks";
import { t } from "ttag";
import { SetByEnvVarWrapper } from "metabase/admin/settings/components/widgets/AdminSettingInput";
+import { useLazyGenerateRandomTokenQuery } from "metabase/api/util";
import { useAdminSetting } from "metabase/api/utils";
import { ConfirmModal } from "metabase/common/components/ConfirmModal";
import { CopyButton } from "metabase/common/components/CopyButton";
-import { UtilApi } from "metabase/services";
import { Box, Button, Flex, TextInputBlurChange } from "metabase/ui";
import { SettingHeader } from "../SettingHeader";
@@ -17,6 +17,7 @@ export const EmbeddingSecretKeyWidget = () => {
const { value, updateSetting, settingDetails } = useAdminSetting(
"embedding-secret-key",
);
+ const [generateRandomToken] = useLazyGenerateRandomTokenQuery();
const handleChange = async (newToken: string) => {
updateSetting({
@@ -26,7 +27,7 @@ export const EmbeddingSecretKeyWidget = () => {
};
const generateToken = async () => {
- const result = await UtilApi.random_token();
+ const result = await generateRandomToken().unwrap();
handleChange(result.token);
};
diff --git a/frontend/src/metabase/admin/tools/components/Help/Help.tsx b/frontend/src/metabase/admin/tools/components/Help/Help.tsx
index 89971e2a73a..89b3ed58107 100644
--- a/frontend/src/metabase/admin/tools/components/Help/Help.tsx
+++ b/frontend/src/metabase/admin/tools/components/Help/Help.tsx
@@ -1,6 +1,5 @@
import cx from "classnames";
-import { type PropsWithChildren, useState } from "react";
-import { useMount } from "react-use";
+import { type PropsWithChildren, useMemo } from "react";
import { t } from "ttag";
import _ from "underscore";
@@ -9,6 +8,8 @@ import {
SettingsSection,
} from "metabase/admin/components/SettingsSection";
import { UpsellBetterSupport } from "metabase/admin/upsells";
+import { useGetBugReportDetailsQuery } from "metabase/api/bug-report";
+import legacyApi from "metabase/api/legacy-client";
import { CopyButton } from "metabase/common/components/CopyButton";
import { ExternalLink } from "metabase/common/components/ExternalLink";
import { useSetting } from "metabase/common/hooks";
@@ -16,7 +17,6 @@ import CS from "metabase/css/core/index.css";
import { PLUGIN_SUPPORT } from "metabase/plugins";
import { useSelector } from "metabase/redux";
import { getIsPaidPlan } from "metabase/selectors/settings";
-import { UtilApi } from "metabase/services";
import { Box, Code, Group } from "metabase/ui";
import S from "./help.module.css";
@@ -25,6 +25,13 @@ function navigatorInfo() {
return _.pick(navigator, "language", "platform", "userAgent", "vendor");
}
+// Returns an external-link URL (not an API call) so it goes through `basename`
+// to support Metabase deployments at a subpath.
+function getConnectionPoolDetailsUrl() {
+ const path = "/api/bug-reporting/connection-pool-details";
+ return new URL(legacyApi.basename + path, location.origin).href;
+}
+
const template = `**Describe the bug**
A clear and concise description of what the bug is.
@@ -92,14 +99,15 @@ const InfoBlock = ({ children }: InfoBlockProps) => (
);
export const Help = ({ children }: PropsWithChildren) => {
- const [details, setDetails] = useState({ "browser-info": navigatorInfo() });
const { tag } = useSetting("version");
const isPaidPlan = useSelector(getIsPaidPlan);
- useMount(async () => {
- const newDetails = await UtilApi.bug_report_details();
- setDetails((oldDetails) => ({ ...oldDetails, ...newDetails }));
- });
+ const { data: bugReportDetails } = useGetBugReportDetailsQuery();
+
+ const details = useMemo(
+ () => ({ "browser-info": navigatorInfo(), ...bugReportDetails }),
+ [bugReportDetails],
+ );
const detailString = JSON.stringify(details, null, 2);
const compactDetailStringForUrl = encodeURIComponent(JSON.stringify(details));
@@ -140,7 +148,7 @@ export const Help = ({ children }: PropsWithChildren) => {
<HelpLink
title={t`Connection Pool Details`}
description={t`Information about active and idle connections for all pools`}
- link={UtilApi.get_connection_pool_details_url()}
+ link={getConnectionPoolDetailsUrl()}
/>
</SettingsSection>
{/* render 'children' so that the child modal routes can show up */}
diff --git a/frontend/src/metabase/admin/tools/components/Logs/Logs.unit.spec.tsx b/frontend/src/metabase/admin/tools/components/Logs/Logs.unit.spec.tsx
index 1af7d0385d8..6a3035181e3 100644
--- a/frontend/src/metabase/admin/tools/components/Logs/Logs.unit.spec.tsx
+++ b/frontend/src/metabase/admin/tools/components/Logs/Logs.unit.spec.tsx
@@ -7,7 +7,6 @@ import {
createMockLocation,
createMockRoutingState,
} from "metabase/redux/store/mocks";
-import { UtilApi } from "metabase/services";
import { DEFAULT_POLLING_DURATION_MS, Logs } from "./Logs";
import { maybeMergeLogs } from "./utils";
@@ -23,7 +22,8 @@ const log = {
process_uuid: "e7774ef2-42ab-43de-89f7-d6de9fdc624f",
};
-let utilSpy: any;
+const countLogsCalls = () =>
+ fetchMock.callHistory.calls("path:/api/logger/logs").length;
interface SetupOpts {
location?: Location;
@@ -51,37 +51,43 @@ function setup({
describe("Logs", () => {
describe("log fetching", () => {
beforeEach(() => {
- utilSpy = jest.spyOn(UtilApi, "logs");
jest.useFakeTimers({ advanceTimers: true });
});
afterEach(() => {
- utilSpy.mockClear();
jest.useRealTimers();
});
- it("should call UtilApi.logs every 1 second", async () => {
+ it("should fetch /api/logger/logs at least once on mount", async () => {
fetchMock.get("path:/api/logger/logs", []);
setup();
await waitFor(() => {
- expect(utilSpy).toHaveBeenCalledTimes(1);
+ expect(countLogsCalls()).toBe(1);
});
});
- it("should skip calls to UtilsApi.logs if last request is still in-flight", async () => {
- fetchMock.get("path:/api/logger/logs", []);
- let resolve: any;
- utilSpy.mockReturnValueOnce(new Promise((res) => (resolve = res)));
+ it("should skip log requests if last request is still in-flight", async () => {
+ let resolveFirst: (logs: unknown) => void = () => {};
+ let callCount = 0;
+ fetchMock.get("path:/api/logger/logs", () => {
+ callCount += 1;
+ if (callCount === 1) {
+ return new Promise<unknown>((res) => {
+ resolveFirst = res;
+ }) as Promise<any>;
+ }
+ return [log];
+ });
setup();
await waitFor(() => {
- expect(utilSpy).toHaveBeenCalledTimes(1);
+ expect(countLogsCalls()).toBe(1);
});
act(() => {
jest.advanceTimersByTime(DEFAULT_POLLING_DURATION_MS + 100);
});
- expect(utilSpy).toHaveBeenCalledTimes(1); // should not have been called
+ expect(countLogsCalls()).toBe(1); // should not have been called
act(() => {
- resolve([log]);
+ resolveFirst([log]);
});
await waitFor(() => {
expect(screen.getByText(new RegExp(log.fqns))).toBeInTheDocument();
@@ -89,7 +95,9 @@ describe("Logs", () => {
act(() => {
jest.advanceTimersByTime(DEFAULT_POLLING_DURATION_MS + 100);
});
- expect(utilSpy).toHaveBeenCalledTimes(2); // should have issued new request
+ await waitFor(() => {
+ expect(countLogsCalls()).toBe(2); // should have issued new request
+ });
});
it("should display no results if there are no logs", async () => {
@@ -164,7 +172,7 @@ describe("Logs", () => {
act(() => {
jest.advanceTimersByTime(DEFAULT_POLLING_DURATION_MS + 100);
});
- expect(utilSpy).toHaveBeenCalledTimes(1);
+ expect(countLogsCalls()).toBe(1);
});
});
diff --git a/frontend/src/metabase/admin/tools/components/Logs/hooks.ts b/frontend/src/metabase/admin/tools/components/Logs/hooks.ts
index 9c770d08ecb..08c1e8b2863 100644
--- a/frontend/src/metabase/admin/tools/components/Logs/hooks.ts
+++ b/frontend/src/metabase/admin/tools/components/Logs/hooks.ts
@@ -1,62 +1,37 @@
-import { useInterval } from "@mantine/hooks";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { useMount, useUnmount } from "react-use";
-import { t } from "ttag";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { UtilApi } from "metabase/services";
+import { useListLogsQuery } from "metabase/api/logger";
import type { Log } from "metabase-types/api";
import { maybeMergeLogs } from "./utils";
export function usePollingLogsQuery(pollingDurationMs: number) {
- const [loaded, setLoaded] = useState(false);
- const [error, setError] = useState<any>(null);
- const [logs, setLogs] = useState<Log[]>([]);
+ const {
+ data: newLogs,
+ isSuccess,
+ error: queryError,
+ } = useListLogsQuery(undefined, { pollingInterval: pollingDurationMs });
- const isMountedRef = useRef(false);
- const isFetchingRef = useRef(false);
+ const [logs, setLogs] = useState<Log[]>([]);
- const fetchLogs = async () => {
- if (isFetchingRef.current) {
- console.warn("skipping logs request as a request is currently in flight");
- return;
+ useEffect(() => {
+ if (newLogs) {
+ setLogs((previousLogs) => maybeMergeLogs(previousLogs, newLogs));
}
+ }, [newLogs]);
- try {
- isFetchingRef.current = true;
- const newLogs: Log[] = await UtilApi.logs();
- if (isMountedRef.current) {
- setLoaded(true);
- setError(null);
- setLogs((logs) => maybeMergeLogs(logs, newLogs));
- isFetchingRef.current = false;
- }
- } catch (err: any) {
- console.error(err);
- const msg = err?.data?.message ?? err.message ?? t`An error occurred.`;
- if (isMountedRef.current) {
- setError(msg);
- isFetchingRef.current = false;
- }
+ const error = useMemo(() => {
+ if (!queryError) {
+ return null;
}
- };
-
- const pollingInterval = useInterval(fetchLogs, pollingDurationMs);
-
- // keep track of mounted state to avoid settings state after unmount
- // clear timeout that is polling for logs
- useMount(() => {
- isMountedRef.current = true;
- fetchLogs();
- pollingInterval.start();
- });
-
- useUnmount(() => {
- isMountedRef.current = false;
- pollingInterval.stop();
- });
-
- return { loaded, error, logs };
+ const errorWithData = queryError as {
+ data?: { message?: string };
+ message?: string;
+ };
+ return errorWithData.data?.message ?? errorWithData.message ?? null;
+ }, [queryError]);
+
+ return { loaded: isSuccess, error, logs };
}
export function useTailLogs(logs: Log[]) {
diff --git a/frontend/src/metabase/admin/tools/components/Logs/utils.ts b/frontend/src/metabase/admin/tools/components/Logs/utils.ts
index 81f1305b917..dea114afd92 100644
--- a/frontend/src/metabase/admin/tools/components/Logs/utils.ts
+++ b/frontend/src/metabase/admin/tools/components/Logs/utils.ts
@@ -63,7 +63,7 @@ export function maybeMergeLogs(logs: Log[], newLogs: Log[]) {
const newestLog = _.first(newLogs);
const hasFetchedNewLogs = newestLog && !hasLog(logs, newestLog);
if (hasFetchedNewLogs) {
- return mergeLogs([logs, newLogs.reverse()]);
+ return mergeLogs([logs, newLogs.toReversed()]);
}
return logs;
}
diff --git a/frontend/src/metabase/api/bug-report.ts b/frontend/src/metabase/api/bug-report.ts
index e4f8994b107..b3874b0f3a5 100644
--- a/frontend/src/metabase/api/bug-report.ts
+++ b/frontend/src/metabase/api/bug-report.ts
@@ -1,4 +1,4 @@
-import type { ErrorPayload } from "metabase-types/api";
+import type { BugReportDetails, ErrorPayload } from "metabase-types/api";
import { Api } from "./api";
@@ -18,7 +18,14 @@ export const bugReportApi = Api.injectEndpoints({
body,
}),
}),
+ getBugReportDetails: builder.query<BugReportDetails, void>({
+ query: () => "/api/bug-reporting/details",
+ }),
}),
});
-export const { useSendBugReportMutation } = bugReportApi;
+export const {
+ useSendBugReportMutation,
+ useGetBugReportDetailsQuery,
+ useLazyGetBugReportDetailsQuery,
+} = bugReportApi;
diff --git a/frontend/src/metabase/api/logger.ts b/frontend/src/metabase/api/logger.ts
index 8ea8f0a4496..41fef45a413 100644
--- a/frontend/src/metabase/api/logger.ts
+++ b/frontend/src/metabase/api/logger.ts
@@ -1,4 +1,8 @@
-import type { AdjustLogLevelsRequest, LoggerPreset } from "metabase-types/api";
+import type {
+ AdjustLogLevelsRequest,
+ Log,
+ LoggerPreset,
+} from "metabase-types/api";
import { Api } from "./api";
import { provideLoggerPresetListTags } from "./tags";
@@ -10,6 +14,9 @@ export const loggerApi = Api.injectEndpoints({
providesTags: (response) =>
response ? provideLoggerPresetListTags(response) : [],
}),
+ listLogs: builder.query<Log[], void>({
+ query: () => "/api/logger/logs",
+ }),
adjustLogLevels: builder.mutation<void, AdjustLogLevelsRequest>({
query: (body) => ({
url: "/api/logger/adjustment",
@@ -28,6 +35,8 @@ export const loggerApi = Api.injectEndpoints({
export const {
useListLoggerPresetsQuery,
+ useListLogsQuery,
+ useLazyListLogsQuery,
useAdjustLogLevelsMutation,
useResetLogLevelsMutation,
} = loggerApi;
diff --git a/frontend/src/metabase/api/session.ts b/frontend/src/metabase/api/session.ts
index 68a5af5721f..364bf3f93d0 100644
--- a/frontend/src/metabase/api/session.ts
+++ b/frontend/src/metabase/api/session.ts
@@ -33,6 +33,13 @@ export const sessionApi = Api.injectEndpoints({
body: { email },
}),
}),
+ checkPassword: builder.mutation<void, { password: string }>({
+ query: (body) => ({
+ method: "POST",
+ url: "/api/session/password-check",
+ body,
+ }),
+ }),
getSessionProperties: builder.query<EnterpriseSettings, void>({
query: () => ({
method: "GET",
@@ -60,6 +67,7 @@ export const sessionApi = Api.injectEndpoints({
export const {
useGetPasswordResetTokenStatusQuery,
useForgotPasswordMutation,
+ useCheckPasswordMutation,
useGetSessionPropertiesQuery,
} = sessionApi;
diff --git a/frontend/src/metabase/auth/actions.ts b/frontend/src/metabase/auth/actions.ts
index 72f24e7179e..55e137830cb 100644
--- a/frontend/src/metabase/auth/actions.ts
+++ b/frontend/src/metabase/auth/actions.ts
@@ -1,5 +1,4 @@
import { type UnknownAction, createAction } from "@reduxjs/toolkit";
-import { getIn } from "icepick";
import { push } from "react-router-redux";
import { loadLocalization } from "metabase/api/localization";
@@ -9,11 +8,10 @@ import { clearCurrentUser, refreshCurrentUser } from "metabase/redux/user";
import { createAsyncThunk } from "metabase/redux/utils";
import { getSetting } from "metabase/selectors/settings";
import { getUser } from "metabase/selectors/user";
-import { SessionApi, UtilApi } from "metabase/services";
+import { SessionApi } from "metabase/services";
import * as Urls from "metabase/urls";
import { isSmallScreen, reload } from "metabase/utils/dom";
import { isResourceNotFoundError } from "metabase/utils/errors";
-import { passwordComplexityDescription } from "metabase/utils/password";
import type { LoginData } from "./types";
@@ -166,19 +164,6 @@ export const resetPassword = createAsyncThunk(
},
);
-export const validatePassword = async (password: string) => {
- const error = passwordComplexityDescription(password);
- if (error) {
- return error;
- }
-
- try {
- await UtilApi.password_check({ password });
- } catch (error) {
- return getIn(error, ["data", "errors", "password"]);
- }
-};
-
const initiateSLO = async () => {
try {
return await SessionApi.slo();
diff --git a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
index bd28d590264..0025df04341 100644
--- a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
+++ b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
@@ -6,10 +6,11 @@ import { t } from "ttag";
import { useGetPasswordResetTokenStatusQuery } from "metabase/api";
import { Button } from "metabase/common/components/Button";
import { Link } from "metabase/common/components/Link";
+import { useValidatePassword } from "metabase/common/hooks";
import { useToast } from "metabase/common/hooks/use-toast";
import { useDispatch } from "metabase/redux";
-import { resetPassword, validatePassword } from "../../actions";
+import { resetPassword } from "../../actions";
import type { ResetPasswordData } from "../../types";
import { AuthLayout } from "../AuthLayout";
import { ResetPasswordForm } from "../ResetPasswordForm";
@@ -35,6 +36,7 @@ export const ResetPassword = ({
const email = location?.query?.email;
const dispatch = useDispatch();
const [sendToast] = useToast();
+ const validatePassword = useValidatePassword();
const { data: status, isLoading } =
useGetPasswordResetTokenStatusQuery(token);
diff --git a/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts b/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
index 98d7c5ee7c6..b75b7a5872c 100644
--- a/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
+++ b/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
@@ -1,9 +1,11 @@
import { useAsync } from "react-use";
import { t } from "ttag";
+import { useLazyGetBugReportDetailsQuery } from "metabase/api/bug-report";
+import { useLazyListLogsQuery } from "metabase/api/logger";
import { useSelector } from "metabase/redux";
import { getUser, getUserIsAdmin } from "metabase/selectors/user";
-import { MetabaseApi, UtilApi } from "metabase/services";
+import { MetabaseApi } from "metabase/services";
import type { ErrorPayload, ReportableEntityName } from "./types";
import { getBrowserInfo, getEntityDetails, hasQueryData } from "./utils";
@@ -26,6 +28,8 @@ export const useErrorInfo = (
const currentUser = useSelector(getUser);
const isAdmin = useSelector(getUserIsAdmin);
const location = window.location.href;
+ const [getBugReportDetails] = useLazyGetBugReportDetailsQuery();
+ const [listLogs] = useLazyListLogsQuery();
return useAsync(async () => {
if (!enabled) {
@@ -45,11 +49,11 @@ export const useErrorInfo = (
const entityInfoRequest = getEntityDetails({ entity, id, isAdHoc });
const bugReportDetailsRequest = isAdmin
- ? UtilApi.bug_report_details().catch(nullOnCatch)
+ ? getBugReportDetails().unwrap().catch(nullOnCatch)
: Promise.resolve(null);
const logsRequest: any = isAdmin
- ? UtilApi.logs().catch(nullOnCatch)
+ ? listLogs().unwrap().catch(nullOnCatch)
: Promise.resolve(null);
const frontendErrors = console?.errorBuffer?.map?.((errArray) =>
@@ -115,7 +119,7 @@ export const useErrorInfo = (
};
return payload;
- }, [enabled]);
+ }, [enabled, getBugReportDetails, listLogs]);
};
const nullOnCatch = () => null;
diff --git a/frontend/src/metabase/common/hooks/index.ts b/frontend/src/metabase/common/hooks/index.ts
index c36c2ee15da..727612c3f66 100644
--- a/frontend/src/metabase/common/hooks/index.ts
+++ b/frontend/src/metabase/common/hooks/index.ts
@@ -12,6 +12,7 @@ export * from "./use-temp-storage";
export * from "./use-temporary-state";
export * from "./use-toast";
export * from "./use-url-with-utm";
+export * from "./use-validate-password";
export { useStoreUrl } from "./use-store-url/use-store-url";
export * from "./use-capture-event";
export * from "./use-progressive-loader";
diff --git a/frontend/src/metabase/common/hooks/use-validate-password.ts b/frontend/src/metabase/common/hooks/use-validate-password.ts
new file mode 100644
index 00000000000..8523c169805
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-validate-password.ts
@@ -0,0 +1,25 @@
+import { getIn } from "icepick";
+import { useCallback } from "react";
+
+import { useCheckPasswordMutation } from "metabase/api";
+import { passwordComplexityDescription } from "metabase/utils/password";
+
+export const useValidatePassword = () => {
+ const [checkPassword] = useCheckPasswordMutation();
+
+ return useCallback(
+ async (password: string): Promise<string | undefined> => {
+ const error = passwordComplexityDescription(password);
+ if (error) {
+ return error;
+ }
+
+ try {
+ await checkPassword({ password }).unwrap();
+ } catch (error) {
+ return getIn(error, ["data", "errors", "password"]);
+ }
+ },
+ [checkPassword],
+ );
+};
diff --git a/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/SetupJwtStep.tsx b/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/SetupJwtStep.tsx
index fb16b62e877..0f814e06181 100644
--- a/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/SetupJwtStep.tsx
+++ b/frontend/src/metabase/embedding/embedding-hub/components/SetupSsoPage/SetupJwtStep.tsx
@@ -3,13 +3,14 @@ import { useCallback, useEffect, useState } from "react";
import { t } from "ttag";
import { useUpdateSettingsMutation } from "metabase/api";
+import { useLazyGenerateRandomTokenQuery } from "metabase/api/util";
import { useSetting, useToast } from "metabase/common/hooks";
-import { UtilApi } from "metabase/services";
import { Button, Group, Stack, Text, TextInput } from "metabase/ui";
export const SetupJwtStep = ({ onSuccess }: { onSuccess: () => void }) => {
const [sendToast] = useToast();
const [updateSettings, { isLoading }] = useUpdateSettingsMutation();
+ const [generateRandomToken] = useLazyGenerateRandomTokenQuery();
const existingJwtIdentityProviderUri = useSetting(
"jwt-identity-provider-uri",
@@ -26,7 +27,7 @@ export const SetupJwtStep = ({ onSuccess }: { onSuccess: () => void }) => {
const handleEnableJwt = useCallback(async () => {
try {
- const { token } = await UtilApi.random_token();
+ const { token } = await generateRandomToken().unwrap();
await updateSettings({
"jwt-identity-provider-uri": jwtIdentityProviderUri.trim(),
@@ -43,7 +44,13 @@ export const SetupJwtStep = ({ onSuccess }: { onSuccess: () => void }) => {
message: t`Failed to enable JWT authentication`,
});
}
- }, [jwtIdentityProviderUri, updateSettings, sendToast, onSuccess]);
+ }, [
+ jwtIdentityProviderUri,
+ generateRandomToken,
+ updateSettings,
+ sendToast,
+ onSuccess,
+ ]);
return (
<Stack gap="lg">
diff --git a/frontend/src/metabase/nav/components/AppSwitcher/useHelpLink.ts b/frontend/src/metabase/nav/components/AppSwitcher/useHelpLink.ts
index d7cc436f24d..e552df990f3 100644
--- a/frontend/src/metabase/nav/components/AppSwitcher/useHelpLink.ts
+++ b/frontend/src/metabase/nav/components/AppSwitcher/useHelpLink.ts
@@ -1,10 +1,8 @@
-import { useEffect, useState } from "react";
-
+import { useGetBugReportDetailsQuery } from "metabase/api/bug-report";
import { useSetting } from "metabase/common/hooks";
import { getHelpUrl } from "metabase/common/utils/help-url";
import { useSelector } from "metabase/redux";
import { getIsPaidPlan } from "metabase/selectors/settings";
-import { UtilApi } from "metabase/services";
import { getUser } from "../../../selectors/user";
@@ -13,22 +11,19 @@ export const useHelpLink = (): { visible: boolean; href: string } => {
const helpLinkCustomDestinationSetting = useSetting(
"help-link-custom-destination",
);
- const [bugReportDetails, setBugReportDetails] = useState(null);
const user = useSelector(getUser);
const isAdmin = !!user?.is_superuser;
const isPaidPlan = useSelector(getIsPaidPlan);
const version = useSetting("version");
+ const { data: bugReportDetails } = useGetBugReportDetailsQuery(undefined, {
+ skip: !isAdmin || !isPaidPlan,
+ });
+
const compactBugReportDetailsForUrl = bugReportDetails
? encodeURIComponent(JSON.stringify(bugReportDetails))
: undefined;
- useEffect(() => {
- if (isAdmin && isPaidPlan) {
- UtilApi.bug_report_details().then(setBugReportDetails);
- }
- }, [isAdmin, isPaidPlan]);
-
const visible = helpLinkSetting !== "hidden";
const showPremiumHelp = isAdmin && isPaidPlan;
const href =
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index d64681b5e99..fafe6085ba6 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -1,4 +1,4 @@
-import api, { DELETE, GET, POST, PUT } from "metabase/api/legacy-client";
+import { DELETE, GET, POST, PUT } from "metabase/api/legacy-client";
import { isNative } from "metabase/common/utils/card";
import { isEmbedPreview } from "metabase/embedding/config";
import Question from "metabase-lib/v1/Question";
@@ -358,22 +358,6 @@ export const UserApi = {
update_qbnewb: PUT("/api/user/:id/modal/qbnewb"),
};
-// TODO: move to all functions to RTK (metabase/api/util.ts)
-export const UtilApi = {
- password_check: POST("/api/session/password-check"),
- random_token: GET("/api/util/random_token"),
- logs: GET("/api/logger/logs"),
- bug_report_details: GET("/api/bug-reporting/details"),
- get_connection_pool_details_url: () => {
- // this one does not need an HTTP verb because it's opened as an external link
- // and it can be deployed at subpath
- const path = "/api/bug-reporting/connection-pool-details";
- const { href } = new URL(api.basename + path, location.origin);
-
- return href;
- },
-};
-
export const FrontendErrorsApi = {
report: POST("/api/frontend-errors"),
};
diff --git a/frontend/src/metabase/setup/components/UserForm/UserForm.tsx b/frontend/src/metabase/setup/components/UserForm/UserForm.tsx
index f0c8d23795a..9a599bfe675 100644
--- a/frontend/src/metabase/setup/components/UserForm/UserForm.tsx
+++ b/frontend/src/metabase/setup/components/UserForm/UserForm.tsx
@@ -5,9 +5,9 @@ import * as Yup from "yup";
import { FormInput } from "metabase/common/components/FormInput";
import { FormSubmitButton } from "metabase/common/components/FormSubmitButton";
+import { useValidatePassword } from "metabase/common/hooks";
import { Form, FormProvider, useFormSubmitButton } from "metabase/forms";
import type { UserInfo } from "metabase/redux/store";
-import { validatePassword } from "metabase/setup/utils";
import { Flex } from "metabase/ui";
import * as Errors from "metabase/utils/errors";
@@ -38,11 +38,12 @@ interface UserFormProps {
onSubmit: (user: UserInfo) => Promise<void>;
}
-const validationContext = {
- onValidatePassword: _.memoize(validatePassword),
-};
-
export const UserForm = ({ user, isHosted, onSubmit }: UserFormProps) => {
+ const validatePassword = useValidatePassword();
+ const validationContext = useMemo(
+ () => ({ onValidatePassword: _.memoize(validatePassword) }),
+ [validatePassword],
+ );
const initialValues = useMemo(() => {
return user ?? USER_SCHEMA.getDefault();
}, [user]);
diff --git a/frontend/src/metabase/setup/utils.ts b/frontend/src/metabase/setup/utils.ts
index c5dd978823b..dd3794c462c 100644
--- a/frontend/src/metabase/setup/utils.ts
+++ b/frontend/src/metabase/setup/utils.ts
@@ -1,9 +1,6 @@
-import { getIn } from "icepick";
import _ from "underscore";
import type { Locale } from "metabase/redux/store";
-import { UtilApi } from "metabase/services";
-import { passwordComplexityDescription } from "metabase/utils/password";
import type { LocaleData } from "metabase-types/api";
import { SUBSCRIBE_TOKEN, SUBSCRIBE_URL } from "./constants";
@@ -30,19 +27,6 @@ export const getDefaultLocale = (
);
};
-export const validatePassword = async (password: string) => {
- const error = passwordComplexityDescription(password);
- if (error) {
- return error;
- }
-
- try {
- await UtilApi.password_check({ password });
- } catch (error) {
- return getIn(error, ["data", "errors", "password"]);
- }
-};
-
export const subscribeToNewsletter = (email: string) => {
const body = new FormData();
body.append("EMAIL", email);