Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
💄 Auto-continue email login once Turnstile succeeds (#2706)
Luke Vella976ae1780ee4
diff --git a/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx b/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsxindex c0702c04b..5603f66ab 100644--- a/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx+++ b/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx@@ -48,11 +48,7 @@ export function LoginWithEmailForm({const loginWithEmailSchema = useLoginWithEmailSchema();const searchParams = useSearchParams();const [showPasswordField, setShowPasswordField] = React.useState(false);- const [showCaptcha, setShowCaptcha] = React.useState(false);const turnstileRef = React.useRef<TurnstileInstance>(null);- const [turnstileToken, setTurnstileToken] = React.useState<string | null>(- null,- );const form = useForm({defaultValues: {identifier: "",@@ -66,142 +62,159 @@ export function LoginWithEmailForm({const getLoginMethod = trpc.auth.getLoginMethod.useMutation();const isPasswordLogin = showPasswordField && !!form.watch("password");- return (- <Form {...form}>- <form- className="space-y-4"- onSubmit={handleSubmit(async ({ identifier, password }) => {- const validatedRedirectTo = validateRedirectUrl(- searchParams?.get("redirectTo"),- );+ const submit = async ({+ identifier,+ password,+ }: {+ identifier: string;+ password?: string;+ }) => {+ const validatedRedirectTo = validateRedirectUrl(+ searchParams?.get("redirectTo"),+ );- if (password) {- const res = await authClient.signIn.email({- email: identifier,- password,+ if (password) {+ const res = await authClient.signIn.email({+ email: identifier,+ password,+ });++ if (res.error) {+ switch (res.error.code) {+ case "INVALID_EMAIL_OR_PASSWORD":+ form.setError("password", {+ message: t("passwordOrEmailIncorrect", {+ defaultValue: "Invalid email or password",+ }),+ });+ break;+ case "BANNED_USER":+ form.setError("identifier", {+ message: t("authErrorsUserBanned", {+ defaultValue:+ "This account has been banned. Please contact support if you believe this is an error.",+ }),+ });+ break;+ default:+ form.setError("password", {+ message: res.error.message,});+ break;+ }+ return;+ }- if (res.error) {- switch (res.error.code) {- case "INVALID_EMAIL_OR_PASSWORD":- form.setError("password", {- message: t("passwordOrEmailIncorrect", {- defaultValue: "Invalid email or password",- }),- });- break;- case "BANNED_USER":- form.setError("identifier", {- message: t("authErrorsUserBanned", {- defaultValue:- "This account has been banned. Please contact support if you believe this is an error.",- }),- });- break;- default:- form.setError("password", {- message: res.error.message,- });- break;- }- return;- }+ window.location.href = validatedRedirectTo ?? "/";- window.location.href = validatedRedirectTo ?? "/";+ return;+ }- return;- }+ if (!showPasswordField) {+ const res = await getLoginMethod.mutateAsync({+ email: identifier,+ });- if (!showPasswordField) {- const res = await getLoginMethod.mutateAsync({- email: identifier,- });+ if (res.method === "credential") {+ // show password field+ setShowPasswordField(true);+ return;+ }+ }- if (res.method === "credential") {- // show password field- setShowPasswordField(true);- return;- }- }+ // The OTP send is captcha-gated. The widget starts solving in the+ // background on mount, so this usually resolves instantly; if+ // Cloudflare demands interaction the widget becomes visible and we+ // wait here while the button shows its loading state.+ let captchaToken: string | undefined;+ if (isTurnstileEnabled) {+ try {+ captchaToken = await turnstileRef.current?.getResponsePromise(120_000);+ } catch {+ form.setError("root", {+ message: t("captchaFailed", {+ defaultValue: "Verification failed. Please try again.",+ }),+ });+ turnstileRef.current?.reset();+ return;+ }+ }- // The OTP send is captcha-gated. Reveal the widget on the first- // attempt and wait for a token before sending.- if (isTurnstileEnabled && !turnstileToken) {- setShowCaptcha(true);- return;- }+ try {+ // When registration is enabled a "sign-in" OTP either signs+ // into an existing account or creates one on verification, so+ // known and unknown emails behave identically. When it's+ // disabled, "email-verification" only reaches existing users.+ const res = await authClient.emailOtp.sendVerificationOtp({+ email: identifier,+ type: isRegistrationEnabled ? "sign-in" : "email-verification",+ fetchOptions: captchaToken+ ? {+ headers: {+ "x-captcha-response": captchaToken,+ },+ }+ : undefined,+ });- try {- // When registration is enabled a "sign-in" OTP either signs- // into an existing account or creates one on verification, so- // known and unknown emails behave identically. When it's- // disabled, "email-verification" only reaches existing users.- const res = await authClient.emailOtp.sendVerificationOtp({- email: identifier,- type: isRegistrationEnabled ? "sign-in" : "email-verification",- fetchOptions: turnstileToken- ? {- headers: {- "x-captcha-response": turnstileToken,- },- }- : undefined,+ if (res.error) {+ switch (res.error.code) {+ case "MISSING_RESPONSE":+ case "VERIFICATION_FAILED":+ form.setError("root", {+ message: t("captchaFailed", {+ defaultValue: "Verification failed. Please try again.",+ }),+ });+ break;+ case "EMAIL_BLOCKED":+ form.setError("identifier", {+ message: t("authErrorsEmailBlocked"),});+ break;+ case "TEMPORARY_EMAIL_NOT_ALLOWED":+ form.setError("identifier", {+ message: t("temporaryEmailNotAllowed"),+ });+ break;+ case "BANNED_USER":+ form.setError("identifier", {+ message: t("authErrorsUserBanned", {+ defaultValue:+ "This account has been banned. Please contact support if you believe this is an error.",+ }),+ });+ break;+ default:+ form.setError("identifier", {+ message: res.error.message,+ });+ break;+ }+ return;+ }- if (res.error) {- switch (res.error.code) {- case "MISSING_RESPONSE":- case "VERIFICATION_FAILED":- form.setError("root", {- message: t("captchaFailed", {- defaultValue: "Verification failed. Please try again.",- }),- });- break;- case "EMAIL_BLOCKED":- form.setError("identifier", {- message: t("authErrorsEmailBlocked"),- });- break;- case "TEMPORARY_EMAIL_NOT_ALLOWED":- form.setError("identifier", {- message: t("temporaryEmailNotAllowed"),- });- break;- case "BANNED_USER":- form.setError("identifier", {- message: t("authErrorsUserBanned", {- defaultValue:- "This account has been banned. Please contact support if you believe this is an error.",- }),- });- break;- default:- form.setError("identifier", {- message: res.error.message,- });- break;- }- return;- }+ await setVerificationEmail(identifier);- await setVerificationEmail(identifier);+ router.push(+ `/login/verify${+ validatedRedirectTo+ ? `?redirectTo=${encodeURIComponent(validatedRedirectTo)}`+ : ""+ }`,+ );+ } finally {+ // Tokens are single-use; start a fresh solve for any retry.+ if (isTurnstileEnabled) {+ turnstileRef.current?.reset();+ }+ }+ };- router.push(- `/login/verify${- validatedRedirectTo- ? `?redirectTo=${encodeURIComponent(validatedRedirectTo)}`- : ""- }`,- );- } finally {- if (isTurnstileEnabled) {- setTurnstileToken(null);- turnstileRef.current?.reset();- }- }- })}- >+ return (+ <Form {...form}>+ <form className="space-y-4" onSubmit={handleSubmit(submit)}><FormFieldcontrol={form.control}name="identifier"@@ -268,23 +281,16 @@ export function LoginWithEmailForm({{form.formState.errors.root?.message ? (<FormMessage>{form.formState.errors.root.message}</FormMessage>) : null}- {showCaptcha && isTurnstileEnabled && turnstileSiteKey ? (+ {isTurnstileEnabled && turnstileSiteKey ? (<Turnstileref={turnstileRef}siteKey={turnstileSiteKey}options={{language: i18n.language,size: "flexible",- }}- onSuccess={(token) => {- setTurnstileToken(token);- }}- onError={() => {- setTurnstileToken(null);- }}- onExpire={() => {- setTurnstileToken(null);- turnstileRef.current?.reset();+ // Solves invisibly in the background; only shows up when+ // Cloudflare requires an interactive challenge.+ appearance: "interaction-only",}}/>) : null}@@ -292,7 +298,6 @@ export function LoginWithEmailForm({<Buttonsize="xl"loading={form.formState.isSubmitting}- disabled={showCaptcha && !isPasswordLogin && !turnstileToken}type="submit"className="w-full"variant="primary"diff --git a/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx b/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsxindex 13fbc27e4..f6ed43a7c 100644--- a/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx+++ b/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx@@ -178,6 +178,9 @@ export function RsvpVerifyEmail({options={{language: i18n.language,size: "flexible",+ // Solves invisibly in the background; only shows up when+ // Cloudflare requires an interactive challenge.+ appearance: "interaction-only",}}onSuccess={(token) => {void sendOtp(token);