🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import { toast } from '@lobehub/ui';
import { useForm } from '@lobehub/ui/form';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useSearchParams } from 'react-router';
import type { CheckUserResponseData } from '@/app/(backend)/api/auth/check-user/route';
import type { ResolveUsernameResponseData } from '@/app/(backend)/api/auth/resolve-username/route';
import { useBusinessSignin } from '@/business/client/hooks/useBusinessSignin';
import { useAuthAgreement } from '@/features/AuthShell/AuthAgreement';
import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';
import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';
import { requestPasswordReset, signIn } from '@/libs/better-auth/auth-client';
import { normalizeProviderId } from '@/libs/better-auth/utils/client';
import {
buildOnboardingRedirectUrl,
sanitizeRedirectPath,
toAbsoluteAuthCallbackUrl,
} from '@/utils/onboardingRedirect';
import { translateAuthError } from '../utils/translateAuthError';
import { EMAIL_REGEX, USERNAME_REGEX } from './SignInEmailStep';
const LAST_AUTH_PROVIDER_KEY = 'lobehub:auth:last-provider:v1';
// Better Auth returns FORBIDDEN for several sign-in rejections (banned user,
// access denied). Only the dedicated EMAIL_NOT_VERIFIED code means the account
// is valid but needs to verify its address, so only that one goes to
// /verify-email; every other 403 stays on the password field as an error.
const isEmailNotVerifiedError = (error?: unknown) =>
(error as { code?: string } | null | undefined)?.code === 'EMAIL_NOT_VERIFIED';
type Step = 'email' | 'password' | 'emailSent';
type SentEmailType = 'magicLink' | 'resetPassword';
interface SentEmailInfo {
email: string;
type: SentEmailType;
}
interface SignInFormValues {
email: string;
password: string;
}
interface ResolvedEmailResult {
email: string;
identifierType: 'email' | 'username';
}
export const useSignIn = () => {
const { t } = useTranslation(['auth', 'authError']);
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const sessionExpired = searchParams.get('reason') === 'sessionExpired';
const enableMagicLink = useAuthServerConfigStore((s) => s.serverConfig.enableMagicLink || false);
const disableEmailPassword = useAuthServerConfigStore(
(s) => s.serverConfig.disableEmailPassword || false,
);
const enableBusinessFeatures = useAuthServerConfigStore(
(s) => s.serverConfig.enableBusinessFeatures || false,
);
const { agreementChecked, continueWithAgreement, setAgreementChecked } = useAuthAgreement();
const form = useForm<SignInFormValues>({
initialValues: { email: '', password: '' },
onSubmit: (values) => {
if (step === 'password') {
void handleSignIn(values);
return;
}
continueWithAgreement(() => {
void handleCheckUser(values);
});
},
});
const [loading, setLoading] = useState(false);
// Locks the email-dispatch actions (magic link / password reset / resend) so a
// slow network can't be double-clicked into multiple emails.
const [sending, setSending] = useState(false);
const [socialLoading, setSocialLoading] = useState<string | null>(null);
/** Provider whose sign-in just failed; the email step explains it under the provider buttons */
const [socialErrorProvider, setSocialErrorProvider] = useState<string | null>(null);
/**
* Failure of an email-dispatch action (sign-in link, password reset, resend). Shown next
* to the link or button that triggered it rather than as a corner toast.
*/
const [sendError, setSendError] = useState('');
const [step, setStep] = useState<Step>('email');
const [email, setEmail] = useState('');
const [sentInfo, setSentInfo] = useState<SentEmailInfo | null>(null);
const [isSocialOnly, setIsSocialOnly] = useState(false);
// Read after mount, not during render: this page is prerendered, and a stored
// provider would make the first client render disagree with the document.
const [lastAuthProvider, setLastAuthProvider] = useState<string | null>(null);
const serverConfigInit = useAuthServerConfigStore((s) => s.serverConfigInit);
const oAuthSSOProviders = useAuthServerConfigStore((s) => s.serverConfig.oAuthSSOProviders) || [];
const { getAdditionalData, preSocialSigninCheck, ssoProviders } = useBusinessSignin();
useEffect(() => {
try {
setLastAuthProvider(localStorage.getItem(LAST_AUTH_PROVIDER_KEY));
} catch {
// Private mode and blocked storage both just mean "no last provider".
}
}, []);
useEffect(() => {
const emailParam = searchParams.get('email');
if (emailParam) form.setValue('email', emailParam);
}, [searchParams, form]);
// On the email step the failure belongs to the email field; on the "check your inbox"
// screen it belongs to the Resend button.
const reportSendError = (message: string) => {
if (step === 'email') form.setErrors({ email: message });
else setSendError(message);
};
const handleSendMagicLink = async (targetEmail?: string): Promise<boolean> => {
if (sending) return false;
try {
const emailValue =
targetEmail ||
(await form
.validate(['email'])
.then(({ valid }) => (valid ? form.getValue('email') : null)));
if (!emailValue) return false;
setSending(true);
setSendError('');
const callbackUrl = searchParams.get('callbackUrl') || '/';
const authOrigin = window.location.origin;
const { error } = await signIn.magicLink({
callbackURL: toAbsoluteAuthCallbackUrl(callbackUrl, authOrigin),
email: emailValue,
// First-time magic-link users are signups — land them on onboarding first
newUserCallbackURL: toAbsoluteAuthCallbackUrl(
buildOnboardingRedirectUrl(callbackUrl),
authOrigin,
),
});
if (error) {
console.error('Magic link error:', error);
reportSendError(translateAuthError(error, t) || t('betterAuth.signin.magicLinkFailed'));
return false;
}
// Success is a forward step, not a fleeting toast: land on a persistent
// "check your inbox" screen (ux Act §3.5).
setSentInfo({ email: emailValue, type: 'magicLink' });
setStep('emailSent');
return true;
} catch (error) {
console.error('Magic link error:', error);
reportSendError(t('betterAuth.signin.magicLinkFailed'));
return false;
} finally {
setSending(false);
}
};
const resolveEmailFromIdentifier = async (
identifier: string,
): Promise<ResolvedEmailResult | null> => {
const trimmedIdentifier = identifier.trim();
if (!trimmedIdentifier) return null;
const isEmailIdentifier = EMAIL_REGEX.test(trimmedIdentifier);
if (isEmailIdentifier)
return { email: trimmedIdentifier.toLowerCase(), identifierType: 'email' };
if (!USERNAME_REGEX.test(trimmedIdentifier)) {
form.setErrors({ email: t('betterAuth.errors.emailInvalid') });
return null;
}
try {
const response = await fetch('/api/auth/resolve-username', {
body: JSON.stringify({ username: trimmedIdentifier }),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
});
const data: ResolveUsernameResponseData = await response.json();
if (!response.ok || !data.exists || !data.email) {
form.setErrors({ email: t('betterAuth.errors.usernameNotFound') });
return null;
}
return { email: data.email, identifierType: 'username' };
} catch (error) {
console.error('Error resolving username:', error);
form.setErrors({ email: t('betterAuth.errors.requestFailed') });
return null;
}
};
const handleCheckUser = async (values: Pick<SignInFormValues, 'email'>) => {
setLoading(true);
await trackLoginOrSignupClicked({ spm: 'signin.email_step.submit' });
try {
const resolvedEmail = await resolveEmailFromIdentifier(values.email);
if (!resolvedEmail) return;
const { email: targetEmail, identifierType } = resolvedEmail;
const response = await fetch('/api/auth/check-user', {
body: JSON.stringify({ email: targetEmail }),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
});
const data: CheckUserResponseData = await response.json();
if (!data.exists) {
if (identifierType === 'username') {
form.setErrors({ email: t('betterAuth.errors.usernameNotFound') });
return;
}
const callbackUrl = searchParams.get('callbackUrl') || '/';
const signupParams = new URLSearchParams();
signupParams.set('email', targetEmail);
signupParams.set('callbackUrl', callbackUrl);
const utmSource = searchParams.get('utm_source');
if (utmSource) signupParams.set('utm_source', utmSource);
const referral = searchParams.get('referral');
if (referral) signupParams.set('referral', referral);
navigate(`/signup?${signupParams.toString()}`);
return;
}
setEmail(targetEmail);
if (data.hasPassword) {
setStep('password');
return;
}
if (enableMagicLink) {
await handleSendMagicLink(targetEmail);
return;
}
// User has no password and magic link is disabled, they can only sign in via social
setIsSocialOnly(true);
} catch (error) {
console.error('Error checking user:', error);
form.setErrors({ email: t('betterAuth.errors.requestFailed') });
} finally {
setLoading(false);
}
};
const handleSignIn = async (values: Pick<SignInFormValues, 'password'>) => {
setLoading(true);
await trackLoginOrSignupClicked({ spm: 'signin.password_step.submit' });
try {
const callbackUrl = searchParams.get('callbackUrl') || '/';
const result = await signIn.email(
{
callbackURL: toAbsoluteAuthCallbackUrl(callbackUrl, window.location.origin),
email,
password: values.password,
},
{
onError: (ctx) => {
console.error('Sign in error:', ctx.error);
if (isEmailNotVerifiedError(ctx.error)) {
navigate(
`/verify-email?email=${encodeURIComponent(email)}&callbackUrl=${encodeURIComponent(callbackUrl)}`,
);
}
},
// callbackUrl targets the main app, outside this auth SPA — full page load required
onSuccess: () => {
window.location.href = sanitizeRedirectPath(callbackUrl);
},
},
);
if (result.error && !isEmailNotVerifiedError(result.error)) {
// Wrong password is the most common sign-in failure. Keep the error
// pinned inline on the field (persistent, with retry context) rather
// than a toast that vanishes in 3s (ux Read §1.1 / Same-Page Error).
form.setErrors({ password: result.error.message || t('betterAuth.signin.error') });
}
} catch (error) {
console.error('Sign in error:', error);
form.setErrors({ password: t('betterAuth.errors.requestFailed') });
} finally {
setLoading(false);
}
};
const handleSocialSignIn = async (provider: string) => {
setSocialLoading(provider);
setSocialErrorProvider(null);
const normalizedProvider = normalizeProviderId(provider);
await trackLoginOrSignupClicked({
provider: normalizedProvider,
spm: 'signin.social.click',
});
try {
if (enableBusinessFeatures && !(await preSocialSigninCheck())) {
setSocialLoading(null);
return;
}
try {
localStorage.setItem(LAST_AUTH_PROVIDER_KEY, provider);
} catch {
// Ignore localStorage errors (e.g., quota exceeded, private mode)
}
const callbackUrl = searchParams.get('callbackUrl') || '/';
// First-time OAuth users are signups — land them on onboarding first
const authOrigin = window.location.origin;
const callbackURL = toAbsoluteAuthCallbackUrl(callbackUrl, authOrigin);
const newUserCallbackURL = toAbsoluteAuthCallbackUrl(
buildOnboardingRedirectUrl(callbackUrl),
authOrigin,
);
const additionalData = await getAdditionalData();
const result = await signIn.social({
additionalData,
callbackURL,
newUserCallbackURL,
provider: normalizedProvider,
});
if (result && 'error' in result && result.error) throw result.error;
} catch (error) {
console.error(`${normalizedProvider} sign in error:`, error);
setSocialErrorProvider(provider);
} finally {
setSocialLoading(null);
}
};
const handleBackToEmail = () => {
setStep('email');
setEmail('');
setIsSocialOnly(false);
setSendError('');
// Drop the previous account's password + any inline error. The form
// instance is shared across steps and defaults to preserve, so without this
// the next email's password step remounts pre-filled with the stale value.
form.reset({ ...form.getValues(), password: '' });
};
const handleGoToSignup = () => {
const currentEmail = form.getValue('email');
const callbackUrl = searchParams.get('callbackUrl') || '/';
const params = new URLSearchParams();
if (currentEmail) params.set('email', currentEmail);
params.set('callbackUrl', callbackUrl);
const utmSource = searchParams.get('utm_source');
if (utmSource) params.set('utm_source', utmSource);
const referral = searchParams.get('referral');
if (referral) params.set('referral', referral);
void trackLoginOrSignupClicked({ spm: 'signin.go_to_signup.click' }).finally(() => {
navigate(`/signup?${params.toString()}`);
});
};
// Fire the password-reset email. Returns true on success. Shared by the
// "forgot password" entry and the resend action on the sent screen.
const dispatchPasswordReset = async (targetEmail: string): Promise<boolean> => {
if (sending) return false;
setSending(true);
setSendError('');
try {
// The better-auth client resolves with `{ data, error }` instead of
// throwing, so a failed send would otherwise land on the "email sent" screen.
const { error } = await requestPasswordReset({
email: targetEmail,
redirectTo: toAbsoluteAuthCallbackUrl(
`/reset-password?email=${encodeURIComponent(targetEmail)}`,
window.location.origin,
),
});
if (error) throw error;
return true;
} catch (error) {
console.error('Password reset email error:', error);
setSendError(
translateAuthError(error as { code?: string }, t) ||
t('betterAuth.signin.resetEmailFailed'),
);
return false;
} finally {
setSending(false);
}
};
const handleForgotPassword = async () => {
if (!email || sending) return;
const ok = await dispatchPasswordReset(email);
if (!ok) return;
setSentInfo({ email, type: 'resetPassword' });
setStep('emailSent');
};
const handleResendEmail = async () => {
if (!sentInfo || sending) return;
const ok =
sentInfo.type === 'magicLink'
? await handleSendMagicLink(sentInfo.email)
: await dispatchPasswordReset(sentInfo.email);
if (ok) toast.success(t('betterAuth.signin.emailSent.resent'));
};
// "Use a different email" — always drop back to the email entry so the label
// matches the action (returning to the password step would keep the same email).
const handleBackFromSent = () => {
setSentInfo(null);
handleBackToEmail();
};
const resolvedProviders = enableBusinessFeatures ? ssoProviders : oAuthSSOProviders;
const sortedProviders = lastAuthProvider
? [...resolvedProviders].sort((a, b) => {
if (a === lastAuthProvider) return -1;
if (b === lastAuthProvider) return 1;
return 0;
})
: resolvedProviders;
return {
agreementChecked,
continueWithAgreement,
disableEmailPassword,
email,
form,
handleBackFromSent,
handleBackToEmail,
handleCheckUser,
handleForgotPassword,
handleGoToSignup,
handleResendEmail,
handleSignIn,
handleSocialSignIn,
isSocialOnly,
lastAuthProvider,
loading,
oAuthSSOProviders: sortedProviders,
sendError,
sending,
sessionExpired,
sentInfo,
serverConfigInit: enableBusinessFeatures ? true : serverConfigInit,
setAgreementChecked,
socialErrorProvider,
socialLoading,
step,
};
};