The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Fix invitation not being sent from /setup flow (#62320)
Anderson4f24f5fe401e
diff --git a/e2e/test/scenarios/onboarding/setup/setup.cy.spec.ts b/e2e/test/scenarios/onboarding/setup/setup.cy.spec.tsindex 6266f593973..7a5b2f15d12 100644--- a/e2e/test/scenarios/onboarding/setup/setup.cy.spec.ts+++ b/e2e/test/scenarios/onboarding/setup/setup.cy.spec.ts@@ -9,7 +9,10 @@ const { admin } = USERS;const locales = ["en", "xx"];describe("scenarios > setup", () => {- beforeEach(() => H.restore("blank"));+ beforeEach(() => {+ H.restore("blank");+ H.resetSnowplow();+ });locales.forEach((locale) => {it(@@ -244,27 +247,8 @@ describe("scenarios > setup", () => {it("should not show 'Sample Database' if env var is explicitly set to false during setup", () => {H.mockSessionProperty("has-sample-database?", false);- cy.visit(- "/setup?first_name=John&last_name=Doe&[email protected]&site_name=Doe%20Unlimited",- );-- skipWelcomePage();- selectPreferredLanguageAndContinue();-- cy.findByTestId("setup-forms").within(() => {- const password = "12341234";- cy.findByLabelText("Create a password").should("be.empty").type(password);- cy.findByLabelText("Confirm your password").type(password);- cy.button("Next").click();-- cy.log("Just go through the usage questionaire");- cy.findByLabelText("What will you use Metabase for?").should(- "be.visible",- );- cy.button("Next").click();- });+ navigateToDatabaseStep();- cy.log("We are now on the database step");cy.findByLabelText("Add your data").within(() => {cy.button("Continue with sample data").should("not.exist");cy.button("I'll add my data later").click();@@ -274,6 +258,38 @@ describe("scenarios > setup", () => {cy.findByLabelText("I'll add my own data later").should("be.visible");});+ it("should create a new user upon inviting a teammate", () => {+ H.mockSessionProperty("email-configured?", true);++ navigateToDatabaseStep();+ cy.findByTestId("step-number").should("have.text", "4");++ cy.findByLabelText("Setup section").click();+ cy.findByLabelText("First name").type("TeammateFirstName");+ cy.findByLabelText("Last name").type("TeammateLastName");+ cy.findByLabelText("Email").type("[email protected]");+ cy.intercept("POST", "/api/user").as("createUser");++ cy.button("Send invitation").click();++ cy.wait("@createUser").then((interception) => {+ expect(interception.request.body).to.include({+ first_name: "TeammateFirstName",+ last_name: "TeammateLastName",+ email: "[email protected]",+ });+ });++ // Checks invite event was sent+ H.expectUnstructuredSnowplowEvent({+ event: "invite_sent",+ source: "setup",+ });++ // Checks we are now in the next step+ cy.findByTestId("step-number").should("have.text", "5");+ });+it("should allow a quick setup for the 'embedding' use case", () => {cy.visit("/setup?first_name=John&last_name=Doe&[email protected]&site_name=Doe%20Unlimited&use_case=embedding",@@ -730,3 +746,26 @@ const typeToken = (token: string) => {.invoke("attr", "type", "password").type(token, { log: false });};++// Navigate to the setup page, fills user data, password, skips usage questionnaire and proceeds to the database step+const navigateToDatabaseStep = () => {+ cy.visit(+ "/setup?first_name=John&last_name=Doe&[email protected]&site_name=Doe%20Unlimited",+ );++ skipWelcomePage();+ selectPreferredLanguageAndContinue();++ cy.findByTestId("setup-forms").within(() => {+ const password = "12341234";+ cy.findByLabelText("Create a password").should("be.empty").type(password);+ cy.findByLabelText("Confirm your password").type(password);+ cy.button("Next").click();++ cy.log("Just go through the usage questionnaire");+ cy.findByLabelText("What will you use Metabase for?").should("be.visible");+ cy.button("Next").click();+ });++ cy.log("We are now on the database step");+};diff --git a/frontend/src/metabase-types/api/user.ts b/frontend/src/metabase-types/api/user.tsindex 51e35119c32..bbd820f41ea 100644--- a/frontend/src/metabase-types/api/user.ts+++ b/frontend/src/metabase-types/api/user.ts@@ -105,6 +105,7 @@ export type CreateUserRequest = {user_group_memberships?: { id: number; is_group_manager: boolean }[];login_attributes?: UserAttributeMap;password?: string;+ source?: "setup" | "admin";};export type UpdatePasswordRequest = {diff --git a/frontend/src/metabase/setup/actions.ts b/frontend/src/metabase/setup/actions.tsindex cb4c364b2cd..3fb73923f7c 100644--- a/frontend/src/metabase/setup/actions.ts+++ b/frontend/src/metabase/setup/actions.ts@@ -7,6 +7,7 @@ import {updateSetting,updateSettings,} from "metabase/admin/settings/settings";+import { userApi } from "metabase/api";import { loadLocalization } from "metabase/lib/i18n";import { createAsyncThunk } from "metabase/lib/redux";import MetabaseSettings from "metabase/lib/settings";@@ -24,7 +25,6 @@ import {} from "./analytics";import {getAvailableLocales,- getInvite,getIsEmbeddingUseCase,getLocale,getNextStep,@@ -103,14 +103,12 @@ export const submitUser = createAsyncThunk<void, UserInfo, ThunkConfig>("metabase/setup/SUBMIT_USER_INFO",async (user: UserInfo, { dispatch, getState, rejectWithValue }) => {const token = getSetupToken(getState());- const invite = getInvite(getState());const locale = getLocale(getState());try {await SetupApi.create({token,user,- invite,prefs: {site_name: user.site_name,site_locale: locale?.code,@@ -175,7 +173,15 @@ export const skipDatabase = createAsyncThunk(export const SUBMIT_USER_INVITE = "metabase/setup/SUBMIT_USER_INVITE";export const submitUserInvite = createAsyncThunk(SUBMIT_USER_INVITE,- (_: InviteInfo, { dispatch }) => {+ 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());},);diff --git a/frontend/src/metabase/setup/actions.unit.spec.ts b/frontend/src/metabase/setup/actions.unit.spec.tsnew file mode 100644index 00000000000..d4ea613bd58--- /dev/null+++ b/frontend/src/metabase/setup/actions.unit.spec.ts@@ -0,0 +1,54 @@+import { userApi } from "metabase/api";+import type { DispatchFn } from "metabase/lib/redux";+import type { InviteInfo, State } from "metabase-types/store";++import { submitUserInvite } from "./actions";++const mockCreateUser = jest.fn();+userApi.endpoints.createUser.initiate = mockCreateUser;++const mockInviteInfo: InviteInfo = {+ email: "[email protected]",+ first_name: "John",+ last_name: "Smith",+};++describe("submitUserInvite", () => {+ let dispatch: DispatchFn;+ let getState: () => State;++ beforeEach(() => {+ dispatch = jest.fn();+ getState = jest.fn();+ });++ afterEach(() => {+ jest.clearAllMocks();+ });++ it("should dispatch createUser with correct parameters", async () => {+ const thunk = submitUserInvite(mockInviteInfo);+ await thunk(dispatch, getState, undefined);+ expect(mockCreateUser).toHaveBeenCalledWith(+ expect.objectContaining(mockInviteInfo),+ );+ });++ it("should handle invite params properly", async () => {+ const incompleteInviteInfo: InviteInfo = {+ email: "[email protected]",+ first_name: null,+ last_name: null,+ };+ const thunk = submitUserInvite(incompleteInviteInfo);++ await thunk(dispatch, getState, undefined);++ expect(mockCreateUser).toHaveBeenCalledWith({+ email: "[email protected]",+ first_name: undefined,+ last_name: undefined,+ source: "setup",+ });+ });+});diff --git a/src/metabase/setup/api.clj b/src/metabase/setup/api.cljindex b8d11833c4e..c8c65466aae 100644--- a/src/metabase/setup/api.clj+++ b/src/metabase/setup/api.clj@@ -5,10 +5,8 @@[metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.appearance.core :as appearance]- [metabase.channel.settings :as channel.settings][metabase.config.core :as config][metabase.events.core :as events]- [metabase.permissions.core :as perms][metabase.request.core :as request][metabase.session.models.session :as session][metabase.settings.core :as setting]@@ -17,7 +15,6 @@[metabase.users.models.user :as user][metabase.util :as u][metabase.util.i18n :as i18n :refer [tru]]- [metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -61,24 +58,6 @@;; return user ID, session ID, and the Session object itself{:session-key (:key session), :user-id user-id, :session session})))-(defn- setup-maybe-create-and-invite-user! [{:keys [email] :as user}, invitor]- (when email- (if-not (channel.settings/email-configured?)- (log/error "Could not invite user because email is not configured.")- (u/prog1 (user/insert-new-user! user)- (user/set-permissions-groups! <> [(perms/all-users-group) (perms/admin-group)])- (events/publish-event! :event/user-invited- {:object- (assoc <>- :is_from_setup true- :invite_method "email"- :sso_source (:sso_source <>))- :details {:invitor (select-keys invitor [:email :first_name])}})- (analytics/track-event! :snowplow/invite- {:event :invite-sent- :invited-user-id (u/the-id <>)- :source "setup"})))))-(defn- setup-set-settings! [{:keys [email site-name site-locale]}];; set a couple preferences(appearance/site-name! site-name)@@ -90,14 +69,10 @@(api.macros/defendpoint :post "/""Special endpoint for creating the first user during setup. This endpoint both creates the user AND logs them in and- returns a session ID. This endpoint can also be used to add a database, create and invite a second admin, and/or- set specific settings from the setup flow."+ returns a session ID. This endpoint can also be used to set specific settings from the setup flow."[_route-params_query-params{{first-name :first_name, last-name :last_name, :keys [email password]} :user- {invited-first-name :first_name- invited-last-name :last_name- invited-email :email} :invite{site-name :site_namesite-locale :site_locale} :prefs}:- [:map@@ -107,10 +82,6 @@[:password ms/ValidPassword][:first_name {:optional true} [:maybe ms/NonBlankString]][:last_name {:optional true} [:maybe ms/NonBlankString]]]]- [:invite {:optional true} [:map- [:first_name {:optional true} [:maybe ms/NonBlankString]]- [:last_name {:optional true} [:maybe ms/NonBlankString]]- [:email {:optional true} [:maybe ms/Email]]]][:prefs [:map[:site_name ms/NonBlankString][:site_locale {:optional true} [:maybe ms/ValidLocale]]]]]@@ -123,10 +94,6 @@:last-name last-name:password password:device-info (request/device-info request)})]- (setup-maybe-create-and-invite-user! {:email invited-email- :first_name invited-first-name- :last_name invited-last-name}- {:email email, :first_name first-name})(setup-set-settings! {:email email :site-name site-name :site-locale site-locale})user-info))(catch Throwable ediff --git a/src/metabase/users/api.clj b/src/metabase/users/api.cljindex 8f86ef1e07a..136cbb71f0b 100644--- a/src/metabase/users/api.clj+++ b/src/metabase/users/api.clj@@ -407,7 +407,7 @@(defn invite-user"Implementation for `POST /`, invites a user to Metabase."- [{:keys [email user_group_memberships] :as body}]+ [{:keys [email user_group_memberships source] :as body}](api/check-superuser)(api/checkp (not (t2/exists? :model/User :%lower.email (u/lower-case-en email)))"email" (tru "Email address already in use."))@@ -421,7 +421,7 @@(analytics/track-event! :snowplow/invite{:event :invite-sent:invited-user-id new-user-id- :source "admin"})+ :source (or source "admin")})(-> (fetch-user :id new-user-id)(t2/hydrate :user_group_memberships)))))@@ -434,7 +434,8 @@[:last_name {:optional true} [:maybe ms/NonBlankString]][:email ms/Email][:user_group_memberships {:optional true} [:maybe [:sequential ::user-group-membership]]]- [:login_attributes {:optional true} [:maybe user/LoginAttributes]]]]+ [:login_attributes {:optional true} [:maybe user/LoginAttributes]]+ [:source {:optional true, :default "admin"} [:maybe ms/NonBlankString]]]](invite-user body));;; +----------------------------------------------------------------------------------------------------------------+diff --git a/test/metabase/setup/api_test.clj b/test/metabase/setup/api_test.cljindex 812751b6f8f..779d8ba5aec 100644--- a/test/metabase/setup/api_test.clj+++ b/test/metabase/setup/api_test.clj@@ -5,13 +5,10 @@[clojure.string :as str][clojure.test :refer :all][medley.core :as m]- [metabase.analytics.snowplow-test :as snowplow-test][metabase.appearance.core :as appearance][metabase.config.core :as config][metabase.driver.settings :as driver.settings][metabase.events.core :as events]- [metabase.notification.test-util :as notification.tu]- [metabase.permissions.models.permissions-group :as perms-group][metabase.settings.core :as setting][metabase.settings.models.setting.cache-test :as setting.cache-test][metabase.setup.api :as api.setup]@@ -92,58 +89,6 @@:details {}}(mt/latest-audit-log-entry :user-joined user-id)))))))))))-(deftest invite-user-test- (testing "POST /api/setup"- (testing "Check that a second admin can be created during setup, and that an invite email is sent successfully and- a Snowplow analytics event is sent"- (mt/with-premium-features #{:audit-app}- (notification.tu/with-send-notification-sync- (mt/with-fake-inbox- (snowplow-test/with-fake-snowplow-collector- (let [email (mt/random-email)- first-name (mt/random-name)- last-name (mt/random-name)- invitor-first-name (mt/random-name)]- (with-setup! {:invite {:email email, :first_name first-name, :last_name last-name}- :user {:first_name invitor-first-name}- :prefs {:site_name "Metabase"}}- (let [invited-user (t2/select-one :model/User :email email)]- (is (= (:first_name invited-user) first-name))- (is (= (:last_name invited-user) last-name))- (is (:is_superuser invited-user))- (is (partial= [{:data {"event" "invite_sent",- "invited_user_id" (u/the-id invited-user)- "source" "setup"}}]- (filter #(= (get-in % [:data "event"]) "invite_sent")- (snowplow-test/pop-event-data-and-user-id!))))- (is (mt/received-email-body?- (re-pattern (str invitor-first-name " could use your help setting up Metabase.*"))))- (testing "The audit-log :user-invited event is recorded"- (let [logged-event (mt/latest-audit-log-entry :user-invited (u/the-id invited-user))]- (is (partial=- {:topic :user-invited- :user_id nil- :model "User"- :model_id (u/the-id (t2/select-one :model/User :email email))- :details {:invite_method "email"- :first_name first-name- :last_name last-name- :email email- :user_group_memberships [{:id (:id (perms-group/all-users))}- {:id (:id (perms-group/admin))}]}}- logged-event))))))))))))))--(deftest invite-user-test-2- (testing "POST /api/setup"- (testing "No second user is created if email is not set up"- (mt/with-temporary-setting-values [email-smtp-host nil]- (let [email (mt/random-email)- first-name (mt/random-name)- last-name (mt/random-name)]- (with-setup! {:invite {:email email, :first_name first-name, :last_name last-name}}- (is (not (t2/exists? :model/User :email email)))))))))-(deftest setup-settings-test(testing "POST /api/setup"(testing "check that we can set various Settings during setup"