feat: implement turnstile on signup (#13913)

* wip

* feat: turnstile + removal of trpcState

* fix: use react-turnstile

* fix: i18n hydration errors

* wip: server side validation for cf token

* fix: hide in e2e tests

* feat:throw on error of token

* fix: set correct form values onVerify

* fix: use getIp for remoteIp and use correct header for token input

* chore: update .env.example

* fix: Update .env.example

* Update apps/web/pages/signup.tsx

* chore: fix typo

* fix: typo

* feat: hide until error

* feat: appearance interaction only

* remove cloudflare from e2e

* fix: legacyBehavior

* fix links + wait for load

* fix: signup tests

* test: wait for load state

---------

Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-04-04 10:21:06 -03:00
1 parent 4a173c48b8
commit 89fe383c9f
11 files changed
+243 -102

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
import type { TurnstileProps } from "react-turnstile";
import Turnstile from "react-turnstile";
import { CLOUDFLARE_SITE_ID } from "@calcom/lib/constants";
type Props = Omit<TurnstileProps, "sitekey">;
export default function TurnstileWidget(props: Props) {
if (!CLOUDFLARE_SITE_ID || process.env.NEXT_PUBLIC_IS_E2E) return null;
return <Turnstile {...props} sitekey={CLOUDFLARE_SITE_ID} theme="auto" />;
}
+4 -2
View File
@@ -24,8 +24,10 @@ const querySchema = z.object({
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const prisma = await import("@calcom/prisma").then((mod) => mod.default);
const emailVerificationEnabled = await getFeatureFlag(prisma, "email-verification");
await ssrInit(ctx);
const signupDisabled = await getFeatureFlag(prisma, "disable-signup");
const ssr = await ssrInit(ctx);
const token = z.string().optional().parse(ctx.query.token);
const redirectUrlData = z
.string()
@@ -42,8 +44,8 @@ export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
redirectUrl,
isGoogleLoginEnabled: IS_GOOGLE_LOGIN_ENABLED,
isSAMLLoginEnabled,
trpcState: ssr.dehydrate(),
prepopulateFormValues: undefined,
emailVerificationEnabled,
};
// username + email prepopulated from query params
+1
View File
@@ -119,6 +119,7 @@
"react-schemaorg": "^2.0.0",
"react-select": "^5.7.0",
"react-timezone-select": "^1.4.0",
"react-turnstile": "^1.1.3",
"react-use-intercom": "1.5.1",
"remove-markdown": "^0.5.0",
"rrule": "^2.7.1",
+8
View File
@@ -4,8 +4,10 @@ import calcomSignupHandler from "@calcom/feature-auth/signup/handlers/calcomHand
import selfHostedSignupHandler from "@calcom/feature-auth/signup/handlers/selfHostedHandler";
import { type RequestWithUsernameStatus } from "@calcom/features/auth/signup/username";
import { IS_PREMIUM_USERNAME_ENABLED } from "@calcom/lib/constants";
import getIP from "@calcom/lib/getIP";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { checkCfTurnstileToken } from "@calcom/lib/server/checkCfTurnstileToken";
import { signupSchema } from "@calcom/prisma/zod-utils";
function ensureSignupIsEnabled(req: RequestWithUsernameStatus) {
@@ -36,8 +38,14 @@ function ensureReqIsPost(req: RequestWithUsernameStatus) {
}
export default async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
const remoteIp = getIP(req);
// Use a try catch instead of returning res every time
try {
await checkCfTurnstileToken({
token: req.headers["cf-access-token"] as string,
remoteIp,
});
ensureReqIsPost(req);
ensureSignupIsEnabled(req);
+32 -7
View File
@@ -3,6 +3,7 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { signIn } from "next-auth/react";
import { Trans } from "next-i18next";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Script from "next/script";
@@ -16,9 +17,15 @@ import getStripe from "@calcom/app-store/stripepayment/lib/client";
import { getPremiumPlanPriceValue } from "@calcom/app-store/stripepayment/lib/utils";
import { getOrgUsernameFromEmail } from "@calcom/features/auth/signup/utils/getOrgUsernameFromEmail";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { useFlagMap } from "@calcom/features/flags/context/provider";
import { classNames } from "@calcom/lib";
import { APP_NAME, URL_PROTOCOL_REGEX, IS_CALCOM, WEBAPP_URL, WEBSITE_URL } from "@calcom/lib/constants";
import {
APP_NAME,
URL_PROTOCOL_REGEX,
IS_CALCOM,
WEBAPP_URL,
WEBSITE_URL,
CLOUDFLARE_SITE_ID,
} from "@calcom/lib/constants";
import { fetchUsername } from "@calcom/lib/fetchUsername";
import { pushGTMEvent } from "@calcom/lib/gtm";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
@@ -45,8 +52,11 @@ import PageWrapper from "@components/PageWrapper";
const signupSchema = apiSignupSchema.extend({
apiError: z.string().optional(), // Needed to display API errors doesnt get passed to the API
cfToken: z.string().optional(),
});
const TurnstileCaptcha = dynamic(() => import("@components/auth/Turnstile"), { ssr: false });
type FormValues = z.infer<typeof signupSchema>;
export type SignupProps = inferSSRProps<typeof getServerSideProps>;
@@ -171,6 +181,7 @@ export default function Signup({
isSAMLLoginEnabled,
orgAutoAcceptEmail,
redirectUrl,
emailVerificationEnabled,
}: SignupProps) {
const [premiumUsername, setPremiumUsername] = useState(false);
const [usernameTaken, setUsernameTaken] = useState(false);
@@ -179,7 +190,6 @@ export default function Signup({
const telemetry = useTelemetry();
const { t, i18n } = useLocale();
const router = useRouter();
const flags = useFlagMap();
const formMethods = useForm<FormValues>({
resolver: zodResolver(signupSchema),
defaultValues: prepopulateFormValues satisfies FormValues,
@@ -225,7 +235,8 @@ export default function Signup({
const isOrgInviteByLink = orgSlug && !prepopulateFormValues?.username;
const signUp: SubmitHandler<FormValues> = async (data) => {
const signUp: SubmitHandler<FormValues> = async (_data) => {
const { cfToken, ...data } = _data;
await fetch("/api/auth/signup", {
body: JSON.stringify({
...data,
@@ -234,6 +245,7 @@ export default function Signup({
}),
headers: {
"Content-Type": "application/json",
"cf-access-token": cfToken ?? "invalid-token",
},
method: "POST",
})
@@ -243,7 +255,7 @@ export default function Signup({
pushGTMEvent("create_account", { email: data.email, user: data.username, lang: data.language });
telemetry.event(telemetryEventTypes.signup, collectPageParameters());
const verifyOrGettingStarted = flags["email-verification"] ? "auth/verify-email" : "getting-started";
const verifyOrGettingStarted = emailVerificationEnabled ? "auth/verify-email" : "getting-started";
const callBackUrl = `${
searchParams?.get("callbackUrl")
? isOrgInviteByLink
@@ -362,6 +374,16 @@ export default function Signup({
{...register("password")}
hintErrors={["caplow", "min", "num"]}
/>
{/* Cloudflare Turnstile Captcha */}
{CLOUDFLARE_SITE_ID ? (
<TurnstileCaptcha
appearance="interaction-only"
onVerify={(token) => {
formMethods.setValue("cfToken", token);
}}
/>
) : null}
<CheckboxField
onChange={() => handleConsentChange(COOKIE_CONSENT)}
description={t("cookie_consent_checkbox")}
@@ -375,6 +397,9 @@ export default function Signup({
!!formMethods.formState.errors.email ||
!formMethods.getValues("email") ||
!formMethods.getValues("password") ||
(CLOUDFLARE_SITE_ID &&
!process.env.NEXT_PUBLIC_IS_E2E &&
!formMethods.getValues("cfToken")) ||
isSubmitting ||
usernameTaken
}>
@@ -497,14 +522,14 @@ export default function Signup({
className="text-emphasis hover:underline"
href={`${WEBSITE_URL}/terms`}
target="_blank">
<a>Terms</a>
Terms
</Link>{" "}
and{" "}
<Link
className="text-emphasis hover:underline"
href={`${WEBSITE_URL}/privacy`}
target="_blank">
<a>Privacy Policy</a>
Privacy Policy
</Link>
.
</Trans>
+6 -5
View File
@@ -25,6 +25,7 @@ test.describe("Signup Flow Test", async () => {
});
await page.goto("/signup");
await page.waitForLoadState("networkidle");
const alertMessage = "Username or email is already taken";
@@ -51,6 +52,7 @@ test.describe("Signup Flow Test", async () => {
});
await page.goto("/signup");
await page.waitForLoadState("networkidle");
const alertMessage = "Username or email is already taken";
@@ -81,6 +83,7 @@ test.describe("Signup Flow Test", async () => {
// Signup with premium username name
await page.goto("/signup");
await page.waitForLoadState("networkidle");
// Fill form
await page.locator('input[name="username"]').fill("rock");
@@ -108,6 +111,7 @@ test.describe("Signup Flow Test", async () => {
});
await page.goto("/signup");
await page.waitForLoadState("networkidle");
// Fill form
await page.locator('input[name="username"]').fill(userToCreate.username);
@@ -115,10 +119,7 @@ test.describe("Signup Flow Test", async () => {
await page.locator('input[name="password"]').fill(userToCreate.password);
await page.click('button[type="submit"]');
await page.waitForLoadState("networkidle");
// Find the newly created user and add it to the fixture store
const newUser = await users.set(userToCreate.email);
expect(newUser).not.toBeNull();
await page.waitForURL("/auth/verify-email**");
// Check that the URL matches the expected URL
expect(page.url()).toContain("/auth/verify-email");
@@ -177,8 +178,8 @@ test.describe("Signup Flow Test", async () => {
});
const signupUrlWithToken = `/signup?token=${token}`;
await page.goto(signupUrlWithToken);
await page.waitForLoadState("networkidle");
const usernameField = page.locator('input[name="username"]');
const emailField = page.locator('input[name="email"]');