Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ function SmsMultiFactorAssertionPhoneForm(props: SmsMultiFactorAssertionPhoneFor
onSubmit={async (e) => {
e.preventDefault();
e.stopPropagation();
await form.handleSubmit();
if (recaptchaVerifier) {
await form.handleSubmit();
}
}}
>
<form.AppForm>
Expand All @@ -127,7 +129,9 @@ function SmsMultiFactorAssertionPhoneForm(props: SmsMultiFactorAssertionPhoneFor
<div className="fui-recaptcha-container" ref={recaptchaContainerRef} />
</fieldset>
<fieldset>
<form.SubmitButton>{getTranslation(ui, "labels", "sendCode")}</form.SubmitButton>
<form.SubmitButton disabled={!recaptchaVerifier}>
{getTranslation(ui, "labels", "sendCode")}
</form.SubmitButton>
<form.ErrorMessage />
</fieldset>
</form.AppForm>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ function MultiFactorEnrollmentPhoneNumberForm(props: MultiFactorEnrollmentPhoneN
onSubmit={async (e) => {
e.preventDefault();
e.stopPropagation();
await form.handleSubmit();
if (recaptchaVerifier) {
await form.handleSubmit();
}
}}
>
<form.AppForm>
Expand All @@ -138,7 +140,9 @@ function MultiFactorEnrollmentPhoneNumberForm(props: MultiFactorEnrollmentPhoneN
<div className="fui-recaptcha-container" ref={recaptchaContainerRef} />
</fieldset>
<fieldset>
<form.SubmitButton>{getTranslation(ui, "labels", "sendCode")}</form.SubmitButton>
<form.SubmitButton disabled={!recaptchaVerifier}>
{getTranslation(ui, "labels", "sendCode")}
</form.SubmitButton>
<form.ErrorMessage />
</fieldset>
</form.AppForm>
Expand Down
38 changes: 38 additions & 0 deletions packages/react/src/auth/forms/phone-auth-form.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import { verifyPhoneNumber, confirmPhoneNumber } from "@firebase-oss/ui-core";
import { createFirebaseUIProvider, createMockUI } from "~/tests/utils";
import { registerLocale } from "@firebase-oss/ui-translations";
import { FirebaseUIProvider } from "~/context";
import { useRecaptchaVerifier } from "~/hooks";

vi.mock("~/components/country-selector", () => ({
CountrySelector: vi.fn().mockImplementation(({ value, onChange, ref }: any) => {
Expand Down Expand Up @@ -578,6 +579,18 @@ describe("<PhoneAuthForm />", () => {
const mockVerificationId = "test-verification-id";
vi.mocked(verifyPhoneNumber).mockResolvedValue(mockVerificationId);

// Create a mock verifier that simulates async render()
const mockVerifier = {
render: vi.fn().mockResolvedValue(123),
clear: vi.fn(),
verify: vi.fn().mockResolvedValue("verification-token"),
};

// Override the global mock to return our specific verifier
vi.mocked(useRecaptchaVerifier).mockReturnValue(
mockVerifier as unknown as import("firebase/auth").RecaptchaVerifier
);

const { container } = render(
<FirebaseUIProvider ui={mockUI}>
<PhoneAuthForm />
Expand All @@ -591,9 +604,34 @@ describe("<PhoneAuthForm />", () => {

await act(async () => {
fireEvent.change(phoneInput, { target: { value: "1234567890" } });
});

// Check if there are any validation errors before submitting
const errorBeforeSubmit = screen.queryByTestId("error-message");
if (errorBeforeSubmit) {
throw new Error(`Form has validation error before submit: ${errorBeforeSubmit.textContent}`);
}

await act(async () => {
fireEvent.click(sendCodeButton);
});

// Wait for the async form submission to complete
await waitFor(
() => {
expect(verifyPhoneNumber).toHaveBeenCalled();
},
{ timeout: 3000 }
);

// Verify that verifyPhoneNumber was called with the verifier
// Note: The phone number gets formatted, so we check for the formatted version
expect(verifyPhoneNumber).toHaveBeenCalledWith(
expect.anything(),
expect.stringMatching(/1.*234.*567.*890/), // Matches formatted phone number like "1(234)567-890" or "+11234567890"
mockVerifier
);

const verificationInput = await waitFor(() => {
return screen.getByRole("textbox", { name: /verificationCode/i });
});
Expand Down
9 changes: 7 additions & 2 deletions packages/react/src/auth/forms/phone-auth-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export function PhoneNumberForm(props: PhoneNumberFormProps) {
const recaptchaContainerRef = useRef<HTMLDivElement>(null);
const recaptchaVerifier = useRecaptchaVerifier(recaptchaContainerRef);
const countrySelector = useRef<CountrySelectorRef>(null);

const form = usePhoneNumberForm({
recaptchaVerifier: recaptchaVerifier!,
onSuccess: props.onSubmit,
Expand All @@ -115,7 +116,9 @@ export function PhoneNumberForm(props: PhoneNumberFormProps) {
onSubmit={async (e) => {
e.preventDefault();
e.stopPropagation();
await form.handleSubmit();
if (recaptchaVerifier) {
await form.handleSubmit();
}
}}
>
<form.AppForm>
Expand All @@ -135,7 +138,9 @@ export function PhoneNumberForm(props: PhoneNumberFormProps) {
</fieldset>
<Policies />
<fieldset>
<form.SubmitButton>{getTranslation(ui, "labels", "sendCode")}</form.SubmitButton>
<form.SubmitButton disabled={!recaptchaVerifier}>
{getTranslation(ui, "labels", "sendCode")}
</form.SubmitButton>
<form.ErrorMessage />
</fieldset>
</form.AppForm>
Expand Down
18 changes: 12 additions & 6 deletions packages/react/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

import { useContext, useMemo, useEffect, useRef } from "react";
import { useContext, useMemo, useEffect, useRef, useState } from "react";
import type { RecaptchaVerifier, User } from "firebase/auth";
import {
createEmailLinkAuthFormSchema,
Expand Down Expand Up @@ -200,7 +200,7 @@ export function useMultiFactorTotpAuthVerifyFormSchema() {
*/
export function useRecaptchaVerifier(ref: React.RefObject<HTMLDivElement | null>) {
const ui = useUI();
const verifierRef = useRef<RecaptchaVerifier | null>(null);
const [verifier, setVerifier] = useState<RecaptchaVerifier | null>(null);
const uiRef = useRef(ui);
const prevElementRef = useRef<HTMLDivElement | null>(null);

Expand All @@ -213,13 +213,19 @@ export function useRecaptchaVerifier(ref: React.RefObject<HTMLDivElement | null>
if (currentElement !== prevElementRef.current) {
prevElementRef.current = currentElement;
if (currentElement) {
verifierRef.current = getBehavior(currentUI, "recaptchaVerification")(currentUI, currentElement);
verifierRef.current.render();
try {
const newVerifier = getBehavior(currentUI, "recaptchaVerification")(currentUI, currentElement);
newVerifier.render();
setVerifier(newVerifier);
} catch (error) {
console.error("[useRecaptchaVerifier] Failed to create/render verifier:", error);
setVerifier(null);
}
} else {
verifierRef.current = null;
setVerifier(null);
}
}
}, [ref]);

return verifierRef.current;
return verifier;
}