Skip to content

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

Have a separate email content for user joining through setup invitation (#63778)

Andersonb5a9d7457fdf
diff --git a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
index 8fe91c7c213..eef82f63a92 100644
--- a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
+++ b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
@@ -1,3 +1,4 @@
+import type { Location } from "history";
import { useCallback } from "react";
import { replace } from "react-router-redux";
import { t } from "ttag";
@@ -21,12 +22,15 @@ interface ResetPasswordQueryParams {
interface ResetPasswordProps {
params: ResetPasswordQueryParams;
+ location?: Location<{ redirect?: string }>;
}
export const ResetPassword = ({
params,
+ location,
}: ResetPasswordProps): JSX.Element | null => {
const { token } = params;
+ const redirectUrl = location?.query?.redirect;
const dispatch = useDispatch();
const { data: status, isLoading } =
useGetPasswordResetTokenStatusQuery(token);
@@ -34,10 +38,10 @@ export const ResetPassword = ({
const handlePasswordSubmit = useCallback(
async ({ password }: ResetPasswordData) => {
await dispatch(resetPassword({ token, password })).unwrap();
- dispatch(replace("/"));
+ dispatch(replace(redirectUrl || "/"));
dispatch(addUndo({ message: t`You've updated your password.` }));
},
- [token, dispatch],
+ [token, dispatch, redirectUrl],
);
if (isLoading) {
diff --git a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.unit.spec.tsx b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.unit.spec.tsx
index a85c9895c5c..8a7c0f53848 100644
--- a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.unit.spec.tsx
+++ b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.unit.spec.tsx
@@ -8,7 +8,7 @@ import {
setupPropertiesEndpoints,
setupResetPasswordEndpoint,
} from "__support__/server-mocks";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
import { createMockSettings, createMockUser } from "metabase-types/api/mocks";
import { ResetPassword } from "./ResetPassword";
@@ -24,9 +24,10 @@ const setup = ({ isTokenValid = true }: SetupOpts = {}) => {
setupCurrentUserEndpoint(createMockUser());
setupPropertiesEndpoints(createMockSettings());
- renderWithProviders(
+ return renderWithProviders(
<>
<Route path="/" component={TestHome} />
+ <Route path="/another-page" component={AnotherPage} />
<Route path="/auth/reset_password/:token" component={ResetPassword} />
</>,
{
@@ -37,6 +38,7 @@ const setup = ({ isTokenValid = true }: SetupOpts = {}) => {
};
const TestHome = () => <div>Home</div>;
+const AnotherPage = () => <div>Another page</div>;
describe("ResetPassword", () => {
it("should show a form when token validations succeeds", async () => {
@@ -51,20 +53,44 @@ describe("ResetPassword", () => {
).toBeInTheDocument();
});
- it("should show a success message when the form is submitted", async () => {
- setup({ isTokenValid: true });
- expect(await screen.findByText("New password")).toBeInTheDocument();
+ describe("when form is submitted", () => {
+ const fillAndSubmit = async () => {
+ expect(await screen.findByText("New password")).toBeInTheDocument();
+
+ await userEvent.type(
+ screen.getByLabelText("Create a password"),
+ "#Password#1!",
+ );
+ await userEvent.type(
+ screen.getByLabelText("Confirm your password"),
+ "#Password#1!",
+ );
+ await waitFor(() => {
+ expect(
+ screen.getByRole("button", { name: "Save new password" }),
+ ).toBeEnabled();
+ });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Save new password" }),
+ );
+ };
- await userEvent.type(screen.getByLabelText("Create a password"), "test");
- await userEvent.type(
- screen.getByLabelText("Confirm your password"),
- "test",
- );
- await waitFor(() => {
- expect(screen.getByText("Save new password")).toBeEnabled();
+ it("should redirect to home page by default", async () => {
+ setup({ isTokenValid: true });
+ await fillAndSubmit();
+ expect(await screen.findByText("Home")).toBeInTheDocument();
});
- await userEvent.click(screen.getByText("Save new password"));
- expect(await screen.findByText("Home")).toBeInTheDocument();
+ it("should allow a custom redirect to be specified", async () => {
+ const { history } = setup({ isTokenValid: true });
+
+ act(() => {
+ history?.replace(`/auth/reset_password/token?redirect=/another-page`);
+ });
+
+ await fillAndSubmit();
+ expect(await screen.findByText("Another page")).toBeInTheDocument();
+ });
});
});
diff --git a/frontend/src/metabase/setup/actions.ts b/frontend/src/metabase/setup/actions.ts
index 3fb73923f7c..7ad98674038 100644
--- a/frontend/src/metabase/setup/actions.ts
+++ b/frontend/src/metabase/setup/actions.ts
@@ -173,16 +173,20 @@ export const skipDatabase = createAsyncThunk(
export const SUBMIT_USER_INVITE = "metabase/setup/SUBMIT_USER_INVITE";
export const submitUserInvite = createAsyncThunk(
SUBMIT_USER_INVITE,
- async (inviteInfo: InviteInfo, { dispatch }) => {
- await dispatch(
- userApi.endpoints.createUser.initiate({
- email: inviteInfo.email,
- first_name: inviteInfo.first_name || undefined,
- last_name: inviteInfo.last_name || undefined,
- source: "setup",
- }),
- ).unwrap();
- dispatch(goToNextStep());
+ async (inviteInfo: InviteInfo, { dispatch, rejectWithValue }) => {
+ try {
+ await dispatch(
+ userApi.endpoints.createUser.initiate({
+ email: inviteInfo.email,
+ first_name: inviteInfo.first_name || undefined,
+ last_name: inviteInfo.last_name || undefined,
+ source: "setup",
+ }),
+ ).unwrap();
+ dispatch(goToNextStep());
+ } catch (error) {
+ return rejectWithValue(error);
+ }
},
);
diff --git a/frontend/src/metabase/setup/components/DatabaseStep/DatabaseStep.tsx b/frontend/src/metabase/setup/components/DatabaseStep/DatabaseStep.tsx
index a6ff9d1e181..a399c0497ae 100644
--- a/frontend/src/metabase/setup/components/DatabaseStep/DatabaseStep.tsx
+++ b/frontend/src/metabase/setup/components/DatabaseStep/DatabaseStep.tsx
@@ -4,6 +4,13 @@ import { c, t } from "ttag";
import { useToast } from "metabase/common/hooks";
import { DatabaseForm } from "metabase/databases/components/DatabaseForm";
import { useDispatch, useSelector } from "metabase/lib/redux";
+import {
+ getDatabase,
+ getDatabaseEngine,
+ getInvite,
+ getIsEmailConfigured,
+ getUser,
+} from "metabase/setup";
import { Text } from "metabase/ui";
import type { DatabaseData } from "metabase-types/api";
import type { InviteInfo } from "metabase-types/store";
@@ -14,13 +21,6 @@ import {
submitUserInvite,
updateDatabaseEngine,
} from "../../actions";
-import {
- getDatabase,
- getDatabaseEngine,
- getInvite,
- getIsEmailConfigured,
- getUser,
-} from "../../selectors";
import { useStep } from "../../useStep";
import { ActiveStep } from "../ActiveStep";
import { InactiveStep } from "../InactiveStep";
@@ -54,8 +54,8 @@ export const DatabaseStep = ({ stepLabel }: NumberedStepProps): JSX.Element => {
}
};
- const handleInviteSubmit = (invite: InviteInfo) => {
- dispatch(submitUserInvite(invite));
+ const handleInviteSubmit = async (invite: InviteInfo) => {
+ await dispatch(submitUserInvite(invite)).unwrap();
};
const handleStepCancel = () => {
diff --git a/frontend/src/metabase/setup/components/DatabaseStep/DatabaseStep.unit.spec.tsx b/frontend/src/metabase/setup/components/DatabaseStep/DatabaseStep.unit.spec.tsx
index ccd05258d66..ed420920f60 100644
--- a/frontend/src/metabase/setup/components/DatabaseStep/DatabaseStep.unit.spec.tsx
+++ b/frontend/src/metabase/setup/components/DatabaseStep/DatabaseStep.unit.spec.tsx
@@ -1,4 +1,7 @@
-import { renderWithProviders, screen } from "__support__/ui";
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders, screen, within } from "__support__/ui";
import type { SetupStep } from "metabase/setup/types";
import type { DatabaseData } from "metabase-types/api";
import { createMockDatabaseData } from "metabase-types/api/mocks";
@@ -52,7 +55,7 @@ describe("DatabaseStep", () => {
expect(screen.getByText("Connecting to Test")).toBeInTheDocument();
});
- it("should render a user invite form", () => {
+ it("should render a user invite form", async () => {
setup({
isEmailConfigured: true,
});
@@ -60,5 +63,53 @@ describe("DatabaseStep", () => {
expect(
screen.getByText("Need help connecting to your data?"),
).toBeInTheDocument();
+
+ await userEvent.click(
+ within(screen.getByRole("button", { name: "Setup section" })).getByRole(
+ "img",
+ { name: "chevrondown icon" },
+ ),
+ );
+
+ expect(screen.getByTestId("invite-user-form")).toBeInTheDocument();
+ });
+
+ it("should handle status properly when invitation request fails", async () => {
+ jest.spyOn(console, "error").mockImplementation(() => {});
+
+ setup({
+ isEmailConfigured: true,
+ });
+
+ const chevronDownIcon = within(
+ screen.getByRole("button", { name: "Setup section" }),
+ ).getByRole("img", { name: "chevrondown icon" });
+
+ await userEvent.click(chevronDownIcon);
+
+ const form = screen.getByTestId("invite-user-form");
+
+ expect(within(form).getByRole("button")).toBeDisabled();
+
+ await userEvent.type(within(form).getByLabelText("First name"), "Jack");
+ await userEvent.type(within(form).getByLabelText("Last name"), "Chan");
+ await userEvent.type(
+ within(form).getByLabelText("Email"),
+ );
+
+ expect(within(form).getByRole("button")).toBeEnabled();
+
+ fetchMock.postOnce("/api/user", {
+ status: 400,
+ body: {
+ errors: {
+ email: "This email is not valid",
+ },
+ },
+ });
+ await userEvent.click(within(form).getByRole("button"));
+ await within(form).findByRole("button", { name: "Failed" });
+ await within(form).findByText(/This email is not valid/);
});
});
diff --git a/frontend/src/metabase/setup/components/InviteUserForm/InviteUserForm.tsx b/frontend/src/metabase/setup/components/InviteUserForm/InviteUserForm.tsx
index 0dcb6ec97a2..7dee0bab047 100644
--- a/frontend/src/metabase/setup/components/InviteUserForm/InviteUserForm.tsx
+++ b/frontend/src/metabase/setup/components/InviteUserForm/InviteUserForm.tsx
@@ -46,7 +46,7 @@ export const InviteUserForm = ({
validationContext={user}
onSubmit={onSubmit}
>
- <Form>
+ <Form data-testid="invite-user-form">
<UserFieldGroup>
<FormInput
name="first_name"
diff --git a/src/metabase/channel/email/new_user_invite.hbs b/src/metabase/channel/email/new_user_invite.hbs
index 5e3aeeca787..136bfc0761a 100644
--- a/src/metabase/channel/email/new_user_invite.hbs
+++ b/src/metabase/channel/email/new_user_invite.hbs
@@ -1,4 +1,5 @@
{{> metabase/channel/email/_header.hbs }}
+{{#with payload.event_info.details.invitor as |invitor|}}
<div style="padding-top: 40px; padding-left: 16px; padding-bottom: 96px; padding-right: 16px; box-sizing: border-box; width: 100%; max-width: 600px; background-color: #FFFFFF; border-radius: 24px; border: 1px solid #dcdfe0; margin-top: 32px; margin-left: auto; margin-right: auto;">
<div style="margin-bottom: 32px; text-align: center; width: 56px; height: 56px; padding-top: 5px; box-sizing: border-box; padding-bottom: 5px; margin-left: auto; margin-right: auto;">
<img height="46" src="{{context.application_logo_url}}" alt="{{context.application_name}} logo" />
@@ -7,7 +8,11 @@
{{#if payload.event_info.object.is_from_setup}}
<div style="max-width: 504px; text-align: center; margin-left: auto; margin-right: auto;">
<h2 style="font-weight: 400; color: #2F3C45; line-height: 36px; margin-top: 0; font-size: 27px;">
- {{payload.event_info.details.invitor.first_name}} could use your help setting up {{context.application_name}}
+ {{#if invitor.first_name}}
+ {{invitor.first_name}} could use your help setting up {{context.application_name}}
+ {{else}}
+ You are invited to help setting up {{context.application_name}}
+ {{/if}}
</h2>
</div>
<div style="max-width: 504px; text-align: center; margin-left: auto; margin-right: auto;">
@@ -15,7 +20,11 @@
{{context.application_name}} is a simple and powerful analytics tool that lets you easily ask questions and get answers about your company’s data.
</p>
<p style="margin-bottom: 0; line-height: 24px; color: #656F76; font-size: 15px;">
- Your {{context.application_name}} is up and running, but {{payload.event_info.details.invitor.first_name}} needs you to connect your data. You'll probably need:
+ {{#if invitor.first_name}}
+ Your {{context.application_name}} is up and running, but {{invitor.first_name}} needs you to connect your data. You'll probably need:
+ {{else}}
+ Your {{context.application_name}} is up and running, but your help is needed to connect data. You'll probably need:
+ {{/if}}
</p>
<ul style="text-align: left; margin-bottom: 32px; font-size: 15px; margin-top: 20px; padding-left: 30px;">
<li>Database type (Redshift, Snowflake, etc...)</li>
@@ -23,11 +32,14 @@
<li>Username and password</li>
</ul>
</div>
- {{/if}}
- {{#unless payload.event_info.object.is_from_setup}}
+ {{else}}
<div style="max-width: 504px; text-align: center; margin-left: auto; margin-right: auto;">
<h2 style="font-weight: 400; color: #2F3C45; line-height: 36px; margin-top: 0; font-size: 27px;">
- {{payload.event_info.details.invitor.first_name}} wants you to join them on {{context.application_name}}
+ {{#if invitor.first_name}}
+ {{invitor.first_name}} wants you to join them on {{context.application_name}}
+ {{else}}
+ You are invited to join {{context.application_name}}
+ {{/if}}
</h2>
</div>
<div style="max-width: 504px; text-align: center; margin-left: auto; margin-right: auto;">
@@ -35,7 +47,7 @@
{{context.application_name}} is a simple and powerful analytics tool that lets you easily ask questions and get answers about your company’s data.
</p>
</div>
- {{/unless}}
+ {{/if}}
<div style="padding-right: 0; padding-left: 0; text-align: center; width: 100%;">
<a
style="font-size: 15px; padding-top: 16px; padding-bottom: 16px; cursor: pointer; text-decoration: none; font-weight: 700; border-radius: 12px; background-color: #358CD9; color: #fff; line-height: 16px; display: inline-block; margin-left: auto; margin-right: auto; min-width: 200px;"
@@ -51,6 +63,7 @@
{{/if}}
</div>
</div>
+{{/with}}
</div>
</body>
</html>
diff --git a/src/metabase/notification/payload/impl/system_event.clj b/src/metabase/notification/payload/impl/system_event.clj
index e0197ed7419..b702433c95b 100644
--- a/src/metabase/notification/payload/impl/system_event.clj
+++ b/src/metabase/notification/payload/impl/system_event.clj
@@ -11,15 +11,17 @@
[metabase.util.malli :as mu]))
(defn- join-url
- [user-id]
+ [user-id redirect]
;; TODO: the reset token should come from the event-info, not generated here!
(let [reset-token (user/set-password-reset-token! user-id)
should-link-to-login-page (and (sso/sso-enabled?)
(not (session/enable-password-login)))]
(if should-link-to-login-page
(str (system/site-url) "/auth/login")
- ;; NOTE: the new user join url is just a password reset with an indicator that this is a first time user
- (str (user/form-password-reset-url reset-token) "#new"))))
+ ;; NOTE: the new user join url is a password reset route with an indicator that this is a first time user.
+ (str (user/form-password-reset-url reset-token)
+ (when redirect (str "?redirect=" redirect))
+ "#new"))))
(defn- custom-payload
"Returns a map of custom payload for a given topic and event-info.
@@ -27,11 +29,12 @@
Currently we need it to support usecases that our template engines doesn't support such as i18n,
but ideally this should be part of the template."
[topic event-info]
- (case topic
- :event/user-invited
- {:user_invited_email_subject (trs "You''re invited to join {0}''s {1}" (appearance/site-name) (messages/app-name-trs))
- :user_invited_join_url (-> event-info :object :id join-url)}
- {}))
+ (let [{user-id :id from-setup :is_from_setup} (:object event-info)]
+ (case topic
+ :event/user-invited
+ {:user_invited_email_subject (trs "You''re invited to join {0}''s {1}" (appearance/site-name) (messages/app-name-trs))
+ :user_invited_join_url (join-url user-id (when from-setup "/admin/databases/create"))}
+ {})))
(mu/defmethod notification.payload/payload :notification/system-event
[notification-info :- ::notification.payload/Notification]
diff --git a/src/metabase/users/api.clj b/src/metabase/users/api.clj
index 50f361f4327..c8dc5abe012 100644
--- a/src/metabase/users/api.clj
+++ b/src/metabase/users/api.clj
@@ -372,8 +372,10 @@
(u/select-keys-when body
:non-nil [:first_name :last_name :email :password :login_attributes])
@api/*current-user*
- false))]
+ (= source "setup")))]
(maybe-set-user-group-memberships! new-user-id user_group_memberships)
+ (when (= source "setup")
+ (maybe-set-user-permissions-groups! new-user-id [(perms/all-users-group) (perms/admin-group)]))
(analytics/track-event! :snowplow/invite
{:event :invite-sent
:invited-user-id new-user-id
diff --git a/test/metabase/notification/payload/impl/system_event_test.clj b/test/metabase/notification/payload/impl/system_event_test.clj
index 8e09b09f419..79cfd2d7eba 100644
--- a/test/metabase/notification/payload/impl/system_event_test.clj
+++ b/test/metabase/notification/payload/impl/system_event_test.clj
@@ -109,13 +109,13 @@
count)))))))
(deftest user-invited-email-content-test
- (let [check (fn [sent-from-setup? expected-subject regexes]
+ (let [check (fn [sent-from-setup? expected-subject regexes invitor-name]
(let [email (mt/with-temporary-setting-values
[site-url "https://metabase.com"
site-name "SuperStar"]
(-> (notification.tu/with-captured-channel-send!
(publish-user-invited-event! (t2/select-one :model/User :email "[email protected]")
- {:first_name "Ngoc" :email "[email protected]"}
+ {:first_name invitor-name :email "[email protected]"}
sent-from-setup?))
:channel/email first))]
(is (= {:recipients #{"[email protected]"}
@@ -124,30 +124,49 @@
:message [(zipmap (map str regexes) (repeat true))]
:recipient-type :cc}
(apply mt/summarize-multipart-single-email email regexes)))))]
- (testing "sent from invite page"
+ (testing "sent from people page"
(check false
"You're invited to join SuperStar's Metabase"
[#"Ngoc wants you to join them on Metabase"
- #"<a[^>]*href=\"https?://metabase\.com/auth/reset_password/.*#new\"[^>]*>Join now</a>"])
+ #"<a[^>]*href=\"https?://metabase\.com/auth/reset_password/.*#new\"[^>]*>Join now</a>"]
+ "Ngoc")
(testing "with sso enabled"
(with-redefs [sso.settings/sso-enabled? (constantly true)
session.settings/enable-password-login (constantly false)]
(check false
"You're invited to join SuperStar's Metabase"
- [#"<a[^>]*href=\"https?://metabase\.com/auth/login\"[^>]*>Join now</a>"]))))
+ [#"<a[^>]*href=\"https?://metabase\.com/auth/login\"[^>]*>Join now</a>"]
+ "Ngoc")))
+
+ (testing "with invitor's first_name not defined"
+ (check false
+ "You're invited to join SuperStar's Metabase"
+ [#"You are invited to join Metabase"
+ #"<a[^>]*href=\"https?://metabase\.com/auth/reset_password/.*#new\"[^>]*>Join now</a>"]
+ nil)))
(testing "subject is translated"
(mt/with-mock-i18n-bundles! {"es" {:messages {"You''re invited to join {0}''s {1}"
"Estás invitado a unirte al {0} de {1}"}}}
(mt/with-temporary-setting-values [site-locale "es"]
- (check false "Estás invitado a unirte al SuperStar de Metabase" []))))
+ (check false "Estás invitado a unirte al SuperStar de Metabase" [] "Ngoc"))))
(testing "sent from setup page"
(check true
"You're invited to join SuperStar's Metabase"
- [#"Ngoc could use your help setting up Metabase"
- #"<a[^>]*href=\"https?://metabase\.com/auth/reset_password/.*#new\"[^>]*>"]))))
+ [#"Kratos could use your help setting up Metabase"
+ #"Your Metabase is up and running, but Kratos needs you to connect your data. You'll probably need:"
+ #"<a[^>]*href=\"https?://metabase\.com/auth/reset_password/.*\?redirect(&#x3D;|=)/admin/databases/create#new\"[^>]*>"]
+ "Kratos")
+
+ (testing "with invitor's first_name not defined"
+ (check true
+ "You're invited to join SuperStar's Metabase"
+ [#"You are invited to help setting up Metabase"
+ #"Your Metabase is up and running, but your help is needed to connect data. You'll probably need:"
+ #"<a[^>]*href=\"https?://metabase\.com/auth/reset_password/.*\?redirect(&#x3D;|=)/admin/databases/create#new\"[^>]*>"]
+ nil)))))
(deftest notification-create-email-test
(mt/with-temporary-setting-values [site-url "https://metabase.com"]
diff --git a/test/metabase/users/api_test.clj b/test/metabase/users/api_test.clj
index f5dfc52aa03..d0e65d606ec 100644
--- a/test/metabase/users/api_test.clj
+++ b/test/metabase/users/api_test.clj
@@ -744,6 +744,20 @@
(defmacro ^:private with-temp-user-email! [[email-binding] & body]
`(do-with-temp-user-email! (fn [~email-binding] ~@body)))
+(deftest create-user-setup-source-test
+ (testing "POST /api/user"
+ (testing "Inviting a teammate from the setup page should create a user with admin permissions"
+ (mt/with-model-cleanup [:model/User]
+ (mt/with-fake-inbox
+ (let [resp (mt/user-http-request :crowberto :post 200 "user"
+ {:first_name (mt/random-name)
+ :last_name (mt/random-name)
+ :email (mt/random-email)
+ :source "setup"})]
+ (is (= [{:id (:id (perms-group/all-users))} {:id (:id (perms-group/admin))}]
+ (:user_group_memberships resp)))
+ (is (true? (:is_superuser resp)))))))))
+
(deftest create-user-set-groups-test
(testing "POST /api/user"
(mt/with-premium-features #{}