Skip to content

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

Invite someone to view a dashboard or question (#76444)

Andrei Chernykheae64a014a68
diff --git a/e2e/test/scenarios/admin-2/people.cy.spec.js b/e2e/test/scenarios/admin-2/people.cy.spec.js
index 193c2dd75bb..7567779fbd2 100644
--- a/e2e/test/scenarios/admin-2/people.cy.spec.js
+++ b/e2e/test/scenarios/admin-2/people.cy.spec.js
@@ -142,8 +142,6 @@ describe("scenarios > admin > people", () => {
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText(`${FULL_NAME} has been added`);
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Show").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText("Done").click();
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
@@ -166,8 +164,6 @@ describe("scenarios > admin > people", () => {
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText(`${email} has been added`);
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Show").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
cy.findByText("Done").click();
// eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
diff --git a/e2e/test/scenarios/sharing/invite-to-view.cy.spec.js b/e2e/test/scenarios/sharing/invite-to-view.cy.spec.js
new file mode 100644
index 00000000000..d08d17e1720
--- /dev/null
+++ b/e2e/test/scenarios/sharing/invite-to-view.cy.spec.js
@@ -0,0 +1,184 @@
+const { H } = cy;
+import { USER_GROUPS } from "e2e/support/cypress_data";
+import {
+ ORDERS_DASHBOARD_ID,
+ ORDERS_QUESTION_ID,
+} from "e2e/support/cypress_sample_instance_data";
+
+const { ALL_USERS_GROUP } = USER_GROUPS;
+
+const PASSWORD = "Sup3r-S3cret-Pw!";
+
+const inviteEmail = () =>
+ `invitee-${Math.round(Math.random() * 1_000_000)}@metabase.test`;
+
+/** Open the Share menu on the current dashboard/question and invite `email`. */
+function inviteFromShareMenu(email) {
+ H.openSharingMenu("Invite someone to view this");
+ H.modal().within(() => {
+ cy.findByLabelText(/Email/i).type(email);
+ cy.button("Send invitation").click();
+ });
+}
+
+/** Pull the Join link out of a sent invite email and decode the HTML entities. */
+function joinUrlFromEmail(sent) {
+ return sent.html
+ .match(/href="([^"]*reset_password[^"]*)"/)[1]
+ .replace(/=/g, "=")
+ .replace(/&/g, "&");
+}
+
+/** Set a password on the new-user signup screen reached from a join link. */
+function completeSignup() {
+ cy.findByLabelText("Create a password").type(PASSWORD);
+ cy.findByLabelText("Confirm your password").type(PASSWORD);
+ cy.button("Save new password").click();
+}
+
+function enableGoogleSSO() {
+ H.activateToken("pro-self-hosted");
+ cy.request("PUT", "/api/google/settings", {
+ "google-auth-auto-create-accounts-domain": null,
+ "google-auth-client-id": "example1.apps.googleusercontent.com",
+ "google-auth-enabled": true,
+ });
+}
+
+describe("scenarios > sharing > invite someone to view", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ describe("invite action in the Share menu", () => {
+ it("invites someone to view a dashboard", () => {
+ const email = inviteEmail();
+ cy.intercept("POST", "/api/user").as("createUser");
+
+ H.visitDashboard(ORDERS_DASHBOARD_ID);
+ inviteFromShareMenu(email);
+
+ cy.wait("@createUser").then(({ request }) => {
+ expect(request.body.email).to.eq(email);
+ expect(request.body.invite_target).to.deep.include({
+ type: "dashboard",
+ id: ORDERS_DASHBOARD_ID,
+ });
+ });
+ });
+
+ it("invites someone to view a question", () => {
+ const email = inviteEmail();
+ cy.intercept("POST", "/api/user").as("createUser");
+
+ H.visitQuestion(ORDERS_QUESTION_ID);
+ inviteFromShareMenu(email);
+
+ cy.wait("@createUser").then(({ request }) => {
+ expect(request.body.invite_target).to.deep.include({
+ type: "question",
+ id: ORDERS_QUESTION_ID,
+ });
+ });
+ });
+ });
+
+ describe("invite email", () => {
+ beforeEach(() => H.setupSMTP());
+
+ it("scopes the subject/body to the dashboard and links to it", () => {
+ H.visitDashboard(ORDERS_DASHBOARD_ID);
+ inviteFromShareMenu(inviteEmail());
+
+ H.getInbox().then(({ body: [email] }) => {
+ expect(email.subject).to.contain("invited to view the dashboard");
+ expect(email.html).to.contain(`/dashboard/${ORDERS_DASHBOARD_ID}`);
+ expect(email.html).to.contain(
+ "wants to share a Metabase dashboard with you",
+ );
+ });
+ });
+
+ it("uses the SSO login link (not a password reset) when password login is disabled", () => {
+ enableGoogleSSO();
+ cy.request("PUT", "/api/setting", { "enable-password-login": false });
+
+ H.visitDashboard(ORDERS_DASHBOARD_ID);
+ inviteFromShareMenu(inviteEmail());
+
+ H.getInbox().then(({ body: [email] }) => {
+ expect(email.html).to.match(
+ new RegExp(
+ `/auth/login\\?redirect(=|=)/dashboard/${ORDERS_DASHBOARD_ID}`,
+ ),
+ );
+ expect(email.html).not.to.contain("reset_password");
+ });
+ });
+ });
+
+ describe("landing after signup", () => {
+ beforeEach(() => H.setupSMTP());
+
+ it("lands the invited user on the shared dashboard after they set a password", () => {
+ H.visitDashboard(ORDERS_DASHBOARD_ID);
+ inviteFromShareMenu(inviteEmail());
+
+ H.getInbox().then(({ body: [sent] }) => {
+ cy.signOut();
+ cy.visit(joinUrlFromEmail(sent));
+ completeSignup();
+
+ cy.location("pathname").should(
+ "match",
+ new RegExp(`/dashboard/${ORDERS_DASHBOARD_ID}(-|/|$)`),
+ );
+ });
+ });
+ });
+
+ describe("permissions", () => {
+ beforeEach(() => H.setupSMTP());
+
+ // The redirect only navigates; it is not an access grant. An invitee whose
+ // group cannot see the dashboard's collection lands on the route but hits the
+ // no-access screen.
+ it("does not grant access to the shared item", () => {
+ cy.request("POST", "/api/collection", {
+ name: "Restricted",
+ parent_id: null,
+ }).then(({ body: collection }) => {
+ // revoke the All Users group's access to the new collection
+ cy.request("GET", "/api/collection/graph").then(({ body: graph }) => {
+ cy.request("PUT", "/api/collection/graph", {
+ ...graph,
+ groups: {
+ ...graph.groups,
+ [ALL_USERS_GROUP]: {
+ ...graph.groups[ALL_USERS_GROUP],
+ [collection.id]: "none",
+ },
+ },
+ });
+ });
+
+ cy.request("POST", "/api/dashboard", {
+ name: "Secret dashboard",
+ collection_id: collection.id,
+ }).then(({ body: dashboard }) => {
+ H.visitDashboard(dashboard.id);
+ inviteFromShareMenu(inviteEmail());
+
+ H.getInbox().then(({ body: [sent] }) => {
+ cy.signOut();
+ cy.visit(joinUrlFromEmail(sent));
+ completeSignup();
+
+ cy.findByText(/don.t have permission to see that/i).should("exist");
+ });
+ });
+ });
+ });
+ });
+});
diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.ts
index 5d40f50be92..7a4e92d55c2 100644
--- a/frontend/src/metabase-types/analytics/event.ts
+++ b/frontend/src/metabase-types/analytics/event.ts
@@ -46,3 +46,17 @@ export type CustomVizEvent =
| CustomVizPluginToggledEvent
| CustomVizPluginRefreshedEvent
| CustomVizSelectedEvent;
+
+export type UserInvitedEvent = ValidateEvent<{
+ event: "user_invited";
+ triggered_from: "admin" | "setup" | "dashboard" | "question";
+ target_id: number | null;
+ result: "success" | "failure";
+ event_detail: "new_user" | "existing_user" | null;
+}>;
+
+export type InviteToViewOpenedEvent = ValidateEvent<{
+ event: "invite_to_view_opened";
+ triggered_from: "dashboard" | "question";
+ target_id: number | null;
+}>;
diff --git a/frontend/src/metabase-types/api/user.ts b/frontend/src/metabase-types/api/user.ts
index 0d5b2f1f079..e848906ca9d 100644
--- a/frontend/src/metabase-types/api/user.ts
+++ b/frontend/src/metabase-types/api/user.ts
@@ -125,6 +125,12 @@ export type UserLoginHistoryItem = {
export type UserLoginHistory = UserLoginHistoryItem[];
+export type InviteTarget = {
+ type: "dashboard" | "question";
+ id: number;
+ name: string;
+};
+
export type CreateUserRequest = {
email: string;
first_name?: string;
@@ -133,6 +139,7 @@ export type CreateUserRequest = {
login_attributes?: UserAttributeMap;
password?: string;
source?: "setup" | "admin";
+ invite_target?: InviteTarget;
};
export type UpdatePasswordRequest = {
diff --git a/frontend/src/metabase/admin/people/containers/NewUserModal.tsx b/frontend/src/metabase/admin/people/containers/NewUserModal.tsx
index 5ff7067b74f..86e8305f4ad 100644
--- a/frontend/src/metabase/admin/people/containers/NewUserModal.tsx
+++ b/frontend/src/metabase/admin/people/containers/NewUserModal.tsx
@@ -2,6 +2,8 @@ import { push } from "react-router-redux";
import { t } from "ttag";
import { useCreateUserMutation } from "metabase/api";
+import { isEmailAlreadyInUse } from "metabase/api/utils/errors";
+import { trackUserInvited } from "metabase/common/analytics";
import { PLUGIN_TENANTS } from "metabase/plugins";
import { useDispatch } from "metabase/redux";
import { Modal } from "metabase/ui";
@@ -30,19 +32,40 @@ export const NewUserModal = ({
const password = MetabaseSettings.isEmailConfigured()
? undefined
: generatePassword();
- const user = await createUser({
- ...vals,
- email: vals.email ?? "",
- first_name: vals.first_name ?? undefined,
- last_name: vals.last_name ?? undefined,
- login_attributes: vals.login_attributes || undefined,
- ...(password ? { password } : {}),
- }).unwrap();
-
- if (password) {
- dispatch(storeTemporaryPassword({ id: user.id, password }));
+ try {
+ const user = await createUser({
+ ...vals,
+ email: vals.email ?? "",
+ first_name: vals.first_name ?? undefined,
+ last_name: vals.last_name ?? undefined,
+ login_attributes: vals.login_attributes || undefined,
+ ...(password ? { password } : {}),
+ }).unwrap();
+
+ // External (tenant) creates send no invite email, so skip tracking.
+ if (!external) {
+ trackUserInvited({
+ triggeredFrom: "admin",
+ targetId: null,
+ result: "success",
+ eventDetail: "new_user",
+ });
+ }
+ if (password) {
+ dispatch(storeTemporaryPassword({ id: user.id, password }));
+ }
+ dispatch(push(Urls.newUserSuccess(user)));
+ } catch (error) {
+ if (!external) {
+ trackUserInvited({
+ triggeredFrom: "admin",
+ targetId: null,
+ result: "failure",
+ eventDetail: isEmailAlreadyInUse(error) ? "existing_user" : null,
+ });
+ }
+ throw error;
}
- dispatch(push(Urls.newUserSuccess(user)));
};
// Use plugin-provided title for external users, fallback to default
diff --git a/frontend/src/metabase/admin/people/forms/UserForm.tsx b/frontend/src/metabase/admin/people/forms/UserForm.tsx
index bb76d4f4b9e..58808986b8d 100644
--- a/frontend/src/metabase/admin/people/forms/UserForm.tsx
+++ b/frontend/src/metabase/admin/people/forms/UserForm.tsx
@@ -145,6 +145,8 @@ interface UserFormProps {
external?: boolean;
edit?: boolean;
userId?: UserId | null;
+ hideNameFields?: boolean;
+ hideAttributes?: boolean;
}
export const UserForm = ({
@@ -155,6 +157,8 @@ export const UserForm = ({
external = false,
edit = false,
userId,
+ hideNameFields = false,
+ hideAttributes = false,
}: UserFormProps) => {
return (
<FormProvider
@@ -165,22 +169,26 @@ export const UserForm = ({
>
{({ dirty }: { dirty: boolean }) => (
<Form disabled={!dirty}>
- <FormTextInput
- name="first_name"
- title={t`First name`}
- placeholder={t`Johnny`}
- label={t`First name`}
- mb="md"
- nullable
- />
- <FormTextInput
- name="last_name"
- title={t`Last name`}
- placeholder={t`Appleseed`}
- label={t`Last name`}
- mb="md"
- nullable
- />
+ {!hideNameFields && (
+ <>
+ <FormTextInput
+ name="first_name"
+ title={t`First name`}
+ placeholder={t`Johnny`}
+ label={t`First name`}
+ mb="md"
+ nullable
+ />
+ <FormTextInput
+ name="last_name"
+ title={t`Last name`}
+ placeholder={t`Appleseed`}
+ label={t`Last name`}
+ mb="md"
+ nullable
+ />
+ </>
+ )}
<FormTextInput
name="email"
type="email"
@@ -203,7 +211,11 @@ export const UserForm = ({
disabled={edit}
/>
)}
- <PLUGIN_ADMIN_USER_FORM_FIELDS.FormLoginAttributes userId={userId} />
+ {!hideAttributes && (
+ <PLUGIN_ADMIN_USER_FORM_FIELDS.FormLoginAttributes
+ userId={userId}
+ />
+ )}
<FormFooter>
<FormErrorMessage inline />
<Button type="button" onClick={onCancel}>{t`Cancel`}</Button>
diff --git a/frontend/src/metabase/admin/people/forms/UserForm.unit.spec.tsx b/frontend/src/metabase/admin/people/forms/UserForm.unit.spec.tsx
index 2ddeebeab5d..479db442b9f 100644
--- a/frontend/src/metabase/admin/people/forms/UserForm.unit.spec.tsx
+++ b/frontend/src/metabase/admin/people/forms/UserForm.unit.spec.tsx
@@ -39,6 +39,8 @@ interface SetupOpts {
initialValues?: typeof USER;
external?: boolean;
tenants?: Tenant[];
+ hideNameFields?: boolean;
+ hideAttributes?: boolean;
}
const setup = ({
@@ -46,6 +48,8 @@ const setup = ({
initialValues = USER,
external = false,
tenants = [] as Tenant[],
+ hideNameFields = false,
+ hideAttributes = false,
}: SetupOpts = {}) => {
const onSubmit = jest.fn();
const onCancel = jest.fn();
@@ -75,6 +79,8 @@ const setup = ({
onCancel={onCancel}
initialValues={initialValues}
external={external}
+ hideNameFields={hideNameFields}
+ hideAttributes={hideAttributes}
/>,
{
storeInitialState: state,
@@ -387,4 +393,25 @@ describe("UserForm", () => {
});
});
});
+
+ describe("trimmed variant (invite flow)", () => {
+ it("hides the name fields when hideNameFields is set", async () => {
+ setup({ hideNameFields: true });
+
+ expect(await screen.findByLabelText(/Email/)).toBeInTheDocument();
+ expect(screen.queryByLabelText("First name")).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("Last name")).not.toBeInTheDocument();
+ });
+
+ it("hides the Attributes field when hideAttributes is set", async () => {
+ setup({
+ enterprisePlugins: ["sandboxes", "tenants"],
+ initialValues: { ...USER, login_attributes: { team: "engineering" } },
+ hideAttributes: true,
+ });
+
+ expect(await screen.findByLabelText(/Email/)).toBeInTheDocument();
+ expect(screen.queryByText("Attributes")).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/frontend/src/metabase/api/utils/errors.ts b/frontend/src/metabase/api/utils/errors.ts
index c5bd76f7c35..18709a20054 100644
--- a/frontend/src/metabase/api/utils/errors.ts
+++ b/frontend/src/metabase/api/utils/errors.ts
@@ -41,6 +41,19 @@ export const getErrorMessage = (
return fallback;
};
+type RequestError = {
+ status?: number;
+ data?: { error_code?: string; errors?: Record<string, unknown> };
+};
+
+const isRequestError = (error: unknown): error is RequestError =>
+ typeof error === "object" && error !== null;
+
+// The createUser endpoint rejects a duplicate email with a 400 carrying an
+// `error_code`. Prefer the stable code over the localized field message.
+export const isEmailAlreadyInUse = (error: unknown): boolean =>
+ isRequestError(error) && error.data?.error_code === "email-already-in-use";
+
function isEmpty(value: unknown): boolean {
return value == null || value === "";
}
diff --git a/frontend/src/metabase/api/utils/errors.unit.spec.ts b/frontend/src/metabase/api/utils/errors.unit.spec.ts
index 07fc31c4d31..feb79b79db6 100644
--- a/frontend/src/metabase/api/utils/errors.unit.spec.ts
+++ b/frontend/src/metabase/api/utils/errors.unit.spec.ts
@@ -1,4 +1,4 @@
-import { getErrorMessage } from "./errors";
+import { getErrorMessage, isEmailAlreadyInUse } from "./errors";
describe("getErrorMessage", () => {
it("should return a message from a string payload", () => {
@@ -53,3 +53,19 @@ describe("getErrorMessage", () => {
expect(result).toEqual("Something went wrong");
});
});
+
+describe("isEmailAlreadyInUse", () => {
+ it("flags only a body carrying the email-already-in-use error_code", () => {
+ expect(
+ isEmailAlreadyInUse({
+ status: 400,
+ data: { error_code: "email-already-in-use" },
+ }),
+ ).toBe(true);
+ expect(
+ isEmailAlreadyInUse({ status: 400, data: { error_code: "archived" } }),
+ ).toBe(false);
+ expect(isEmailAlreadyInUse({ status: 400, data: {} })).toBe(false);
+ expect(isEmailAlreadyInUse(undefined)).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/common/analytics/index.ts b/frontend/src/metabase/common/analytics/index.ts
index d381f444d7d..f2b6e2f6450 100644
--- a/frontend/src/metabase/common/analytics/index.ts
+++ b/frontend/src/metabase/common/analytics/index.ts
@@ -1 +1,2 @@
export { trackCustomHomepageDashboardEnabled } from "./homepage";
+export { trackInviteToViewOpened, trackUserInvited } from "./invite-events";
diff --git a/frontend/src/metabase/common/analytics/invite-events.ts b/frontend/src/metabase/common/analytics/invite-events.ts
new file mode 100644
index 00000000000..f06f13e7aa2
--- /dev/null
+++ b/frontend/src/metabase/common/analytics/invite-events.ts
@@ -0,0 +1,29 @@
+import { trackSimpleEvent } from "metabase/analytics";
+import type {
+ InviteToViewOpenedEvent,
+ UserInvitedEvent,
+} from "metabase-types/analytics";
+
+export const trackUserInvited = (params: {
+ triggeredFrom: UserInvitedEvent["triggered_from"];
+ targetId: UserInvitedEvent["target_id"];
+ result: UserInvitedEvent["result"];
+ eventDetail: UserInvitedEvent["event_detail"];
+}) =>
+ trackSimpleEvent({
+ event: "user_invited",
+ triggered_from: params.triggeredFrom,
+ target_id: params.targetId,
+ result: params.result,
+ event_detail: params.eventDetail,
+ });
+
+export const trackInviteToViewOpened = (params: {
+ triggeredFrom: InviteToViewOpenedEvent["triggered_from"];
+ targetId: InviteToViewOpenedEvent["target_id"];
+}) =>
+ trackSimpleEvent({
+ event: "invite_to_view_opened",
+ triggered_from: params.triggeredFrom,
+ target_id: params.targetId,
+ });
diff --git a/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.styled.tsx b/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.styled.tsx
deleted file mode 100644
index dc28bfaf885..00000000000
--- a/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.styled.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-// eslint-disable-next-line no-restricted-imports
-import styled from "@emotion/styled";
-
-import { CopyButton } from "metabase/common/components/CopyButton";
-
-export const PasswordCopyButton = styled(CopyButton)`
- cursor: pointer;
-
- &:hover {
- color: var(--mb-color-core-brand);
- }
-`;
diff --git a/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.tsx b/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.tsx
index 5a7e5f69516..0d56bb71d16 100644
--- a/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.tsx
+++ b/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.tsx
@@ -1,88 +1,54 @@
-import cx from "classnames";
-import { useState } from "react";
+import { useId } from "react";
import { t } from "ttag";
-import CS from "metabase/css/core/index.css";
-import { color } from "metabase/ui/utils/colors";
-
-import { PasswordCopyButton } from "./PasswordReveal.styled";
-
-const styles = {
- input: {
- fontSize: "1.2rem",
- letterSpacing: "2",
- color: color("text-primary"),
- outline: "none",
- },
-};
-
-const Label = () => (
- <div
- style={{ top: -12 }}
- className={cx(CS.absolute, CS.textCentered, CS.left, CS.right)}
- >
- <span
- className={cx(
- CS.px1,
- CS.bgWhite,
- CS.h6,
- CS.textBold,
- CS.textMedium,
- CS.textUppercase,
- )}
- >
- {t`Temporary Password`}
- </span>
- </div>
-);
+import {
+ ActionIcon,
+ CopyButton,
+ Flex,
+ Icon,
+ Input,
+ PasswordInput,
+ Tooltip,
+} from "metabase/ui";
interface PasswordRevealProps {
password: string;
}
export const PasswordReveal = ({ password }: PasswordRevealProps) => {
- const [visible, setVisible] = useState(false);
+ const inputId = useId();
return (
- <div
- style={{ borderWidth: 2 }}
- className={cx(
- CS.bordered,
- CS.rounded,
- CS.flex,
- CS.alignCenter,
- CS.p3,
- CS.relative,
- )}
+ <Input.Wrapper
+ label={t`Temporary password`}
+ labelProps={{ htmlFor: inputId }}
>
- <Label />
- {visible ? (
- <input
- style={styles.input}
- className={cx(CS.textLight, CS.textNormal, CS.mr3, CS.borderless)}
+ <Flex gap="md" align="center" wrap="nowrap">
+ <PasswordInput
+ id={inputId}
value={password}
- onClick={(e) => {
- const target = e.currentTarget;
- target.setSelectionRange(0, target.value.length);
- }}
readOnly
+ radius="lg"
+ size="lg"
+ flex={1}
/>
- ) : (
- // eslint-disable-next-line i18next/no-literal-string
- <span style={styles.input} className={CS.mr3}>
- ●●●●●●●●●●●●
- </span>
- )}
- <div className={cx(CS.mlAuto, CS.flex, CS.alignCenter)}>
- <a
- className={cx(CS.link, CS.textBold, CS.mr2)}
- onClick={() => setVisible(!visible)}
- >
- {visible ? t`Hide` : t`Show`}
- </a>
-
- <PasswordCopyButton value={password} />
- </div>
- </div>
+ <CopyButton value={password} timeout={2000}>
+ {({ copied, copy }) => (
+ <Tooltip label={copied ? t`Copied!` : t`Copy`}>
+ <ActionIcon
+ onClick={copy}
+ data-testid="copy-button"
+ aria-label={t`Copy password`}
+ variant="subtle"
+ color="icon-secondary"
+ size="lg"
+ >
+ <Icon name={copied ? "check" : "copy"} />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ </CopyButton>
+ </Flex>
+ </Input.Wrapper>
);
};
diff --git a/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.unit.spec.tsx b/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.unit.spec.tsx
index 0f5560825db..0d36762ea04 100644
--- a/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/PasswordReveal/PasswordReveal.unit.spec.tsx
@@ -1,19 +1,18 @@
-import { fireEvent, render, screen } from "__support__/ui";
+import { renderWithProviders, screen } from "__support__/ui";
import { PasswordReveal } from "metabase/common/components/PasswordReveal";
describe("password reveal", () => {
- it("should toggle the visibility state when hide / show are clicked", () => {
- render(<PasswordReveal password="password" />);
- expect(screen.queryByText("Hide")).not.toBeInTheDocument();
+ it("masks the temporary password", () => {
+ renderWithProviders(<PasswordReveal password="password" />);
- fireEvent.click(screen.getByText("Show"));
-
- expect(screen.getByText("Hide")).toBeInTheDocument();
- expect(screen.queryByText("Show")).not.toBeInTheDocument();
+ expect(screen.getByLabelText("Temporary password")).toHaveAttribute(
+ "type",
+ "password",
+ );
});
- it("should render a copy button", () => {
- render(<PasswordReveal password="password" />);
+ it("renders a copy button", () => {
+ renderWithProviders(<PasswordReveal password="password" />);
expect(screen.getByTestId("copy-button")).toBeInTheDocument();
});
});
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.tsx
index f8fe9cd03a2..9d55faca93c 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.tsx
@@ -1,15 +1,20 @@
+import { useDisclosure } from "@mantine/hooks";
+import { t } from "ttag";
+
import { isInstanceAnalyticsCollection } from "metabase/common/collections/utils";
import { useSetting } from "metabase/common/hooks";
import {
getIsDashCardsRunning,
getSelectedTabId,
} from "metabase/dashboard/selectors";
+import { InviteToViewModal } from "metabase/embedding/components/SharingMenu/InviteToViewModal";
import {
CopyLinkMenuItem,
CopyPublicLinkMenuItem,
} from "metabase/embedding/components/SharingMenu/MenuItems/CopyLinkMenuItem";
import { EmbedMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/EmbedMenuItem";
import { ExportPdfMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/ExportPdfMenuItem";
+import { InviteToViewMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/InviteToViewMenuItem";
import { PublicLinkMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/PublicLinkMenuItem";
import { SharingMenu } from "metabase/embedding/components/SharingMenu/SharingMenu";
import type { DashboardSharingModalType } from "metabase/embedding/components/SharingMenu/types";
@@ -23,7 +28,7 @@ import {
dashboard as getDashboardUrl,
publicDashboard as getPublicDashboardUrl,
} from "metabase/urls";
-import type { Dashboard } from "metabase-types/api";
+import type { Dashboard, InviteTarget } from "metabase-types/api";
import { DashboardPublicLinkPopover } from "../../../DashboardInfoSidebar/DashboardPublicLinkPopover/DashboardPublicLinkPopover";
@@ -62,15 +67,24 @@ function AdminDashboardSharingMenu({ dashboard }: { dashboard: Dashboard }) {
resource: dashboard,
resourceType: "dashboard",
});
+ const [isInviteOpen, { open: openInvite, close: closeInvite }] =
+ useDisclosure();
const isDashCardsRunning = useSelector(getIsDashCardsRunning);
const isPublicSharingEnabled = useSetting("enable-public-sharing");
+ const siteUrl = useSetting("site-url");
const isAnalytics =
dashboard.collection && isInstanceAnalyticsCollection(dashboard.collection);
const canShare = !isAnalytics;
+ // x-ray dashboards have string ids and can't be invite targets.
+ const inviteTarget: InviteTarget | undefined =
+ typeof dashboard.id === "number"
+ ? { type: "dashboard", id: dashboard.id, name: dashboard.name }
+ : undefined;
return (
<Flex>
<SharingMenu>
+ <InviteToViewMenuItem onClick={openInvite} />
<CopyDashboardLinkMenuItem dashboard={dashboard} />
{canShare && isPublicSharingEnabled && (
<PublicLinkMenuItem
@@ -93,6 +107,15 @@ function AdminDashboardSharingMenu({ dashboard }: { dashboard: Dashboard }) {
onClose={() => setModalType(null)}
/>
)}
+ {isInviteOpen && (
+ <InviteToViewModal
+ title={t`Invite someone to view this dashboard`}
+ shareUrl={`${siteUrl}${getDashboardUrl(dashboard)}`}
+ triggeredFrom="dashboard"
+ inviteTarget={inviteTarget}
+ onClose={closeInvite}
+ />
+ )}
</Flex>
);
}
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx
index 6b97cd30de4..9585a41bacf 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/DashboardSharingMenu/DashboardSharingMenu.unit.spec.tsx
@@ -1,7 +1,12 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { screen, waitFor } from "__support__/ui";
-import { createMockDashboardTab } from "metabase-types/api/mocks";
+import type { Dashboard } from "metabase-types/api";
+import {
+ createMockDashboardTab,
+ createMockUser,
+} from "metabase-types/api/mocks";
import { openMenu, setupDashboardSharingMenu } from "./tests/setup";
@@ -294,4 +299,79 @@ describe("DashboardSharingMenu", () => {
});
});
});
+
+ describe("invite to view", () => {
+ const inviteAndGetRequestBody = async (dashboard: Partial<Dashboard>) => {
+ fetchMock.get("path:/api/permissions/group", []);
+ fetchMock.post("path:/api/user", createMockUser({ id: 99 }));
+ setupDashboardSharingMenu({
+ isAdmin: true,
+ isEmailSetup: true,
+ dashboard,
+ });
+ await openMenu();
+ await userEvent.click(screen.getByText("Invite someone to view this"));
+ await userEvent.type(
+ await screen.findByLabelText(/Email/),
+ );
+ await userEvent.click(
+ screen.getByRole("button", { name: "Send invitation" }),
+ );
+ await waitFor(() =>
+ expect(
+ fetchMock.callHistory.calls("path:/api/user", { method: "POST" }),
+ ).toHaveLength(1),
+ );
+ const call = fetchMock.callHistory.calls("path:/api/user", {
+ method: "POST",
+ })[0];
+ return JSON.parse(
+ await (call.options?.body as unknown as Promise<string>),
+ );
+ };
+
+ it("shows the invite item for admins", async () => {
+ setupDashboardSharingMenu({ isAdmin: true });
+ await openMenu();
+ expect(
+ screen.getByText("Invite someone to view this"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not show the invite item for non-admins", async () => {
+ setupDashboardSharingMenu({ isAdmin: false });
+ await openMenu();
+ expect(
+ screen.queryByText("Invite someone to view this"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("opens the invite modal for the dashboard", async () => {
+ fetchMock.get("path:/api/permissions/group", []);
+ setupDashboardSharingMenu({ isAdmin: true });
+ await openMenu();
+ await userEvent.click(screen.getByText("Invite someone to view this"));
+ expect(
+ await screen.findByText("Invite someone to view this dashboard"),
+ ).toBeInTheDocument();
+ });
+
+ it("sends the dashboard as the invite_target", async () => {
+ const body = await inviteAndGetRequestBody({ id: 42, name: "Q3 KPIs" });
+ expect(body.invite_target).toEqual({
+ type: "dashboard",
+ id: 42,
+ name: "Q3 KPIs",
+ });
+ });
+
+ it("omits the invite_target for an x-ray dashboard (string id)", async () => {
+ const body = await inviteAndGetRequestBody({
+ id: "10-12345",
+ name: "An x-ray",
+ });
+ expect(body.invite_target).toBeUndefined();
+ });
+ });
});
diff --git a/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.tsx b/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.tsx
new file mode 100644
index 00000000000..4b822565798
--- /dev/null
+++ b/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.tsx
@@ -0,0 +1,184 @@
+import { type ReactNode, useEffect, useState } from "react";
+import { Link } from "react-router";
+import { jt, t } from "ttag";
+
+import { UserForm } from "metabase/admin/people/forms/UserForm";
+import { useCreateUserMutation } from "metabase/api";
+import { isEmailAlreadyInUse } from "metabase/api/utils/errors";
+import {
+ trackInviteToViewOpened,
+ trackUserInvited,
+} from "metabase/common/analytics";
+import { CopyTextInput } from "metabase/common/components/CopyTextInput";
+import { PasswordReveal } from "metabase/common/components/PasswordReveal";
+import { useSetting, useToast } from "metabase/common/hooks";
+import { useSelector } from "metabase/redux";
+import { getSetting, isSsoEnabled } from "metabase/selectors/settings";
+import { Button, Group, Icon, Modal, Stack, Text } from "metabase/ui";
+import { generatePassword } from "metabase/utils/password";
+import type { InviteTarget, User } from "metabase-types/api";
+
+interface InviteToViewModalProps {
+ title: string;
+ shareUrl: string;
+ triggeredFrom: "dashboard" | "question";
+ inviteTarget?: InviteTarget;
+ onClose: () => void;
+}
+
+export const InviteToViewModal = ({
+ title,
+ shareUrl,
+ triggeredFrom,
+ inviteTarget,
+ onClose,
+}: InviteToViewModalProps) => {
+ const [createUser] = useCreateUserMutation();
+ const [sendToast] = useToast();
+
+ const isEmailConfigured = useSetting("email-configured?");
+ const isPasswordLoginEnabled = useSelector((state) =>
+ getSetting(state, "enable-password-login"),
+ );
+ const ssoEnabled = useSelector(isSsoEnabled);
+
+ const [credentials, setCredentials] = useState<{
+ email: string;
+ tmpPassword: string;
+ } | null>(null);
+
+ const targetId = inviteTarget?.id ?? null;
+
+ useEffect(() => {
+ trackInviteToViewOpened({ triggeredFrom, targetId });
+ }, [triggeredFrom, targetId]);
+
+ const createInvitedUser = async (
+ values: Partial<User>,
+ password?: string,
+ ) => {
+ try {
+ const user = await createUser({
+ ...values,
+ email: values.email ?? "",
+ first_name: values.first_name ?? undefined,
+ last_name: values.last_name ?? undefined,
+ login_attributes: values.login_attributes || undefined,
+ ...(password ? { password } : {}),
+ ...(inviteTarget ? { invite_target: inviteTarget } : {}),
+ }).unwrap();
+ trackUserInvited({
+ triggeredFrom,
+ targetId,
+ result: "success",
+ eventDetail: "new_user",
+ });
+ return user;
+ } catch (error) {
+ trackUserInvited({
+ triggeredFrom,
+ targetId,
+ result: "failure",
+ eventDetail: isEmailAlreadyInUse(error) ? "existing_user" : null,
+ });
+ throw error;
+ }
+ };
+
+ const inviteByEmail = async (values: Partial<User>) => {
+ await createInvitedUser(values);
+ sendToast({ icon: "check", message: t`Invitation sent` });
+ onClose();
+ };
+
+ const inviteWithTemporaryPassword = async (values: Partial<User>) => {
+ const tmpPassword = generatePassword();
+ const user = await createInvitedUser(values, tmpPassword);
+ setCredentials({ email: user.email, tmpPassword });
+ };
+
+ // Password login can only be off when SSO is configured, so this already implies SSO.
+ const needsEmailSetup = !isEmailConfigured && !isPasswordLoginEnabled;
+
+ let body: ReactNode;
+ if (needsEmailSetup) {
+ body = <EmailSetupPrompt shareUrl={shareUrl} onClose={onClose} />;
+ } else if (credentials) {
+ body = (
+ <TemporaryPasswordSuccess
+ email={credentials.email}
+ password={credentials.tmpPassword}
+ shareUrl={shareUrl}
+ onClose={onClose}
+ />
+ );
+ } else {
+ body = (
+ <UserForm
+ initialValues={{}}
+ submitText={t`Send invitation`}
+ onCancel={onClose}
+ onSubmit={
+ isEmailConfigured ? inviteByEmail : inviteWithTemporaryPassword
+ }
+ hideAttributes
+ hideNameFields={ssoEnabled}
+ />
+ );
+ }
+
+ return (
+ <Modal opened title={title} padding="xl" onClose={onClose}>
+ {body}
+ </Modal>
+ );
+};
+
+const EmailSetupPrompt = ({
+ shareUrl,
+ onClose,
+}: {
+ shareUrl: string;
+ onClose: () => void;
+}) => (
+ <Stack gap="lg">
+ <Text>{t`To invite people by email, set up email first. Or share this link, they'll land on it after signing in:`}</Text>
+ <CopyTextInput label={t`Link to share`} value={shareUrl} />
+ <Group justify="flex-end">
+ <Button onClick={onClose}>{t`Cancel`}</Button>
+ <Button
+ component={Link}
+ to="/admin/settings/email"
+ variant="filled"
+ leftSection={<Icon name="mail" />}
+ >
+ {t`Set up email`}
+ </Button>
+ </Group>
+ </Stack>
+);
+
+const TemporaryPasswordSuccess = ({
+ email,
+ password,
+ shareUrl,
+ onClose,
+}: {
+ email: string;
+ password: string;
+ shareUrl: string;
+ onClose: () => void;
+}) => (
+ <Stack gap="lg">
+ <Text>
+ {jt`We couldn't send an email invitation. Share this temporary password with ${(
+ <strong key="email">{email}</strong>
+ )} so they can sign in.`}
+ </Text>
+ <PasswordReveal password={password} />
+ <CopyTextInput label={t`Link to share`} value={shareUrl} />
+ <Group justify="flex-end">
+ <Button variant="filled" onClick={onClose}>{t`Done`}</Button>
+ </Group>
+ </Stack>
+);
diff --git a/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.unit.spec.tsx b/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.unit.spec.tsx
new file mode 100644
index 00000000000..372b388e5bc
--- /dev/null
+++ b/frontend/src/metabase/embedding/components/SharingMenu/InviteToViewModal.unit.spec.tsx
@@ -0,0 +1,244 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import type { InviteTarget } from "metabase-types/api";
+import { createMockGroup, createMockUser } from "metabase-types/api/mocks";
+
+import { InviteToViewModal } from "./InviteToViewModal";
+
+// metabase/common/analytics is auto-mocked globally (frontend/test/__support__/mocks.js),
+// so the trackers are jest.fns we can assert on.
+const { trackUserInvited, trackInviteToViewOpened } = jest.requireMock(
+ "metabase/common/analytics",
+);
+
+const GROUPS = [
+ createMockGroup({ id: 1, magic_group_type: "all-internal-users" }),
+ createMockGroup({ id: 2, name: "Administrators", magic_group_type: "admin" }),
+ createMockGroup({ id: 3, name: "foo", magic_group_type: null }),
+];
+
+const TITLE = "Invite someone to view this dashboard";
+
+const SHARE_URL = "http://localhost/dashboard/1";
+
+const CREATED_USER = createMockUser({ id: 99, email: "[email protected]" });
+
+const INVITE_TARGET: InviteTarget = {
+ type: "dashboard",
+ id: 1,
+ name: "My dashboard",
+};
+
+interface SetupOpts {
+ title?: string;
+ emailConfigured?: boolean;
+ ssoEnabled?: boolean;
+ passwordLoginEnabled?: boolean;
+ createError?: boolean;
+}
+
+const setup = ({
+ title = TITLE,
+ emailConfigured = true,
+ ssoEnabled = false,
+ passwordLoginEnabled = true,
+ createError = false,
+}: SetupOpts = {}) => {
+ const onClose = jest.fn();
+
+ fetchMock.get("path:/api/permissions/group", GROUPS);
+ fetchMock.post(
+ "path:/api/user",
+ createError
+ ? {
+ status: 400,
+ body: {
+ error_code: "email-already-in-use",
+ errors: { email: "Email address already in use." },
+ },
+ }
+ : CREATED_USER,
+ );
+
+ const state = createMockState({
+ settings: mockSettings({
+ "email-configured?": emailConfigured,
+ "enable-password-login": passwordLoginEnabled,
+ "saml-enabled": ssoEnabled,
+ }),
+ });
+
+ const { store } = renderWithProviders(
+ <InviteToViewModal
+ title={title}
+ shareUrl={SHARE_URL}
+ triggeredFrom="dashboard"
+ inviteTarget={INVITE_TARGET}
+ onClose={onClose}
+ />,
+ { storeInitialState: state },
+ );
+
+ return { onClose, store };
+};
+
+const submitInvite = async (email: string) => {
+ await userEvent.type(await screen.findByLabelText(/Email/), email);
+ await userEvent.click(
+ screen.getByRole("button", { name: "Send invitation" }),
+ );
+};
+
+describe("InviteToViewModal", () => {
+ beforeEach(() => {
+ trackUserInvited.mockClear();
+ trackInviteToViewOpened.mockClear();
+ });
+
+ it("renders the provided title", async () => {
+ setup({ title: "Invite someone to view this question" });
+
+ expect(
+ await screen.findByText("Invite someone to view this question"),
+ ).toBeInTheDocument();
+ });
+
+ it("hides the name fields whenever SSO is enabled, including mixed mode", async () => {
+ setup({ ssoEnabled: true, passwordLoginEnabled: true });
+
+ expect(await screen.findByLabelText(/Email/)).toBeInTheDocument();
+ expect(screen.queryByLabelText("First name")).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("Last name")).not.toBeInTheDocument();
+ });
+
+ it("creates the user, shows a confirmation toast, and closes when email is configured", async () => {
+ const { onClose, store } = setup({ emailConfigured: true });
+
+ await submitInvite("[email protected]");
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(store.getState().undo).toEqual([
+ expect.objectContaining({ message: "Invitation sent" }),
+ ]);
+ });
+
+ it("shows a temporary password instead of a toast when email is not configured", async () => {
+ const { onClose } = setup({
+ emailConfigured: false,
+ passwordLoginEnabled: true,
+ });
+
+ await submitInvite("[email protected]");
+
+ expect(await screen.findByText("Temporary password")).toBeInTheDocument();
+ expect(screen.getByDisplayValue(SHARE_URL)).toBeInTheDocument();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it("still shows a temporary password (not the email-setup prompt) in mixed SSO + password mode", async () => {
+ setup({
+ emailConfigured: false,
+ ssoEnabled: true,
+ passwordLoginEnabled: true,
+ });
+
+ await submitInvite("[email protected]");
+
+ expect(await screen.findByText("Temporary password")).toBeInTheDocument();
+ expect(screen.queryByText("Set up email")).not.toBeInTheDocument();
+ });
+
+ it("prompts to set up email on SSO-only instances without email configured", async () => {
+ setup({
+ emailConfigured: false,
+ ssoEnabled: true,
+ passwordLoginEnabled: false,
+ });
+
+ expect(await screen.findByText("Set up email")).toBeInTheDocument();
+ expect(screen.getByDisplayValue(SHARE_URL)).toBeInTheDocument();
+ expect(screen.queryByLabelText(/Email/)).not.toBeInTheDocument();
+ });
+
+ it("surfaces an inline error and stays open when the email is already in use", async () => {
+ const { onClose } = setup({ createError: true });
+
+ await submitInvite("[email protected]");
+
+ expect(
+ await screen.findByText("Email address already in use."),
+ ).toBeInTheDocument();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it("sends the invite_target entity in the create-user request", async () => {
+ const { onClose } = setup({ emailConfigured: true });
+
+ await submitInvite("[email protected]");
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+ const call = fetchMock.callHistory.calls("path:/api/user", {
+ method: "POST",
+ })[0];
+ const body = JSON.parse(
+ await (call.options?.body as unknown as Promise<string>),
+ );
+ expect(body.invite_target).toEqual(INVITE_TARGET);
+ });
+
+ it("tracks invite_to_view_opened when the modal opens", () => {
+ setup();
+
+ expect(trackInviteToViewOpened).toHaveBeenCalledWith({
+ triggeredFrom: "dashboard",
+ targetId: 1,
+ });
+ expect(trackInviteToViewOpened).toHaveBeenCalledTimes(1);
+ });
+
+ it("tracks user_invited success/new_user on a successful invite", async () => {
+ const { onClose } = setup({ emailConfigured: true });
+
+ await submitInvite("[email protected]");
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+ expect(trackUserInvited).toHaveBeenCalledWith({
+ triggeredFrom: "dashboard",
+ targetId: 1,
+ result: "success",
+ eventDetail: "new_user",
+ });
+ expect(trackUserInvited).toHaveBeenCalledTimes(1);
+ });
+
+ it("tracks user_invited failure/existing_user when the email is already in use", async () => {
+ setup({ createError: true });
+
+ await submitInvite("[email protected]");
+ await screen.findByText("Email address already in use.");
+
+ expect(trackUserInvited).toHaveBeenCalledWith({
+ triggeredFrom: "dashboard",
+ targetId: 1,
+ result: "failure",
+ eventDetail: "existing_user",
+ });
+ expect(trackUserInvited).toHaveBeenCalledTimes(1);
+ });
+
+ it("never sends the invitee email to analytics", async () => {
+ const { onClose } = setup({ emailConfigured: true });
+
+ await submitInvite("[email protected]");
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+ expect(JSON.stringify(trackUserInvited.mock.calls)).not.toContain(
+ );
+ });
+});
diff --git a/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/InviteToViewMenuItem.tsx b/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/InviteToViewMenuItem.tsx
new file mode 100644
index 00000000000..3803d1e455d
--- /dev/null
+++ b/frontend/src/metabase/embedding/components/SharingMenu/MenuItems/InviteToViewMenuItem.tsx
@@ -0,0 +1,14 @@
+import { t } from "ttag";
+
+import { Icon, Menu } from "metabase/ui";
+
+export function InviteToViewMenuItem({ onClick }: { onClick: () => void }) {
+ return (
+ <Menu.Item
+ leftSection={<Icon name="person" aria-hidden />}
+ onClick={onClick}
+ >
+ {t`Invite someone to view this`}
+ </Menu.Item>
+ );
+}
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.tsx
index e97e5fdfc67..ac3340ee517 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.tsx
@@ -1,8 +1,10 @@
+import { useDisclosure } from "@mantine/hooks";
import { useMemo } from "react";
import { t } from "ttag";
import { isInstanceAnalyticsCollection } from "metabase/common/collections/utils";
import { useSetting } from "metabase/common/hooks";
+import { InviteToViewModal } from "metabase/embedding/components/SharingMenu/InviteToViewModal";
import { LinkCopiedTooltipLabel } from "metabase/embedding/components/SharingMenu/LinkCopiedTooltipLabel";
import {
COPY_TIMEOUT_MS,
@@ -10,6 +12,7 @@ import {
CopyPublicLinkMenuItem,
} from "metabase/embedding/components/SharingMenu/MenuItems/CopyLinkMenuItem";
import { EmbedMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/EmbedMenuItem";
+import { InviteToViewMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/InviteToViewMenuItem";
import { PublicLinkMenuItem } from "metabase/embedding/components/SharingMenu/MenuItems/PublicLinkMenuItem";
import {
SharingButton,
@@ -87,11 +90,15 @@ function AdminQuestionSharingMenu({ question }: { question: Question }) {
resourceType: "question",
},
);
+ const [isInviteOpen, { open: openInvite, close: closeInvite }] =
+ useDisclosure();
const isPublicSharingEnabled = useSetting("enable-public-sharing");
+ const shareUrl = useQuestionAppUrl(question);
return (
<Flex>
<SharingMenu>
+ <InviteToViewMenuItem onClick={openInvite} />
<CopyQuestionLinkMenuItem question={question} />
{isPublicSharingEnabled && (
<PublicLinkMenuItem
@@ -111,6 +118,19 @@ function AdminQuestionSharingMenu({ question }: { question: Question }) {
onClose={() => setModalType(null)}
/>
)}
+ {isInviteOpen && (
+ <InviteToViewModal
+ title={t`Invite someone to view this question`}
+ shareUrl={shareUrl}
+ triggeredFrom="question"
+ inviteTarget={{
+ type: "question",
+ id: question.id(),
+ name: question.card().name,
+ }}
+ onClose={closeInvite}
+ />
+ )}
</Flex>
);
}
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx
index e831d940a6d..850bcc6b581 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/ViewTitleHeaderRightSide/QuestionSharingMenu/QuestionSharingMenu.unit.spec.tsx
@@ -1,4 +1,5 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { screen, waitFor } from "__support__/ui";
@@ -212,4 +213,36 @@ describe("QuestionSharingMenu", () => {
});
});
});
+
+ describe("invite to view", () => {
+ it("shows the invite item for admins", async () => {
+ await setupQuestionSharingMenu({ isAdmin: true });
+ await openMenu();
+ expect(
+ screen.getByText("Invite someone to view this"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not show the invite item for non-admins", async () => {
+ await setupQuestionSharingMenu({
+ isAdmin: false,
+ isPublicSharingEnabled: true,
+ hasPublicLink: true,
+ });
+ await openMenu();
+ expect(
+ screen.queryByText("Invite someone to view this"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("opens the invite modal for the question", async () => {
+ fetchMock.get("path:/api/permissions/group", []);
+ await setupQuestionSharingMenu({ isAdmin: true });
+ await openMenu();
+ await userEvent.click(screen.getByText("Invite someone to view this"));
+ expect(
+ await screen.findByText("Invite someone to view this question"),
+ ).toBeInTheDocument();
+ });
+ });
});
diff --git a/frontend/src/metabase/setup/actions.ts b/frontend/src/metabase/setup/actions.ts
index 1c32a60096a..d14146e2c7b 100644
--- a/frontend/src/metabase/setup/actions.ts
+++ b/frontend/src/metabase/setup/actions.ts
@@ -3,7 +3,9 @@ import { t } from "ttag";
import { setupApi, userApi } from "metabase/api";
import { loadLocalization } from "metabase/api/localization";
+import { isEmailAlreadyInUse } from "metabase/api/utils/errors";
import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
+import { trackUserInvited } from "metabase/common/analytics";
import { createDatabase } from "metabase/redux/databases";
import {
initializeSettings,
@@ -176,8 +178,20 @@ export const submitUserInvite = createAsyncThunk(
source: "setup",
}),
).unwrap();
+ trackUserInvited({
+ triggeredFrom: "setup",
+ targetId: null,
+ result: "success",
+ eventDetail: "new_user",
+ });
dispatch(goToNextStep());
} catch (error) {
+ trackUserInvited({
+ triggeredFrom: "setup",
+ targetId: null,
+ result: "failure",
+ eventDetail: isEmailAlreadyInUse(error) ? "existing_user" : null,
+ });
return rejectWithValue(error);
}
},
diff --git a/frontend/src/metabase/setup/actions.unit.spec.ts b/frontend/src/metabase/setup/actions.unit.spec.ts
index cbc52ddf01b..c757d7be591 100644
--- a/frontend/src/metabase/setup/actions.unit.spec.ts
+++ b/frontend/src/metabase/setup/actions.unit.spec.ts
@@ -4,6 +4,7 @@ import type { InviteInfo, State } from "metabase/redux/store";
import { submitUserInvite } from "./actions";
+const { trackUserInvited } = jest.requireMock("metabase/common/analytics");
const mockCreateUser = jest.fn();
userApi.endpoints.createUser.initiate = mockCreateUser;
@@ -51,4 +52,21 @@ describe("submitUserInvite", () => {
source: "setup",
});
});
+
+ it("tracks user_invited from setup when the create succeeds", async () => {
+ (dispatch as unknown as jest.Mock).mockReturnValue({
+ unwrap: () => Promise.resolve(),
+ });
+
+ const thunk = submitUserInvite(mockInviteInfo);
+ await thunk(dispatch, getState, undefined);
+
+ expect(trackUserInvited).toHaveBeenCalledWith({
+ triggeredFrom: "setup",
+ targetId: null,
+ result: "success",
+ eventDetail: "new_user",
+ });
+ expect(trackUserInvited).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/frontend/test/__support__/mocks.js b/frontend/test/__support__/mocks.js
index 187e3fc1122..7135ef907cc 100644
--- a/frontend/test/__support__/mocks.js
+++ b/frontend/test/__support__/mocks.js
@@ -27,6 +27,7 @@ global.window.ResizeObserver = class ResizeObserver {
};
jest.mock("metabase/analytics");
+jest.mock("metabase/common/analytics");
jest.mock("@uiw/react-codemirror", () => {
const { forwardRef } = jest.requireActual("react");
diff --git a/src/metabase/channel/email/new_user_invite.hbs b/src/metabase/channel/email/new_user_invite.hbs
index 464cd8cdc78..30462757bb2 100644
--- a/src/metabase/channel/email/new_user_invite.hbs
+++ b/src/metabase/channel/email/new_user_invite.hbs
@@ -5,54 +5,87 @@
<img style="max-height: 46px; max-width: 100%;" src="{{context.application_logo_url}}" alt="{{context.application_name}} logo" />
</div>
<div>
- {{#if payload.event_info.object.is_from_setup}}
+ {{#if payload.custom.invite_target_name}}
<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;">
- {{#if invitor.first_name}}
- {{invitor.first_name}} could use your help setting up {{context.application_name}}
+ {{#if payload.custom.invite_target_is_dashboard}}
+ {{#if invitor.first_name}}
+ {{invitor.first_name}} wants to share a {{context.application_name}} dashboard with you
+ {{else}}
+ A {{context.application_name}} dashboard has been shared with you
+ {{/if}}
{{else}}
- You are invited to help setting up {{context.application_name}}
+ {{#if invitor.first_name}}
+ {{invitor.first_name}} wants to share a {{context.application_name}} question with you
+ {{else}}
+ A {{context.application_name}} question has been shared with you
+ {{/if}}
{{/if}}
</h2>
</div>
<div style="max-width: 504px; text-align: center; margin-left: auto; margin-right: auto;">
- <p style="margin-top: 24px; margin-bottom: 10px; line-height: 24px; color: #656F76; font-size: 15px;">
- {{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;">
- {{#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>
- <li>Host and port</li>
- <li>Username and password</li>
- </ul>
- </div>
- {{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;">
- {{#if invitor.first_name}}
- {{invitor.first_name}} wants you to join them on {{context.application_name}}
+ <div style="margin-top: 24px; margin-bottom: 24px;">
+ {{#if payload.custom.invite_target_is_dashboard}}
+ <svg width="20" height="20" viewBox="0 0 16 16" fill="#509EE3" xmlns="http://www.w3.org/2000/svg" style="vertical-align: middle;"><path d="M4.75 9a.75.75 0 0 0 0 1.5h6.5a.75.75 0 0 0 0-1.5h-6.5zM4 6.25a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.75 5.5a.75.75 0 0 0 0 1.5h3.5a.75.75 0 0 0 0-1.5h-3.5z" /><path fill-rule="evenodd" clip-rule="evenodd" d="M1.25 3c0-.966.784-1.75 1.75-1.75h10c.966 0 1.75.784 1.75 1.75v10A1.75 1.75 0 0 1 13 14.75H3A1.75 1.75 0 0 1 1.25 13V3zm1.5 10V3.5h10.5V13a.25.25 0 0 1-.25.25H3a.25.25 0 0 1-.25-.25z" /></svg>
{{else}}
- You are invited to join {{context.application_name}}
+ <svg width="20" height="20" viewBox="0 0 16 16" fill="#509EE3" xmlns="http://www.w3.org/2000/svg" style="vertical-align: middle;"><path d="M11.5 2.75a.75.75 0 0 1 .75-.75h1a.75.75 0 0 1 .75.75V14h-2.5V2.75zM6.75 8.25c0-.467 0-.701.1-.875a.75.75 0 0 1 .275-.275C7.299 7 7.533 7 8 7s.701 0 .875.1a.75.75 0 0 1 .275.275c.1.174.1.408.1.875V14h-2.5V8.25zM2.75 10a.75.75 0 0 0-.75.75V14h2.5v-3.25a.75.75 0 0 0-.75-.75h-1z" /></svg>
{{/if}}
- </h2>
- </div>
- <div style="max-width: 504px; text-align: center; margin-left: auto; margin-right: auto;">
- <p style="margin-top: 24px; margin-bottom: 24px; line-height: 24px; color: #656F76; font-size: 15px;">
+ <span style="vertical-align: middle; margin-left: 8px; font-size: 18px; font-weight: 600; color: #2F3C45;">{{payload.custom.invite_target_name}}</span>
+ </div>
+ <p style="margin-bottom: 32px; line-height: 24px; color: #656F76; font-size: 15px;">
{{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>
+ {{else}}
+ {{#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;">
+ {{#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;">
+ <p style="margin-top: 24px; margin-bottom: 10px; line-height: 24px; color: #656F76; font-size: 15px;">
+ {{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;">
+ {{#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>
+ <li>Host and port</li>
+ <li>Username and password</li>
+ </ul>
+ </div>
+ {{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;">
+ {{#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;">
+ <p style="margin-top: 24px; margin-bottom: 24px; line-height: 24px; color: #656F76; font-size: 15px;">
+ {{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>
+ {{/if}}
{{/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;"
+ style="font-size: 15px; padding-top: 16px; padding-bottom: 16px; padding-left: 32px; padding-right: 32px; 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;"
href="{{payload.custom.user_invited_join_url}}"
- >Join now</a>
+ >Join {{context.application_name}} now</a>
</div>
{{#if payload.event_info.object.is_from_setup}}
<div style="max-width: 504px; margin-left: auto; margin-right: auto; line-height: 24px; color: #656F76; text-align: center;">
diff --git a/src/metabase/events/schema.clj b/src/metabase/events/schema.clj
index f23ef37c40b..b7c3f65210b 100644
--- a/src/metabase/events/schema.clj
+++ b/src/metabase/events/schema.clj
@@ -103,6 +103,11 @@
[:is_from_setup {:optional true} :boolean]
[:first_name {:optional true} [:maybe :string]]
[:invite_method {:optional true} :string]
+ [:invite_target {:optional true}
+ [:map
+ [:type [:enum "dashboard" "question"]]
+ [:id ms/PositiveInt]
+ [:name ms/NonBlankString]]]
[:sso_source {:optional true} [:maybe [:or :keyword :string]]]]]
[:details {:optional true}
[:map {:closed true}
diff --git a/src/metabase/notification/payload/impl/system_event.clj b/src/metabase/notification/payload/impl/system_event.clj
index db777e3ccd8..9785736b2c2 100644
--- a/src/metabase/notification/payload/impl/system_event.clj
+++ b/src/metabase/notification/payload/impl/system_event.clj
@@ -22,7 +22,8 @@
(not (session/enable-password-login)))
email (t2/select-one-fn :email [:model/User :email] user-id)]
(if should-link-to-login-page
- (str (system/site-url) "/auth/login")
+ (cond-> (str (system/site-url) "/auth/login")
+ redirect (str "?redirect=" redirect))
;; 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)
"?"
@@ -36,11 +37,26 @@
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]
- (let [{user-id :id from-setup :is_from_setup} (:object event-info)]
+ (let [{user-id :id from-setup :is_from_setup invite-target :invite_target} (: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"))}
+ (let [dashboard? (= (:type invite-target) "dashboard")
+ redirect (or (when invite-target
+ (if dashboard?
+ (urls/dashboard-path (:id invite-target))
+ (urls/card-path (:id invite-target))))
+ (when from-setup "/admin/databases/create"))
+ subject (cond
+ (and invite-target dashboard?)
+ (trs "You''re invited to view the dashboard {0}" (:name invite-target))
+ invite-target
+ (trs "You''re invited to view the question {0}" (:name invite-target))
+ :else
+ (trs "You''re invited to join {0}''s {1}" (appearance/site-name) (messages/app-name-trs)))]
+ (cond-> {:user_invited_email_subject subject
+ :user_invited_join_url (join-url user-id redirect)}
+ invite-target (assoc :invite_target_name (:name invite-target)
+ :invite_target_is_dashboard dashboard?)))
:event/security-advisory-match
(let [{:keys [severity match_status]} (:object event-info)]
{:severity_label (case severity
diff --git a/src/metabase/users/models/user.clj b/src/metabase/users/models/user.clj
index 5cbc80f4c6b..75117353f3a 100644
--- a/src/metabase/users/models/user.clj
+++ b/src/metabase/users/models/user.clj
@@ -471,17 +471,22 @@
"Convenience function for inviting a new `User` and sending them a welcome email.
This function will create the user, which will trigger the built-in system event
notification to send an invite via email."
- [new-user :- users.schema/NewUser invitor :- Invitor setup? :- :boolean]
- ;; create the new user
- (u/prog1 (t2/insert-returning-instance! :model/User new-user)
- ;; TODO make sure the email being sent synchronously.
- (events/publish-event! :event/user-invited
- {:object
- (assoc <>
- :is_from_setup setup?
- :invite_method "email"
- :sso_source (:sso_source new-user))
- :details {:invitor (select-keys invitor [:email :first_name])}})))
+ ([new-user invitor setup?]
+ (create-and-invite-user! new-user invitor setup? nil))
+ ([new-user :- users.schema/NewUser
+ invitor :- Invitor
+ setup? :- :boolean
+ invite-target :- [:maybe users.schema/InviteTarget]]
+ ;; create the new user
+ (u/prog1 (t2/insert-returning-instance! :model/User new-user)
+ (events/publish-event! :event/user-invited
+ {:object
+ (cond-> (assoc <>
+ :is_from_setup setup?
+ :invite_method "email"
+ :sso_source (:sso_source new-user))
+ invite-target (assoc :invite_target invite-target))
+ :details {:invitor (select-keys invitor [:email :first_name])}}))))
;;; TODO -- this should probably be moved into [[metabase.sso.google]]
(mu/defn create-new-google-auth-user!
diff --git a/src/metabase/users/schema.clj b/src/metabase/users/schema.clj
index 64c35038c6c..e943cc7e8ea 100644
--- a/src/metabase/users/schema.clj
+++ b/src/metabase/users/schema.clj
@@ -39,3 +39,11 @@
[:is_group_manager
{:optional true, :description "Only relevant if `advanced-permissions` is enabled. If it is, you should always include this key."}
:boolean]])
+
+(def InviteTarget
+ "The dashboard or question an invite points at, as `{:type :id :name}`. Drives the post-signup
+ landing redirect and the scoped invite email. Not an access grant; collection permissions still apply."
+ [:map
+ [:type [:enum "dashboard" "question"]]
+ [:id ms/PositiveInt]
+ [:name ms/NonBlankString]])
diff --git a/src/metabase/users/util.clj b/src/metabase/users/util.clj
index 5c1f3a82a5f..50861180038 100644
--- a/src/metabase/users/util.clj
+++ b/src/metabase/users/util.clj
@@ -59,12 +59,14 @@
[{:keys [email
user-group-memberships
source
- tenant-id]
+ tenant-id
+ invite-target]
:as attributes} :- [:map
[:source {:optional true, :default :admin} [:enum :setup :admin]]]]
(api/check-superuser)
- (api/checkp (not (t2/exists? :model/User :%lower.email (u/lower-case-en email)))
- "email" (tru "Email address already in use."))
+ (api/check-400 (not (t2/exists? :model/User :%lower.email (u/lower-case-en email)))
+ {:errors {:email (tru "Email address already in use.")}
+ :error_code "email-already-in-use"})
(api/checkp (not (and tenant-id
(not (setting/get :use-tenants))))
"tenant_id"
@@ -81,7 +83,8 @@
:login-attributes :login_attributes
:tenant-id :tenant_id}))
@api/*current-user*
- (= source :setup))))]
+ (= source :setup)
+ invite-target)))]
(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)]))
diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.clj
index 6496c20eaf2..67763b4868c 100644
--- a/src/metabase/users_rest/api.clj
+++ b/src/metabase/users_rest/api.clj
@@ -420,12 +420,14 @@
[:user_group_memberships {:optional true} [:maybe [:sequential ::users.schema/user-group-membership]]]
[:login_attributes {:optional true} [:maybe users.schema/LoginAttributes]]
[:source {:optional true, :default :admin} [:maybe keyword?]]
- [:tenant_id {:optional true} [:maybe ms/PositiveInt]]]]
+ [:tenant_id {:optional true} [:maybe ms/PositiveInt]]
+ [:invite_target {:optional true} [:maybe users.schema/InviteTarget]]]]
(users/invite-user! (set/rename-keys body {:first_name :first-name
:last_name :last-name
:user_group_memberships :user-group-memberships
:login_attributes :login-attributes
- :tenant_id :tenant-id})))
+ :tenant_id :tenant-id
+ :invite_target :invite-target})))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Updating a User -- PUT /api/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 46b5c049d97..85779846334 100644
--- a/test/metabase/notification/payload/impl/system_event_test.clj
+++ b/test/metabase/notification/payload/impl/system_event_test.clj
@@ -9,6 +9,7 @@
[metabase.sso.settings :as sso.settings]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
+ [metabase.users.models.user :as user]
[toucan2.core :as t2]))
(use-fixtures
@@ -129,20 +130,20 @@
(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 Metabase now</a>"]
"Ngoc")
(testing "with sso enabled"
(mt/with-dynamic-fn-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 Metabase 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>"]
+ #"<a[^>]*href=\"https?://metabase\.com/auth/reset_password/.*#new\"[^>]*>Join Metabase now</a>"]
nil)))
(testing "subject is translated"
(mt/with-mock-i18n-bundles! {"es" {:messages {"You''re invited to join {0}''s {1}"
@@ -187,6 +188,72 @@
(= (:content-type %) "image/png"))
(rest (:message email)))))))))
+(deftest create-and-invite-user-redirect-test
+ (testing "create-and-invite-user! lands the invitee on the invite_target item after signup"
+ (mt/with-model-cleanup [:model/User]
+ (let [join-url-html (fn [invite-target]
+ (mt/with-temporary-setting-values [site-url "https://metabase.com"]
+ (-> (notification.tu/with-captured-channel-send!
+ (user/create-and-invite-user! {:first_name "Newbie" :email (mt/random-email)}
+ {:first_name "Admin" :email "[email protected]"}
+ false
+ invite-target))
+ :channel/email first :message first :content)))]
+ (testing "dashboard"
+ (is (re-find #"/auth/reset_password/.*redirect(&#x3D;|=)/dashboard/42.*#new"
+ (join-url-html {:type "dashboard" :id 42 :name "Q3 KPIs"}))))
+ (testing "question"
+ (is (re-find #"/auth/reset_password/.*redirect(&#x3D;|=)/question/7.*#new"
+ (join-url-html {:type "question" :id 7 :name "Signups"}))))))))
+
+(deftest create-and-invite-user-sso-redirect-test
+ (testing "with SSO enabled and password login disabled, the invite link points at /auth/login carrying the item redirect"
+ (mt/with-model-cleanup [:model/User]
+ (mt/with-dynamic-fn-redefs [sso.settings/sso-enabled? (constantly true)
+ session.settings/enable-password-login (constantly false)]
+ (let [join-url-html (fn [invite-target]
+ (mt/with-temporary-setting-values [site-url "https://metabase.com"]
+ (-> (notification.tu/with-captured-channel-send!
+ (user/create-and-invite-user! {:first_name "Newbie" :email (mt/random-email)}
+ {:first_name "Admin" :email "[email protected]"}
+ false
+ invite-target))
+ :channel/email first :message first :content)))]
+ (testing "dashboard"
+ (is (re-find #"/auth/login\?redirect(&#x3D;|=)/dashboard/42"
+ (join-url-html {:type "dashboard" :id 42 :name "Q3 KPIs"}))))
+ (testing "question"
+ (is (re-find #"/auth/login\?redirect(&#x3D;|=)/question/7"
+ (join-url-html {:type "question" :id 7 :name "Signups"})))))))))
+
+(deftest create-and-invite-user-email-content-test
+ (testing "the invite email is scoped to the dashboard/question when an invite_target is present"
+ (mt/with-model-cleanup [:model/User]
+ (let [invite-email (fn [invite-target]
+ (mt/with-temporary-setting-values [site-url "https://metabase.com"
+ site-name "SuperStar"]
+ (-> (notification.tu/with-captured-channel-send!
+ (user/create-and-invite-user! {:first_name "Newbie" :email (mt/random-email)}
+ {:first_name "Ngoc" :email "[email protected]"}
+ false
+ invite-target))
+ :channel/email first)))
+ body (fn [email] (-> email :message first :content))]
+ (testing "dashboard"
+ (let [email (invite-email {:type "dashboard" :id 42 :name "Q3 KPIs"})]
+ (is (= "You're invited to view the dashboard Q3 KPIs" (:subject email)))
+ (is (re-find #"Ngoc wants to share a Metabase dashboard with you" (body email)))
+ (is (re-find #"Q3 KPIs" (body email)))))
+ (testing "question"
+ (let [email (invite-email {:type "question" :id 7 :name "Signups"})]
+ (is (= "You're invited to view the question Signups" (:subject email)))
+ (is (re-find #"Ngoc wants to share a Metabase question with you" (body email)))
+ (is (re-find #"Signups" (body email)))))
+ (testing "no invite_target falls back to the generic invite"
+ (let [email (invite-email nil)]
+ (is (= "You're invited to join SuperStar's Metabase" (:subject email)))
+ (is (re-find #"Ngoc wants you to join them on Metabase" (body email)))))))))
+
(deftest notification-create-email-test
(mt/with-temporary-setting-values [site-url "https://metabase.com"]
(let [rasta (mt/fetch-user :rasta)
diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.clj
index 748c3146d09..d6b6337d733 100644
--- a/test/metabase/users_rest/api_test.clj
+++ b/test/metabase/users_rest/api_test.clj
@@ -828,6 +828,19 @@
(:user_group_memberships resp)))
(is (true? (:is_superuser resp)))))))))
+(deftest create-user-invite-target-validation-test
+ (testing "POST /api/user rejects a malformed invite_target"
+ (let [base {:first_name "Cam" :last_name "Era" :email (mt/random-email)}]
+ (testing "type outside the dashboard/question enum"
+ (mt/user-http-request :crowberto :post 400 "user"
+ (assoc base :invite_target {:type "collection" :id 1 :name "Q3"})))
+ (testing "non-positive id"
+ (mt/user-http-request :crowberto :post 400 "user"
+ (assoc base :invite_target {:type "dashboard" :id 0 :name "Q3"})))
+ (testing "blank name"
+ (mt/user-http-request :crowberto :post 400 "user"
+ (assoc base :invite_target {:type "dashboard" :id 1 :name ""}))))))
+
(deftest create-user-set-groups-test
(testing "POST /api/user"
(mt/with-premium-features #{}
@@ -931,7 +944,8 @@
(deftest create-user-mixed-case-email-2
(testing "POST /api/user/:id"
(testing "attempting to create a new user with an email with case mutations of an existing email should fail"
- (is (=? {:errors {:email "Email address already in use."}}
+ (is (=? {:errors {:email "Email address already in use."}
+ :error_code "email-already-in-use"}
(mt/user-http-request :crowberto :post 400 "user"
{:first_name "Something"
:last_name "Random"