Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore(auth): introduce two-step sign-up that redirects to sso (#10610)

Marc Klingen8844cef73dbc
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index f7f2af3e26..ff05e93fc8 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -105,6 +105,7 @@ const events = {
"mixpanel_form_submitted",
],
sign_in: ["cloud_region_switch", "button_click"],
+ sign_up: ["button_click"],
auth: ["reset_password_email_requested", "update_password_form_submit"],
playground: [
"execute_button_click",
diff --git a/web/src/pages/auth/sign-up.tsx b/web/src/pages/auth/sign-up.tsx
index 7734bb6cba..15558d4df6 100644
--- a/web/src/pages/auth/sign-up.tsx
+++ b/web/src/pages/auth/sign-up.tsx
@@ -14,7 +14,7 @@ import { signIn } from "next-auth/react";
import Head from "next/head";
import Link from "next/link";
import { useForm } from "react-hook-form";
-import type * as z from "zod/v4";
+import * as z from "zod/v4";
import { env } from "@/src/env.mjs";
import { useState } from "react";
import { LangfuseIcon } from "@/src/components/LangfuseLogo";
@@ -31,10 +31,14 @@ import { Turnstile } from "@marsidev/react-turnstile";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { useRouter } from "next/router";
import DOMPurify from "dompurify";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import useLocalStorage from "@/src/components/useLocalStorage";
// Use the same getServerSideProps function as src/pages/auth/sign-in.tsx
export { getServerSideProps } from "@/src/pages/auth/sign-in";
+type NextAuthProvider = NonNullable<Parameters<typeof signIn>[0]>;
+
export default function SignIn({
authProviders,
runningOnHuggingFaceSpaces,
@@ -42,6 +46,7 @@ export default function SignIn({
useHuggingFaceRedirect(runningOnHuggingFaceSpaces);
const { isLangfuseCloud, region } = useLangfuseCloudRegion();
const router = useRouter();
+ const capture = usePostHogClientCapture();
// Read query params for targetPath and email pre-population
const queryTargetPath = router.query.targetPath as string | undefined;
@@ -66,8 +71,21 @@ export default function SignIn({
);
const [formError, setFormError] = useState<string | null>(null);
+
+ // Two-step login flow: ask for email first, detect SSO, then either redirect to SSO or reveal password field.
+ // Skip this flow when no SSO is configured - show password field immediately
+ const [showPasswordStep, setShowPasswordStep] = useState<boolean>(
+ !authProviders.sso,
+ );
+ const [continueLoading, setContinueLoading] = useState<boolean>(false);
+ const [lastUsedAuthMethod, setLastUsedAuthMethod] =
+ useLocalStorage<NextAuthProvider | null>(
+ "langfuse_last_used_auth_method",
+ null,
+ );
+
const form = useForm({
- resolver: zodResolver(signupSchema),
+ resolver: showPasswordStep ? zodResolver(signupSchema) : undefined,
defaultValues: {
name: "",
email: emailParam ?? "",
@@ -75,6 +93,82 @@ export default function SignIn({
},
});
+ async function handleContinue() {
+ setContinueLoading(true);
+ setFormError(null);
+ form.clearErrors();
+
+ // Ensure email is valid before hitting the API
+ // We use z.string().email() manually because we don't use the full schema resolver in the first step
+ // or we could just trigger validation for the email field only
+ const emailValue = form.getValues("email");
+ // Basic check using zod directly or trigger
+ // Using trigger("email") might validate against the full schema if we don't be careful,
+ // but since we conditionally set the resolver, it might be tricky.
+ // Simplest is manual check here matching what sign-in does.
+ // Note: signupSchema has name and password as required, so trigger() would fail on those if using full schema.
+
+ // Manual email validation to match sign-in behavior
+ // Although signupSchema.shape.email is ZodString, let's just use a new Zod check for simplicity and robustness
+ const emailSchema = z.string().email();
+ const emailResult = emailSchema.safeParse(emailValue);
+
+ if (!emailResult.success) {
+ form.setError("email", {
+ message: "Invalid email address",
+ });
+ setContinueLoading(false);
+ return;
+ }
+
+ // Extract domain and check whether SSO is configured for it
+ const domain = emailResult.data.split("@")[1]?.toLowerCase();
+
+ try {
+ const res = await fetch(
+ `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/auth/check-sso`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ domain }),
+ },
+ );
+
+ if (res.ok) {
+ // Enterprise SSO found – redirect straight away
+ const { providerId } = await res.json();
+ capture("sign_up:button_click", { provider: "sso_auto" });
+
+ // Store the SSO provider as the last used auth method
+ setLastUsedAuthMethod(providerId as NextAuthProvider);
+
+ void signIn(providerId);
+ return; // stop further execution – page redirect expected
+ }
+
+ // No SSO – fall back to password step
+ setShowPasswordStep(true);
+
+ // Auto-focus password input when password step becomes visible
+ setTimeout(() => {
+ // Find and focus the name input (since it's the first new field) or password?
+ // Plan says "name + password fields". Usually Name is first in Sign Up.
+ // Let's focus Name.
+ const nameInput = document.querySelector(
+ 'input[name="name"]',
+ ) as HTMLInputElement;
+ if (nameInput) {
+ nameInput.focus();
+ }
+ }, 100);
+ } catch (error) {
+ console.error(error);
+ setFormError("Unable to check SSO configuration. Please try again.");
+ } finally {
+ setContinueLoading(false);
+ }
+ }
+
async function onSubmit(values: z.infer<typeof signupSchema>) {
try {
setFormError(null);
@@ -144,21 +238,30 @@ export default function SignIn({
<form
className="space-y-6"
// eslint-disable-next-line @typescript-eslint/no-misused-promises
- onSubmit={form.handleSubmit(onSubmit)}
+ onSubmit={
+ showPasswordStep
+ ? form.handleSubmit(onSubmit)
+ : (e) => {
+ e.preventDefault();
+ void handleContinue();
+ }
+ }
>
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Name</FormLabel>
- <FormControl>
- <Input placeholder="Jane Doe" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
+ {showPasswordStep && (
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Input placeholder="Jane Doe" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
<FormField
control={form.control}
name="email"
@@ -172,30 +275,40 @@ export default function SignIn({
</FormItem>
)}
/>
- <FormField
- control={form.control}
- name="password"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Password</FormLabel>
- <FormControl>
- <PasswordInput {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
+ {showPasswordStep && (
+ <FormField
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Password</FormLabel>
+ <FormControl>
+ <PasswordInput {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
<Button
type="submit"
className="w-full"
- loading={form.formState.isSubmitting}
+ loading={
+ showPasswordStep
+ ? form.formState.isSubmitting
+ : continueLoading
+ }
disabled={
- env.NEXT_PUBLIC_TURNSTILE_SITE_KEY !== undefined &&
- turnstileToken === undefined
+ (env.NEXT_PUBLIC_TURNSTILE_SITE_KEY !== undefined &&
+ showPasswordStep &&
+ turnstileToken === undefined) ||
+ (showPasswordStep
+ ? false // Form validation handles this via handleSubmit
+ : form.watch("email") === "")
}
data-testid="submit-email-password-sign-up-form"
>
- Sign up
+ {showPasswordStep ? "Sign up" : "Continue"}
</Button>
{formError ? (
<div className="text-center text-sm font-medium text-destructive">
@@ -204,24 +317,32 @@ export default function SignIn({
) : null}
</form>
</Form>
- <SSOButtons authProviders={authProviders} action="sign up" />
+ <SSOButtons
+ authProviders={authProviders}
+ action="sign up"
+ lastUsedMethod={lastUsedAuthMethod}
+ onProviderSelect={setLastUsedAuthMethod}
+ />
{
// Turnstile exists copy-paste also on sign-up.tsx
- env.NEXT_PUBLIC_TURNSTILE_SITE_KEY !== undefined && (
- <>
- <Divider className="text-muted-foreground" />
- <Turnstile
- siteKey={env.NEXT_PUBLIC_TURNSTILE_SITE_KEY}
- options={{
- theme: "light",
- action: "sign-in",
- cData: turnstileCData,
- }}
- className="mx-auto"
- onSuccess={setTurnstileToken}
- />
- </>
- )
+ // Only show turnstile when we are on the password step (final submission)
+ // if SSO is enabled. If SSO is disabled, showPasswordStep is true, so it shows.
+ env.NEXT_PUBLIC_TURNSTILE_SITE_KEY !== undefined &&
+ showPasswordStep && (
+ <>
+ <Divider className="text-muted-foreground" />
+ <Turnstile
+ siteKey={env.NEXT_PUBLIC_TURNSTILE_SITE_KEY}
+ options={{
+ theme: "light",
+ action: "sign-in",
+ cData: turnstileCData,
+ }}
+ className="mx-auto"
+ onSuccess={setTurnstileToken}
+ />
+ </>
+ )
}
<p className="mt-10 text-center text-sm text-muted-foreground">
Already have an account?{" "}